Skip to content

Commit f4d545c

Browse files
committed
test: improve TestLockAndDo
1 parent bd2a860 commit f4d545c

File tree

1 file changed

+11
-23
lines changed

1 file changed

+11
-23
lines changed

modules/globallock/globallock_test.go

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88
"os"
99
"sync"
1010
"testing"
11-
"time"
1211

1312
"github.com/stretchr/testify/assert"
1413
"github.com/stretchr/testify/require"
@@ -44,10 +43,7 @@ func TestLockAndDo(t *testing.T) {
4443
}
4544

4645
func testLockAndDo(t *testing.T) {
47-
const (
48-
duration = 2 * time.Second
49-
concurrency = 100
50-
)
46+
const concurrency = 1000
5147

5248
ctx := context.Background()
5349
count := 0
@@ -57,31 +53,23 @@ func testLockAndDo(t *testing.T) {
5753
go func() {
5854
defer wg.Done()
5955
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+
6666
return nil
6767
})
6868
require.NoError(t, err)
6969
}()
7070
}
7171

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-
7872
wg.Wait()
7973

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-
8674
assert.Equal(t, concurrency, count)
8775
}

0 commit comments

Comments
 (0)