-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner_test.go
114 lines (90 loc) · 2.14 KB
/
runner_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
102
103
104
105
106
107
108
109
110
111
112
113
114
package runner_test
import (
"context"
"reflect"
"syscall"
"testing"
"time"
"github.com/raksly/runner"
"github.com/stretchr/testify/assert"
)
func run() {
time.Sleep(time.Second)
}
func runContext(ctx context.Context) {
<-ctx.Done()
}
func assertChan(assert *assert.Assertions, c interface{}, expectClosed bool) {
if expectClosed {
_, ok := reflect.ValueOf(c).Recv()
assert.False(ok)
} else {
chosen, _, _ := reflect.Select([]reflect.SelectCase{
reflect.SelectCase{Dir: reflect.SelectDefault},
reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(c)},
})
assert.Equal(0, chosen)
}
}
func Test2(t *testing.T) {
assert := assert.New(t)
ctx, cancel := context.WithCancel(context.Background())
r := runner.Runner{Ctx: ctx}
c1 := r.Run(run)
c2 := r.RunContext(runContext)
c3 := r.RunOtherContext(ctx, runContext)
c4 := r.RunSigs(syscall.SIGINT)
select {
case <-c1:
case <-c2:
assert.Fail("should not run")
case <-c3:
assert.Fail("should not run")
case <-c4:
assert.Fail("should not run")
}
assertChan(assert, c1, true)
assertChan(assert, c2, false)
assertChan(assert, c3, false)
assertChan(assert, c4, false)
cancel()
r.Wait()
assertChan(assert, c2, true)
assertChan(assert, c3, true)
assertChan(assert, c4, false)
var r2 runner.Runner
r2.Run(func() {})
r2.RunContext(func(ctx context.Context) {
assert.Nil(ctx)
})
r2.Wait()
}
// Keeping Test1 to ensure the old api still works
func Test1(t *testing.T) {
assert := assert.New(t)
ctx, cancel := context.WithCancel(context.Background())
runner := runner.New(ctx)
assert.Equal(ctx, runner.Context())
c1 := runner.Run(run)
c2 := runner.RunContext(runContext)
c3 := runner.RunOtherContext(ctx, runContext)
c4 := runner.RunSigs(syscall.SIGINT)
select {
case <-c1:
case <-c2:
assert.Fail("should not run")
case <-c3:
assert.Fail("should not run")
case <-c4:
assert.Fail("should not run")
}
assertChan(assert, c1, true)
assertChan(assert, c2, false)
assertChan(assert, c3, false)
assertChan(assert, c4, false)
cancel()
runner.Wait()
assertChan(assert, c2, true)
assertChan(assert, c3, true)
assertChan(assert, c4, false)
}