/
runner_test.go
121 lines (93 loc) · 2.18 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
115
116
117
118
119
120
121
package runner_test
import (
"errors"
"fmt"
"testing"
"time"
"github.com/DanielKrawisz/runner"
)
// A runnable test function.
var goFunc = func(i int, returnErr bool) runner.Runnable {
return runner.Runnable(func(quit <-chan struct{}) error {
out:
for {
select {
case <-quit:
fmt.Println("About to break out of function", i)
break out
}
}
if returnErr {
return errors.New("This is an error.")
}
return nil
})
}
// TestRunner tests starting and stoping the runner twice without errors.
func TestRunner(t *testing.T) {
funcs := []runner.Runnable{goFunc(0, false), goFunc(1, false), goFunc(2, false)}
run := runner.New(funcs)
err := run.Start()
if err != nil {
t.Error("Failed to start: ", err)
}
time.Sleep(time.Second)
run.Stop()
err = run.Start()
if err != nil {
t.Error("Failed to start a second time: ", err)
}
time.Sleep(time.Second)
run.Stop()
}
// TestRunnerErr tests error conditions and ensures that the runner dies.
func TestRunnerErr(t *testing.T) {
funcs := []runner.Runnable{goFunc(0, true), goFunc(1, true), goFunc(2, false)}
run := runner.New(funcs)
err := run.Start()
if err != nil {
t.Error("Failed to start: ", err)
}
time.Sleep(time.Second)
run.Stop()
err = run.Start()
if err == nil {
t.Error("Should fail to start.")
}
time.Sleep(time.Second)
run.Stop()
}
// TestRunnerWait tests whether the Wait function stops after Stop is done and
// doesn't cause a deadlock or race condition.
func TestRunnerWait(t *testing.T) {
funcs := []runner.Runnable{goFunc(0, false), goFunc(1, false), goFunc(2, false)}
run := runner.New(funcs)
err := run.Start()
if err != nil {
t.Error("Failed to start: ", err)
}
startChan := make(chan struct{})
doneWaitChan := make(chan struct{})
doneStopChan := make(chan struct{})
go func() {
<-startChan
run.Wait()
doneWaitChan <- struct{}{}
}()
// This will cause Wait to be called.
startChan <- struct{}{}
time.Sleep(time.Second)
go func() {
<-startChan
run.Stop()
doneStopChan <- struct{}{}
}()
// This will cause Stop to be called.
close(startChan)
select {
case <-doneWaitChan:
t.Error("Wait ended before stop.")
case <-doneStopChan:
}
<-doneWaitChan
}