-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrap_test.go
More file actions
82 lines (72 loc) · 1.61 KB
/
Copy pathwrap_test.go
File metadata and controls
82 lines (72 loc) · 1.61 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
76
77
78
79
80
81
82
package workerpool
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestWrap(t *testing.T) {
t.Parallel()
p := New(Options{
Capacity: 10,
IdleTimeout: 100 * time.Millisecond,
WaitIfNoWorkersAvailable: true,
})
t.Cleanup(func() { p.WaitDone(context.Background()) })
f := Wrap(p, func(_ context.Context, i int) (int, error) {
time.Sleep(time.Duration(i%10+1) * time.Millisecond)
return i + 1, nil
})
t.Run("sequential", func(t *testing.T) {
t.Parallel()
expect := 0
actual := 0
for i := 0; i < 100; i++ {
ctx := context.Background()
if i%2 == 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
cancel()
}
v, err := f(ctx, i)
if i%2 == 0 {
require.ErrorIs(t, err, context.Canceled)
} else {
require.NoError(t, err)
expect += i + 1
}
actual += v
}
require.Equal(t, expect, actual)
})
t.Run("parallel", func(t *testing.T) {
t.Parallel()
expectAtomic := atomic.Int64{}
actualAtomic := atomic.Int64{}
wg := sync.WaitGroup{}
for i := 0; i < 500; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
ctx := context.Background()
if i%2 == 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
cancel()
}
v, err := f(ctx, i)
if i%2 == 0 {
require.ErrorIs(t, err, context.Canceled)
} else {
require.NoError(t, err)
expectAtomic.Add(int64(i + 1))
}
actualAtomic.Add(int64(v))
}(i)
}
wg.Wait()
require.Equal(t, expectAtomic.Load(), actualAtomic.Load())
})
}