-
Notifications
You must be signed in to change notification settings - Fork 13
/
delay_test.go
101 lines (93 loc) · 1.94 KB
/
delay_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
98
99
100
101
package pipeline
import (
"context"
"reflect"
"testing"
"time"
)
func TestDelay(t *testing.T) {
t.Parallel()
const maxTestDuration = time.Second
type args struct {
ctxTimeout time.Duration
duration time.Duration
in []int
}
type want struct {
out []int
open bool
}
for _, test := range []struct {
name string
args args
want want
}{{
name: "out closes after duration when in closes",
args: args{
ctxTimeout: maxTestDuration,
duration: maxTestDuration - 100*time.Millisecond,
in: []int{1},
},
want: want{
out: []int{1},
open: false,
},
}, {
name: "delay is not applied when the context is canceled",
args: args{
ctxTimeout: 10 * time.Millisecond,
duration: maxTestDuration,
in: []int{1, 2, 3, 4, 5},
},
want: want{
out: []int{1, 2, 3, 4, 5},
open: false,
},
}, {
name: "out is delayed by duration",
args: args{
ctxTimeout: maxTestDuration,
duration: maxTestDuration / 4,
in: []int{1, 2, 3, 4, 5},
},
want: want{
out: []int{1, 2, 3, 4},
open: true,
},
}} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
// Create in channel
in := Emit(test.args.in...)
// Create a context with a timeut
ctx, cancel := context.WithTimeout(context.Background(), test.args.ctxTimeout)
defer cancel()
// Start reading from in
delay := Delay(ctx, test.args.duration, in)
timeout := time.After(maxTestDuration)
var isOpen bool
var outs []int
loop:
for {
select {
case i, open := <-delay:
isOpen = open
if !open {
break loop
}
outs = append(outs, i)
case <-timeout:
break loop
}
}
// Expecting the out channel to be open or closed
if test.want.open != isOpen {
t.Errorf("%t != %t", test.want.open, isOpen)
}
// Expecting processed outputs
if !reflect.DeepEqual(test.want.out, outs) {
t.Errorf("%+v != %+v", test.want.out, outs)
}
})
}
}