-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchan_test.go
57 lines (53 loc) · 1.22 KB
/
chan_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
package pp
import (
"context"
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestChanDivide(t *testing.T) {
ctx := context.Background()
// Since we are obliged to work with channel pointers in this context, we need this tricky function to get
// the casting right.
getCh := func() (chan int, *<-chan int) {
ch := make(chan int, 1)
var recv <-chan int = ch
return ch, &recv
}
t.Run("empty", func(t *testing.T) {
ch, recv := getCh()
step := ChanDivide(recv, func(_ context.Context, i int) error {
return fmt.Errorf("failed")
})
close(ch)
err := step(ctx)
require.NoError(t, err)
})
t.Run("context cancelled", func(t *testing.T) {
ch, recv := getCh()
ctx, cancel := context.WithCancel(ctx)
value := 0
step := ChanDivide(recv, func(_ context.Context, _ int) error {
value = 1
return fmt.Errorf("failed")
})
cancel()
err := step(ctx)
require.NoError(t, err)
require.Equal(t, 0, value)
close(ch)
})
t.Run("success", func(t *testing.T) {
ch, recv := getCh()
value := 0
step := ChanDivide(recv, func(_ context.Context, i int) error {
value = i
return nil
})
ch <- 1
close(ch)
err := step(ctx)
require.NoError(t, err)
require.Equal(t, 1, value)
})
}