-
Notifications
You must be signed in to change notification settings - Fork 14
/
worker_test.go
126 lines (111 loc) · 2.25 KB
/
worker_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
122
123
124
125
126
// Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package worker_test
import (
"time"
"github.com/juju/errors"
"github.com/juju/testing"
gc "gopkg.in/check.v1"
"github.com/juju/worker/v4"
)
type WorkerSuite struct {
testing.IsolationSuite
}
var _ = gc.Suite(&WorkerSuite{})
func (*WorkerSuite) TestStop(c *gc.C) {
killed := 0
testErr := errors.New("an error")
w := hookWorker{
kill: func() {
killed++
},
wait: func() error {
c.Check(killed, gc.Equals, 1)
return testErr
},
}
err := worker.Stop(w)
c.Assert(killed, gc.Equals, 1)
c.Assert(err, gc.Equals, testErr)
}
func (*WorkerSuite) TestDead(c *gc.C) {
waiting := make(chan struct{})
w := hookWorker{
wait: func() error {
waiting <- struct{}{}
<-waiting
return nil
},
}
deadCh := worker.Dead(w)
select {
case <-waiting:
case <-time.After(longWait):
c.Fatalf("wait never called")
}
select {
case <-deadCh:
c.Fatalf("received value before worker is dead")
case <-time.After(shortWait):
}
close(waiting)
select {
case <-deadCh:
case <-time.After(longWait):
c.Fatalf("never received on dead channel")
}
}
func (*WorkerSuite) TestDeadWithDeadMethod(c *gc.C) {
deadCh := make(chan struct{})
w := hookWorkerWithDead{
hookWorker: hookWorker{
wait: func() error {
c.Error("wait should not be called")
return nil
},
},
dead: func() <-chan struct{} {
return deadCh
},
}
ch := worker.Dead(w)
c.Assert(ch, gc.Equals, (<-chan struct{})(deadCh))
}
func (*WorkerSuite) TestDeadWithDeadMethodReturningNil(c *gc.C) {
waitCalls, deadCalls := 0, 0
w := hookWorkerWithDead{
hookWorker: hookWorker{
wait: func() error {
waitCalls++
return nil
},
},
dead: func() <-chan struct{} {
deadCalls++
return nil
},
}
ch := worker.Dead(w)
<-ch
c.Assert(waitCalls, gc.Equals, 1)
c.Assert(deadCalls, gc.Equals, 1)
}
// hookWorker implements worker.Worker by
// deferring to its member functions.
type hookWorker struct {
kill func()
wait func() error
}
func (w hookWorker) Kill() {
w.kill()
}
func (w hookWorker) Wait() error {
return w.wait()
}
type hookWorkerWithDead struct {
hookWorker
dead func() <-chan struct{}
}
func (w hookWorkerWithDead) Dead() <-chan struct{} {
return w.dead()
}