-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgroup_test.go
More file actions
91 lines (77 loc) · 1.93 KB
/
group_test.go
File metadata and controls
91 lines (77 loc) · 1.93 KB
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
package worker_test
import (
"context"
"sync/atomic"
"testing"
"time"
"github.com/chapsuk/worker"
. "github.com/smartystreets/goconvey/convey"
)
func TestGroup(t *testing.T) {
Convey("Given empty workers group", t, func() {
wk := worker.NewGroup()
So(wk, ShouldNotBeNil)
Convey("When add 3 workers", func() {
var (
counter int32
res = make(chan struct{})
)
wk.Add(
worker.New(createFakeJob(&counter, res)),
worker.New(createFakeJob(&counter, res)),
worker.New(createFakeJob(&counter, res)),
)
Convey("workers should not be started", func() {
So(atomic.LoadInt32(&counter), ShouldEqual, 0)
})
Convey("When run group with 3 workers", func() {
wk.Run()
for i := 0; i < 3; i++ {
So(readFromChannelWithTimeout(res), ShouldBeTrue)
}
Convey("all workers should be started", func() {
So(atomic.LoadInt32(&counter), ShouldEqual, 3)
})
Convey("When add worker after group run", func() {
wk.Add(worker.New(createFakeJob(&counter, res)))
So(readFromChannelWithTimeout(res), ShouldBeTrue)
Convey("added worker should be executed", func() {
So(atomic.LoadInt32(&counter), ShouldEqual, 4)
})
})
Convey("Stop workers call", func() {
ch := make(chan struct{})
go func() {
wk.Stop()
ch <- struct{}{}
}()
Convey("should not be blocking", func() {
select {
case <-ch:
So("non-blocking", ShouldEqual, "non-blocking")
case <-time.Tick(time.Second):
So("blocking", ShouldEqual, "non-blocking")
}
})
})
})
})
})
}
func createFakeJob(counter *int32, result chan struct{}) worker.Job {
return func(ctx context.Context) {
atomic.AddInt32(counter, 1)
select {
case result <- struct{}{}:
case <-ctx.Done():
}
}
}
func readFromChannelWithTimeout(result chan struct{}) bool {
select {
case <-result:
return true
case <-time.Tick(time.Second):
return false
}
}