Repository navigation
Expand file tree
/
Copy pathparallel_test.go
More file actions
75 lines (68 loc) · 1.66 KB
/
Copy pathparallel_test.go
File metadata and controls
75 lines (68 loc) · 1.66 KB
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
package taskkit
import (
"context"
"sync/atomic"
"testing"
"time"
"github.com/go-sdk/core/errx"
"github.com/go-sdk/core/testx"
)
func TestParallelHonorsLimit(t *testing.T) {
var running atomic.Int64
var maximum atomic.Int64
gate := make(chan struct{})
started := make(chan struct{}, 4)
done := make(chan error, 1)
go func() {
done <- Parallel(context.Background(), []int{1, 2, 3, 4}, func(context.Context, int) error {
current := running.Add(1)
for {
previous := maximum.Load()
if current <= previous || maximum.CompareAndSwap(previous, current) {
break
}
}
started <- struct{}{}
<-gate
running.Add(-1)
return nil
}, WithLimit(2))
}()
for range 2 {
select {
case <-started:
case <-time.After(time.Second):
testx.FailNow(t, "parallel workers did not start")
}
}
close(gate)
testx.NoError(t, <-done)
testx.EqualValues(t, 2, maximum.Load())
}
func TestParallelAggregatesErrorsByInputOrder(t *testing.T) {
first := errx.New("first")
third := errx.New("third")
err := Parallel(context.Background(), []int{0, 1, 2}, func(_ context.Context, value int) error {
switch value {
case 0:
return first
case 2:
return third
default:
return nil
}
}, WithLimit(3))
testx.ErrorIs(t, err, first)
testx.ErrorIs(t, err, third)
testx.ErrorContains(t, err, "parallel item 0")
testx.ErrorContains(t, err, "parallel item 2")
}
func TestParallelRecoversPanic(t *testing.T) {
err := Parallel(context.Background(), []int{1}, func(context.Context, int) error {
panic("failed")
})
testx.ErrorIs(t, err, ErrPanicRecovered)
var panicErr *PanicError
testx.ErrorAs(t, err, &panicErr)
testx.NotEmpty(t, panicErr.Stack)
}