-
Notifications
You must be signed in to change notification settings - Fork 1
/
parallel_batch_test.go
72 lines (61 loc) · 1.56 KB
/
parallel_batch_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
package incr
import (
"context"
"fmt"
"runtime"
"sync"
"sync/atomic"
"testing"
"github.com/wcharczuk/go-incr/testutil"
)
type arrayIter[A any] struct {
values []A
index int
}
func (a *arrayIter[A]) Next() (v A, ok bool) {
if a.index == len(a.values) {
return
}
v = a.values[a.index]
a.index++
return v, true
}
func Test_parallelBatch(t *testing.T) {
var work []string
for x := 0; x < runtime.NumCPU()<<1; x++ {
work = append(work, fmt.Sprintf("work-%d", x))
}
workIter := &arrayIter[string]{values: work}
seen := make(map[string]struct{})
var seenMu sync.Mutex
err := parallelBatch[string](testContext(), func(_ context.Context, v string) error {
seenMu.Lock()
seen[v] = struct{}{}
seenMu.Unlock()
return nil
}, workIter.Next, runtime.NumCPU())
testutil.NoError(t, err)
testutil.Equal(t, len(work), len(seen))
for x := 0; x < runtime.NumCPU()<<1; x++ {
key := fmt.Sprintf("work-%d", x)
_, hasKey := seen[key]
testutil.Equal(t, true, hasKey)
}
}
func Test_parallelBatch_error(t *testing.T) {
var work []string
for x := 0; x < runtime.NumCPU()<<1; x++ {
work = append(work, fmt.Sprintf("work-%d", x))
}
workIter := &arrayIter[string]{values: work}
var processed uint32
err := parallelBatch[string](testContext(), func(_ context.Context, v string) error {
atomic.AddUint32(&processed, 1)
if v == "work-2" {
return fmt.Errorf("this is only a test")
}
return nil
}, workIter.Next, runtime.NumCPU())
testutil.Error(t, err)
testutil.Equal(t, len(work), processed, fmt.Sprintf("work=%d processed=%d", len(work), processed))
}