-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblack_test.go
112 lines (102 loc) · 2.14 KB
/
black_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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package sync2_test
import (
"context"
"testing"
"time"
"github.com/mkch/sync2"
)
func TestMutex(t *testing.T) {
g := sync2.NewMutexGroup()
m := g.NewMutex()
var n = 0
m.Lock()
go func() {
defer m.Unlock()
n = 100
}()
m.Lock()
if n != 100 {
t.Fatal()
}
}
func TestLockAll(t *testing.T) {
g := sync2.NewMutexGroup()
m1 := g.NewMutex()
m2 := g.NewMutex()
m1.Lock()
m2.Lock()
t0 := time.Now()
go func() {
time.Sleep(time.Millisecond * 10)
m1.Unlock()
}()
go func() {
time.Sleep(time.Millisecond * 20)
m2.Unlock()
}()
g.LockAll(m1, m2)
if time.Since(t0) < time.Millisecond*20 {
t.Fatal()
}
}
func TestMutexCancel(t *testing.T) {
g := sync2.NewMutexGroup()
m := g.NewMutex()
if err := m.Lock(); err != nil {
t.Fatal(err)
}
go g.Cancel()
if err := m.Lock(); err != sync2.ErrCanceled {
t.Fatal(err)
}
// All locking methods should return the same error
if err := m.Lock(); err != sync2.ErrCanceled {
t.Fatal(err)
}
if err := m.Unlock(); err != sync2.ErrCanceled {
t.Fatal(err)
}
if err := g.LockAll(m, g.NewMutex()); err != sync2.ErrCanceled {
t.Fatal(err)
}
}
func TestMutexCtx(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
g := sync2.NewMutexGroupWithContext(ctx)
m1 := g.NewMutex()
m2 := g.NewMutex()
m1.Lock()
m2.Lock()
cancel()
if err := g.LockAll(m1, m2); err != context.Canceled {
t.Fatal(err)
}
}
func TestMutexMultiCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
g := sync2.NewMutexGroupWithContext(ctx)
m := g.NewMutex()
g.Cancel() // Set cause to sync2.ErrCanceled
cancel() // Nop
time.Sleep(time.Millisecond * 10)
if err := m.Lock(); err != sync2.ErrCanceled {
t.Fatal(err)
}
}
func TestSleep(t *testing.T) {
const d = time.Millisecond * 200
start := time.Now()
if err := sync2.Sleep(context.Background(), d); err != nil {
t.Fatal(err)
}
diff := time.Since(start) - d
if diff < 0 || diff > d/3 {
t.Fatalf("inaccurate sleep %v", diff)
}
ctx, cancel := context.WithTimeout(context.Background(), 0)
defer cancel()
if err := sync2.Sleep(ctx, time.Second); err != context.DeadlineExceeded {
t.Fatal(err)
}
}