-
Notifications
You must be signed in to change notification settings - Fork 1
/
changen_test.go
95 lines (87 loc) · 1.93 KB
/
changen_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
package goneric
import (
"github.com/stretchr/testify/assert"
"testing"
"time"
)
func TestChanGen(t *testing.T) {
f := ctr{}
ch := make(chan int, 1)
ChanGen(f.Counter, ch)
a := <-ch
b := <-ch
c := <-ch
d := <-ch
assert.Equal(t, []int{1, 2, 3, 4}, []int{a, b, c, d})
}
func TestChanGenN(t *testing.T) {
t.Run("chan open", func(t *testing.T) {
ch := make(chan int, 1)
ChanGenN(3, func(i int) int { return i + 1 }, ch)
a := <-ch
b := <-ch
c := <-ch
var d int
select {
case d = <-ch:
case <-time.After(time.Millisecond * 20):
}
assert.Equal(t, []int{1, 2, 3, 0}, []int{a, b, c, d})
})
t.Run("chan close", func(t *testing.T) {
ch := make(chan int, 1)
ChanGenN(3, func(i int) int { return i + 1 }, ch, true)
data := make([]int, 0)
idx := 0
O:
for {
idx++
select {
case v := <-ch:
data = append(data, v)
case <-time.After(time.Millisecond * 20):
break O
}
if idx > 3 {
break
}
}
assert.Equal(t, []int{1, 2, 3, 0}, data)
})
}
func TestChanGenCloser(t *testing.T) {
t.Run("with closing output channel", func(t *testing.T) {
f := ctr{}
ch := make(chan int, 1)
cl := ChanGenCloser(f.Counter, ch)
_ = <-ch
cl(true)
// first one after channel drains
_ = <-ch
// next one for loop iteration to get to the exit check
_ = <-ch
// this one should be empty
d := <-ch
assert.NotEqual(t, 4, d)
assert.Panics(t, func() { close(ch) }, "make sure out channel is closed")
})
t.Run("without closing output channel", func(t *testing.T) {
f := ctr{}
ch := make(chan int, 1)
cl := ChanGenCloser(f.Counter, ch)
_ = <-ch
cl()
// first one after channel drains
_ = <-ch
// next one for loop iteration to get to the exit check
_ = <-ch
// this one should be empty
var d int
select {
case d = <-ch:
case <-time.After(time.Millisecond * 50):
}
assert.NotEqual(t, 4, d)
assert.NotPanics(t, func() { close(ch) }, "make sure out channel is not closed")
})
}