-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocker_test.go
More file actions
82 lines (68 loc) · 1.84 KB
/
locker_test.go
File metadata and controls
82 lines (68 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package pgutil
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLocker(t *testing.T) {
var (
db = NewTestDB(t)
ctx = context.Background()
)
locker, err := NewTransactionalLocker(db, StringKey("test"))
require.NoError(t, err)
t.Run("sequential", func(t *testing.T) {
require.NoError(t, locker.WithLock(ctx, 125, func(tx DB) error {
return nil
}))
require.NoError(t, locker.WithLock(ctx, 125, func(tx DB) error {
return nil
}))
})
t.Run("concurrent", func(t *testing.T) {
runWithHeldLock := func(f func()) {
var (
signal = make(chan struct{}) // closed when key=125 is acquired
block = make(chan struct{}) // closed when key=125 should be released
errors = make(chan error, 1) // holds acquisition error from goroutine
)
go func() {
defer close(errors)
if err := locker.WithLock(ctx, 125, func(tx DB) error {
close(signal)
<-block
return nil
}); err != nil {
errors <- err
}
}()
<-signal // Wait for key=125 to be acquired by goroutine above
f() // Run test function with held lock
close(block) // Unblock test routine
for err := range errors {
require.NoError(t, err)
}
}
runWithHeldLock(func() {
// Test acquisition of concurrently held lock
acquired, err := locker.TryWithLock(ctx, 125, func(tx DB) error {
return nil
})
require.NoError(t, err)
assert.False(t, acquired)
// Test acquisition of concurrently un-held lock
acquired, err = locker.TryWithLock(ctx, 126, func(tx DB) error {
return nil
})
require.NoError(t, err)
assert.True(t, acquired)
})
// Test acquisition of released lock
acquired, err := locker.TryWithLock(ctx, 125, func(tx DB) error {
return nil
})
require.NoError(t, err)
assert.True(t, acquired)
})
}