forked from AliyunContainerService/pouch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer_lock_test.go
96 lines (78 loc) · 2.15 KB
/
container_lock_test.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package ctrd
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func Test_containerLock_TrylockWithRetry(t *testing.T) {
l := &containerLock{
ids: make(map[string]struct{}),
}
// basically, if the releaseTimeout < the tryLockTimeout,
// TrylockWithTimeout will lock successfully. If not, it will fail.
runTrylockWithT := func(tryLockTimeout, releaseTimeout time.Duration) bool {
id := "c"
assert.Equal(t, l.Trylock(id), true)
defer l.Unlock(id)
var (
releaseCh = make(chan struct{})
waitCh = make(chan bool)
res bool
)
go func() {
close(releaseCh)
ctx, cancel := context.WithTimeout(context.TODO(), tryLockTimeout)
defer cancel()
waitCh <- l.TrylockWithRetry(ctx, id)
}()
<-releaseCh
time.Sleep(releaseTimeout)
l.Unlock(id)
select {
case <-time.After(3 * time.Second):
t.Fatalf("timeout to get the Trylock result")
case res = <-waitCh:
}
return res
}
assert.Equal(t, true, runTrylockWithT(5*time.Second, 200*time.Millisecond))
assert.Equal(t, false, runTrylockWithT(200*time.Millisecond, 500*time.Millisecond))
}
func Test_containerLock_Trylock(t *testing.T) {
l := &containerLock{
ids: make(map[string]struct{}),
}
assert.Equal(t, len(l.ids), 0)
// lock a new element
ok := l.Trylock("element1")
assert.Equal(t, ok, true)
assert.Equal(t, len(l.ids), 1)
assert.Equal(t, l.ids["element1"], struct{}{})
// lock an existent element
ok = l.Trylock("element1")
assert.Equal(t, ok, false)
assert.Equal(t, len(l.ids), 1)
assert.Equal(t, l.ids["element1"], struct{}{})
// lock another new element
ok = l.Trylock("element2")
assert.Equal(t, ok, true)
assert.Equal(t, len(l.ids), 2)
assert.Equal(t, l.ids["element1"], struct{}{})
}
func Test_containerLock_Unlock(t *testing.T) {
l := &containerLock{
ids: make(map[string]struct{}),
}
// unlock a non-existent element
l.Unlock("non-existent")
assert.Equal(t, len(l.ids), 0)
// lock a new element
ok := l.Trylock("element1")
assert.Equal(t, ok, true)
assert.Equal(t, len(l.ids), 1)
assert.Equal(t, l.ids["element1"], struct{}{})
// unlock an existent element
l.Unlock("element1")
assert.Equal(t, len(l.ids), 0)
}