-
Notifications
You must be signed in to change notification settings - Fork 210
/
channel_wait.go
71 lines (57 loc) · 1.57 KB
/
channel_wait.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
package testutil
import (
"reflect"
"testing"
"time"
)
func ChannelWaitForValueUpTo(t *testing.T, waitOn interface{}, waitFor time.Duration) interface{} {
cases := make([]reflect.SelectCase, 2)
cases[0] = reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(waitOn),
Send: reflect.Value{},
}
delayChan := time.After(waitFor)
cases[1] = reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(delayChan),
Send: reflect.Value{},
}
idx, v, ok := reflect.Select(cases)
if !ok {
t.Fatal("Channel has been closed")
}
if idx != 0 {
t.Fatalf("No message after waiting %v seconds", waitFor)
}
return v.Interface()
}
const waitForDefault = 10 * time.Second
func ChannelWaitForValue(t *testing.T, waitOn interface{}) interface{} {
return ChannelWaitForValueUpTo(t, waitOn, waitForDefault)
}
func ChannelWaitForCloseUpTo(t *testing.T, waitOn interface{}, waitFor time.Duration) {
cases := make([]reflect.SelectCase, 2)
cases[0] = reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(waitOn),
Send: reflect.Value{},
}
delayChan := time.After(waitFor)
cases[1] = reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(delayChan),
Send: reflect.Value{},
}
idx, v, ok := reflect.Select(cases)
if !ok {
return // Channel closed, everything OK
}
if idx != 0 {
t.Fatalf("channel not closed after waiting %v seconds", waitOn)
}
t.Fatalf("got unexpected message: %v", v.Interface())
}
func ChannelWaitForClose(t *testing.T, waitOn interface{}) {
ChannelWaitForCloseUpTo(t, waitOn, waitForDefault)
}