-
Notifications
You must be signed in to change notification settings - Fork 0
/
workerpool_test.go
137 lines (105 loc) · 2.22 KB
/
workerpool_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
127
128
129
130
131
132
133
134
135
136
137
package main
import (
"time"
"testing"
"errors"
)
var (
dummyErr = errors.New("Dummy error")
)
func sleepTask(duration time.Duration) (f func() error) {
f = func() error {
time.Sleep(duration)
return nil
}
return
}
func errorTask(err error) (f func() error) {
f = func() error {
return err
}
return
}
func TestSubmitTask(t *testing.T) {
t.Parallel()
p := NewWorkerPool(1)
p.SubmitFunc(sleepTask(100 * time.Millisecond))
<- p.ResultCh
select {
case <- p.ResultCh:
t.Error("Unexpected task result")
default:
// should have no pending result
}
p.Stop()
if !p.IsStopped() {
t.Error("Worker pool should be closed")
}
}
func TestErrorTask(t *testing.T) {
t.Parallel()
p := NewWorkerPool(1)
p.SubmitFunc(errorTask(dummyErr))
p.Stop()
r := <- p.ResultCh
if r.Err != dummyErr {
t.Error("Expect task error to be set")
}
}
func TestMultiWorker(t *testing.T) {
t.Parallel()
workers := 2
numTasks := workers*2
p := NewWorkerPool(workers)
start := time.Now()
for i := 0; i < numTasks; i++ {
p.SubmitFunc(sleepTask(1 * time.Second))
}
p.Stop()
numResult := 0
done := false
for {
timeout := time.After(100 * time.Millisecond)
select {
case <- p.ResultCh:
numResult = numResult + 1
case <- timeout:
done = true
}
if done {
break
}
}
totalTime := time.Since(start)
if numResult != numTasks {
t.Error("Expect numResult to be", workers, "got", numResult)
}
// each task take 1 second, but since we have multiple workers, we expect
// the total time should be less than that
if totalTime >= (time.Duration(numTasks) * time.Second) {
t.Error("Expect total execution time to be less than", numTasks)
}
}
func TestSubmitError(t *testing.T) {
t.Parallel()
p := NewWorkerPool(1)
ch := make(chan error)
go func() {
for i := 0; i < 5; i++ {
ch <- p.SubmitFunc(sleepTask(1 * time.Second))
}
close(ch)
}()
p.Stop()
// make sure we receive at least one error
hasError := false
for i := range ch {
if i != nil {
hasError = true
break
}
}
if !hasError {
t.Error("Expect to receive error when sending to a stopped worker pool")
}
}