-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutex_test.go
97 lines (82 loc) · 1.74 KB
/
mutex_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
97
package main
import (
"context"
"testing"
"time"
)
func assert(t *testing.T, ok bool, msg string, args ...interface{}) {
if !ok {
t.Errorf(msg, args...)
}
}
func TestMutex_Lock(t *testing.T) {
m := NewMutex()
m.Lock()
done := make(chan struct{})
go func() {
m.Lock()
defer m.Unlock()
close(done)
}()
m.Unlock()
<-done
}
func TestMutex_TryLock(t *testing.T) {
m := NewMutex()
m.Lock()
assert(t, !m.TryLock(), "TryLock must return false")
m.Unlock()
assert(t, m.TryLock(), "TryLock must return false")
m.Unlock()
}
func TestMutex_TryLockWith(t *testing.T) {
m := NewMutex()
m.Lock()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
assert(t, !m.TryLockWith(ctx), "TryLockWith must return false")
m.Unlock()
assert(t, m.TryLockWith(context.Background()), "TryLockWith must return true")
m.Unlock()
m.Lock()
done := make(chan struct{})
go func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
ok := m.TryLockWith(ctx)
assert(t, ok, "TryLockWith must return true")
if ok {
defer m.Unlock()
}
close(done)
}()
m.Unlock()
<-done
}
func TestMutex_TryLockTimeout(t *testing.T) {
m := NewMutex()
m.Lock()
assert(t, !m.TryLockTimeout(time.Second), "TryLockWith must return false")
m.Unlock()
assert(t, m.TryLockTimeout(time.Second), "TryLockWith must return true")
m.Unlock()
m.Lock()
done := make(chan struct{})
go func() {
ok := m.TryLockTimeout(time.Second)
assert(t, ok, "TryLockWith must return true")
if ok {
defer m.Unlock()
}
close(done)
}()
m.Unlock()
<-done
}
func TestMutex_Unlock(t *testing.T) {
m := NewMutex()
defer func() {
assert(t, recover() != nil, "unpaired Unlock must panic")
}()
m.Unlock()
}