File tree Expand file tree Collapse file tree 1 file changed +11
-23
lines changed Expand file tree Collapse file tree 1 file changed +11
-23
lines changed Original file line number Diff line number Diff line change 8
8
"os"
9
9
"sync"
10
10
"testing"
11
- "time"
12
11
13
12
"github.com/stretchr/testify/assert"
14
13
"github.com/stretchr/testify/require"
@@ -44,10 +43,7 @@ func TestLockAndDo(t *testing.T) {
44
43
}
45
44
46
45
func testLockAndDo (t * testing.T ) {
47
- const (
48
- duration = 2 * time .Second
49
- concurrency = 100
50
- )
46
+ const concurrency = 1000
51
47
52
48
ctx := context .Background ()
53
49
count := 0
@@ -57,31 +53,23 @@ func testLockAndDo(t *testing.T) {
57
53
go func () {
58
54
defer wg .Done ()
59
55
err := LockAndDo (ctx , "test" , func (ctx context.Context ) error {
60
- select {
61
- case <- ctx .Done ():
62
- return ctx .Err ()
63
- case <- time .After (duration / concurrency ):
64
- count ++
65
- }
56
+ count ++
57
+
58
+ // It's impossible to acquire the lock inner the function
59
+ ok , err := TryLockAndDo (ctx , "test" , func (ctx context.Context ) error {
60
+ assert .Fail (t , "should not acquire the lock" )
61
+ return nil
62
+ })
63
+ assert .False (t , ok )
64
+ assert .NoError (t , err )
65
+
66
66
return nil
67
67
})
68
68
require .NoError (t , err )
69
69
}()
70
70
}
71
71
72
- ok , err := TryLockAndDo (ctx , "test" , func (ctx context.Context ) error {
73
- return nil
74
- })
75
- assert .False (t , ok )
76
- assert .NoError (t , err )
77
-
78
72
wg .Wait ()
79
73
80
- ok , err = TryLockAndDo (ctx , "test" , func (ctx context.Context ) error {
81
- return nil
82
- })
83
- assert .True (t , ok )
84
- assert .NoError (t , err )
85
-
86
74
assert .Equal (t , concurrency , count )
87
75
}
You can’t perform that action at this time.
0 commit comments