-
Notifications
You must be signed in to change notification settings - Fork 0
/
waiter_test.go
145 lines (112 loc) · 2.54 KB
/
waiter_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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package appetizer
import (
"context"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestWaiter_ensureCond(t *testing.T) {
t.Run("condition is set up", func(t *testing.T) {
w := &Waiter{}
cond := sync.NewCond(&w.mu)
w.cond = cond
w.ensureCond()
assert.Equal(t, cond, w.cond)
})
t.Run("exactly once", func(t *testing.T) {
w := &Waiter{}
w.ensureCond()
if assert.NotNil(t, w.cond) {
w.cond = nil
w.ensureCond()
assert.Nil(t, w.cond)
}
})
}
func TestWaiter_Is(t *testing.T) {
w := &Waiter{}
if assert.True(t, w.Is(false)) {
w.ready.Store(true)
assert.True(t, w.Is(true))
}
}
func TestWaiter_Set(t *testing.T) {
t.Run("ready is false", func(t *testing.T) {
w := &Waiter{}
w.Set(false)
assert.Nil(t, w.cond)
})
t.Run("ready is true", func(t *testing.T) {
w := &Waiter{}
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*10)
defer cancel()
go func() {
w.Set(true)
}()
select {
case <-ctx.Done():
t.Fatal("wait should've completed")
case <-w.WaitCh():
}
})
}
func TestWaiter_WaitCh(t *testing.T) {
t.Run("ready", func(t *testing.T) {
w := &Waiter{}
w.Set(true)
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*5)
defer cancel()
select {
case <-ctx.Done():
t.Fatal("wait should've completed")
case <-w.WaitCh():
}
})
t.Run("condition is created", func(t *testing.T) {
w := &Waiter{}
if assert.Nil(t, w.cond) {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*5)
defer cancel()
select {
case <-w.WaitCh():
t.Fatal("wait should've failed")
case <-ctx.Done():
assert.NotNil(t, w.cond)
}
}
})
t.Run("wait", func(t *testing.T) {
w := &Waiter{}
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*5)
defer cancel()
ch := w.WaitCh()
go func() {
<-time.After(time.Millisecond)
w.Set(true)
}()
select {
case <-ctx.Done():
t.Fatal("wait should've completed")
case <-ch:
assert.True(t, w.Is(true))
}
})
}
func TestWaiter_Wait(t *testing.T) {
t.Run("ready", func(t *testing.T) {
w := &Waiter{}
w.Set(true)
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*5)
defer cancel()
assert.NoError(t, w.Wait(ctx))
})
t.Run("timeout", func(t *testing.T) {
w := &Waiter{}
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*5)
defer cancel()
if err := w.Wait(ctx); assert.Error(t, err) {
assert.ErrorIs(t, err, context.DeadlineExceeded)
}
})
}