-
Notifications
You must be signed in to change notification settings - Fork 0
/
series_test.go
97 lines (86 loc) · 1.81 KB
/
series_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
package async_test
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/ghosind/go-assert"
"github.com/ghosind/go-async"
)
func TestSeries(t *testing.T) {
a := assert.New(t)
seq := make([]int, 0, 5)
tasks := make([]async.AsyncFn, 0, 5)
for i := 0; i < 5; i++ {
n := i
tasks = append(tasks, func() int {
seq = append(seq, n)
return n
})
}
out, err := async.Series(tasks...)
a.NilNow(err)
a.EqualNow(out, [][]any{{0}, {1}, {2}, {3}, {4}})
a.EqualNow(seq, []int{0, 1, 2, 3, 4})
}
func TestSeriesFailure(t *testing.T) {
a := assert.New(t)
expectedErr := errors.New("n = 2")
seq := make([]int, 0, 5)
tasks := make([]async.AsyncFn, 0, 5)
for i := 0; i < 5; i++ {
n := i
tasks = append(tasks, func() (int, error) {
if n == 2 {
return 0, expectedErr
}
seq = append(seq, n)
return n, nil
})
}
out, err := async.Series(tasks...)
a.NotNilNow(err)
a.IsErrorNow(err, expectedErr)
a.EqualNow(out, [][]any{{0, nil}, {1, nil}, {0, expectedErr}, {}, {}})
a.EqualNow(seq, []int{0, 1})
}
func TestSeriesWithContext(t *testing.T) {
a := assert.New(t)
tasks := make([]async.AsyncFn, 0, 5)
timeoutErr := errors.New("timeout")
for i := 0; i < 5; i++ {
tasks = append(tasks, func(ctx context.Context) error {
select {
case <-ctx.Done():
return timeoutErr
default:
time.Sleep(50 * time.Millisecond)
return nil
}
})
}
ctx, canFunc := context.WithTimeout(context.Background(), 75*time.Millisecond)
defer canFunc()
out, err := async.SeriesWithContext(ctx, tasks...)
a.NotNilNow(err)
a.IsErrorNow(err, timeoutErr)
a.EqualNow(out, [][]any{{nil}, {nil}, {timeoutErr}, {}, {}})
}
func ExampleSeries() {
i := 0
async.Series(func() {
fmt.Println(i)
i++
}, func() {
fmt.Println(i)
i++
}, func() {
fmt.Println(i)
i++
})
// Output:
// 0
// 1
// 2
}