forked from creachadair/taskgroup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaskgroup_test.go
300 lines (255 loc) · 6.34 KB
/
taskgroup_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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package taskgroup_test
import (
"context"
"errors"
"math/rand"
"reflect"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/creachadair/taskgroup"
"github.com/fortytw2/leaktest"
)
const numTasks = 64
// randms returns a random duration of up to n milliseconds.
func randms(n int) time.Duration { return time.Duration(rand.Intn(n)) * time.Millisecond }
// busyWork returns a Task that does nothing for n ms and returns err.
func busyWork(n int, err error) taskgroup.Task {
return func() error { time.Sleep(randms(n)); return err }
}
func TestBasic(t *testing.T) {
defer leaktest.Check(t)()
t.Logf("Group value is %d bytes", reflect.TypeOf((*taskgroup.Group)(nil)).Elem().Size())
// Verify that the group works at all.
g := taskgroup.New(nil).Go(busyWork(25, nil))
if err := g.Wait(); err != nil {
t.Errorf("Unexpected task error: %v", err)
}
// Verify that the group can be reused.
g.Go(busyWork(50, nil))
g.Go(busyWork(75, nil))
if err := g.Wait(); err != nil {
t.Errorf("Unexpected task error: %v", err)
}
t.Run("Zero", func(t *testing.T) {
var g taskgroup.Group
g.Go(busyWork(30, nil))
if err := g.Wait(); err != nil {
t.Errorf("Unexpected task error: %v", err)
}
_, run := g.Limit(1)
run(busyWork(60, nil))
if err := g.Wait(); err != nil {
t.Errorf("Unexpected task error: %v", err)
}
})
}
func TestErrorPropagation(t *testing.T) {
defer leaktest.Check(t)()
var errBogus = errors.New("bogus")
g := taskgroup.New(nil).Go(func() error { return errBogus })
if err := g.Wait(); err != errBogus {
t.Errorf("Wait: got error %v, wanted %v", err, errBogus)
}
}
func TestCancellation(t *testing.T) {
defer leaktest.Check(t)()
var errs []error
g := taskgroup.New(taskgroup.Listen(func(err error) {
errs = append(errs, err)
}))
errOther := errors.New("something is wrong")
ctx, cancel := context.WithCancel(context.Background())
var numOK int32
for i := 0; i < numTasks; i++ {
g.Go(func() error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(randms(1)):
return errOther
case <-time.After(randms(1)):
atomic.AddInt32(&numOK, 1)
return nil
}
})
}
cancel()
g.Wait()
var numCanceled, numOther int
for _, err := range errs {
switch err {
case context.Canceled:
numCanceled++
case errOther:
numOther++
default:
t.Errorf("Unexpected error: %v", err)
}
}
t.Logf("Got %d successful tasks, %d cancelled tasks, and %d other errors",
numOK, numCanceled, numOther)
if total := int(numOK) + numCanceled + numOther; total != numTasks {
t.Errorf("Task count mismatch: got %d results, wanted %d", total, numTasks)
}
}
func TestCapacity(t *testing.T) {
defer leaktest.Check(t)()
const maxCapacity = 25
const numTasks = 1492
g, start := taskgroup.New(nil).Limit(maxCapacity)
var p peakValue
var n int32
for i := 0; i < numTasks; i++ {
start(func() error {
p.inc()
defer p.dec()
time.Sleep(2 * time.Millisecond)
atomic.AddInt32(&n, 1)
return nil
})
}
g.Wait()
t.Logf("Total tasks completed: %d", n)
if p.max > maxCapacity {
t.Errorf("Exceeded maximum capacity: got %d, want %d", p.max, maxCapacity)
} else {
t.Logf("Maximum concurrent tasks: %d", p.max)
}
}
func TestRegression(t *testing.T) {
t.Run("WaitRace", func(t *testing.T) {
ready := make(chan struct{})
g := taskgroup.New(nil).Go(func() error {
<-ready
return nil
})
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); g.Wait() }()
go func() { defer wg.Done(); g.Wait() }()
close(ready)
wg.Wait()
})
t.Run("WaitUnstarted", func(t *testing.T) {
defer func() {
if x := recover(); x != nil {
t.Errorf("Unexpected panic: %v", x)
}
}()
g := taskgroup.New(nil)
g.Wait()
})
}
func TestSingleTask(t *testing.T) {
defer leaktest.Check(t)()
sentinel := errors.New("expected value")
t.Run("Early", func(t *testing.T) {
release := make(chan struct{})
s := taskgroup.Go(func() error {
defer close(release)
return sentinel
})
select {
case <-release:
if err := s.Wait(); err != sentinel {
t.Errorf("Wait: got %v, want %v", err, sentinel)
}
case <-time.After(1 * time.Second):
t.Fatal("Timed out waiting for task to finish")
}
})
t.Run("Late", func(t *testing.T) {
release := make(chan error, 1)
s := taskgroup.Go(func() error {
return <-release
})
g := taskgroup.New(nil).Go(taskgroup.NoError(func() {
if err := s.Wait(); err != sentinel {
t.Errorf("Background Wait: got %v, want %v", err, sentinel)
}
}))
release <- sentinel
if err := s.Wait(); err != sentinel {
t.Errorf("Foreground Wait: got %v, want %v", err, sentinel)
}
g.Wait()
})
}
func TestSingleResult(t *testing.T) {
defer leaktest.Check(t)()
release := make(chan struct{})
s := taskgroup.Call(func() (int, error) {
<-release
return 25, nil
})
time.AfterFunc(2*time.Millisecond, func() { close(release) })
res, err := s.Wait().Get()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if res != 25 {
t.Errorf("Result: got %v, want 25", res)
}
}
func TestCollector(t *testing.T) {
var sum int
c := taskgroup.NewCollector(func(v int) { sum += v })
vs := shuffled(15)
g := taskgroup.New(nil)
for i, v := range vs {
v := v
if v > 10 {
// This value should not be accumulated.
g.Go(c.Task(func() (int, error) {
return -100, errors.New("don't add this")
}))
} else if i%2 == 0 {
// A function with an error.
g.Go(c.Task(func() (int, error) { return v, nil }))
} else {
// A function without an error.
g.Go(c.NoError(func() int { return v }))
}
}
g.Wait() // wait for tasks to finish
c.Wait() // wait for collector
if want := (10 * 11) / 2; sum != want {
t.Errorf("Final result: got %d, want %d", sum, want)
}
}
func TestCollector_Stream(t *testing.T) {
var sum int
c := taskgroup.NewCollector(func(v int) { sum += v })
g := taskgroup.New(nil).Go(c.Stream(func(vs chan<- int) error {
for _, v := range shuffled(10) {
vs <- v
}
return nil
}))
if err := g.Wait(); err != nil {
t.Errorf("Unexpected error from group: %v", err)
}
c.Wait()
if want := (10 * 11) / 2; sum != want {
t.Errorf("Final result: got %d, want %d", sum, want)
}
}
type peakValue struct {
μ sync.Mutex
cur, max int
}
func (p *peakValue) inc() {
p.μ.Lock()
p.cur++
if p.cur > p.max {
p.max = p.cur
}
p.μ.Unlock()
}
func (p *peakValue) dec() {
p.μ.Lock()
p.cur--
p.μ.Unlock()
}