-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtaskgroup_test.go
372 lines (317 loc) · 7.67 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package taskgroup_test
import (
"context"
"errors"
"math"
"math/rand/v2"
"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.
var g taskgroup.Group
g.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) {
g := taskgroup.New(nil)
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")
var g taskgroup.Group
g.Go(func() error { return errBogus })
if err := g.Wait(); err != errBogus {
t.Errorf("Wait: got error %v, wanted %v", err, errBogus)
}
g.OnError(func(error) error { return nil }) // discard
g.Go(func() error { return errBogus })
if err := g.Wait(); err != nil {
t.Errorf("Wait: got error %v, wanted nil", err)
}
}
func TestCancellation(t *testing.T) {
defer leaktest.Check(t)()
var errs []error
g := taskgroup.New(func(err error) {
errs = append(errs, err)
})
errOther := errors.New("something is wrong")
ctx, cancel := context.WithCancel(context.Background())
var numOK int32
for range numTasks {
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
// Verify that multiple groups sharing a throttle respect the combined
// capacity limit.
throttle := taskgroup.NewThrottle(maxCapacity)
var g1, g2 taskgroup.Group
start1 := throttle.Limit(&g1)
start2 := throttle.Limit(&g2)
var p peakValue
var n int32
for i := range numTasks {
start := start1
if i%2 == 1 {
start = start2
}
start.Run(func() {
p.inc()
defer p.dec()
time.Sleep(2 * time.Millisecond)
atomic.AddInt32(&n, 1)
})
}
g1.Wait()
g2.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{})
var g taskgroup.Group
g.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)
}
}()
var g taskgroup.Group
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
})
var g taskgroup.Group
g.Run(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 TestWaitMoreTasks(t *testing.T) {
defer leaktest.Check(t)()
var g taskgroup.Group
var results int
coll := taskgroup.Gather(g.Go, func(int) {
results++
})
// Test that if a task spawns more tasks on its own recognizance, waiting
// correctly waits for all of them provided we do not let the group go empty
// before all the tasks are spawned.
var countdown func(int) int
countdown = func(n int) int {
if n > 1 {
// The subordinate task, if there is one, is started before this one
// exits, ensuring the group is kept "afloat".
coll.Run(func() int {
return countdown(n - 1)
})
}
return n
}
coll.Run(func() int { return countdown(15) })
g.Wait()
if results != 15 {
t.Errorf("Got %d results, want 15", results)
}
}
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 TestGatherer(t *testing.T) {
defer leaktest.Check(t)()
g, run := taskgroup.New(nil).Limit(4)
checkWait := func(t *testing.T) {
t.Helper()
if err := g.Wait(); err != nil {
t.Errorf("Unexpected error from Wait: %v", err)
}
}
t.Run("Call", func(t *testing.T) {
var sum int
r := taskgroup.Gather(run, func(v int) {
sum += v
})
for _, v := range rand.Perm(15) {
r.Call(func() (int, error) {
if v > 10 {
return -100, errors.New("don't add this")
}
return v, nil
})
}
g.Wait()
if want := (10 * 11) / 2; sum != want {
t.Errorf("Final result: got %d, want %d", sum, want)
}
})
t.Run("Run", func(t *testing.T) {
var sum int
r := taskgroup.Gather(run, func(v int) {
sum += v
})
for _, v := range rand.Perm(15) {
r.Run(func() int { return v + 1 })
}
checkWait(t)
if want := (15 * 16) / 2; sum != want {
t.Errorf("Final result: got %d, want %d", sum, want)
}
})
t.Run("Report", func(t *testing.T) {
var sum uint32
r := taskgroup.Gather(g.Go, func(v uint32) {
sum |= v
})
for _, i := range rand.Perm(32) {
r.Report(func(report func(v uint32)) error {
for _, v := range rand.Perm(i + 1) {
report(uint32(1 << v))
}
return nil
})
}
checkWait(t)
if sum != math.MaxUint32 {
t.Errorf("Final result: got %d, want %d", sum, math.MaxUint32)
}
})
}
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()
}