| 
									
										
										
										
											2021-09-01 22:38:56 +08:00
										 |  |  | //go:build integration
 | 
					
						
							| 
									
										
										
										
											2018-12-11 21:00:09 +08:00
										 |  |  | // +build integration
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | package serverlock | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | import ( | 
					
						
							|  |  |  | 	"context" | 
					
						
							|  |  |  | 	"testing" | 
					
						
							|  |  |  | 	"time" | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2019-05-14 21:38:18 +08:00
										 |  |  | 	"github.com/stretchr/testify/assert" | 
					
						
							| 
									
										
										
										
											2018-12-11 21:00:09 +08:00
										 |  |  | ) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | func TestServerLok(t *testing.T) { | 
					
						
							|  |  |  | 	sl := createTestableServerLock(t) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2019-05-14 21:38:18 +08:00
										 |  |  | 	counter := 0 | 
					
						
							|  |  |  | 	fn := func() { counter++ } | 
					
						
							|  |  |  | 	atInterval := time.Second * 1 | 
					
						
							|  |  |  | 	ctx := context.Background() | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	//this time `fn` should be executed
 | 
					
						
							|  |  |  | 	assert.Nil(t, sl.LockAndExecute(ctx, "test-operation", atInterval, fn)) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	//this should not execute `fn`
 | 
					
						
							|  |  |  | 	assert.Nil(t, sl.LockAndExecute(ctx, "test-operation", atInterval, fn)) | 
					
						
							|  |  |  | 	assert.Nil(t, sl.LockAndExecute(ctx, "test-operation", atInterval, fn)) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	// wait 2 second.
 | 
					
						
							|  |  |  | 	<-time.After(time.Second * 2) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	// now `fn` should be executed again
 | 
					
						
							|  |  |  | 	err := sl.LockAndExecute(ctx, "test-operation", atInterval, fn) | 
					
						
							|  |  |  | 	assert.Nil(t, err) | 
					
						
							|  |  |  | 	assert.Equal(t, counter, 2) | 
					
						
							| 
									
										
										
										
											2018-12-11 21:00:09 +08:00
										 |  |  | } |