-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
pool_test.go
97 lines (77 loc) · 1.56 KB
/
pool_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
package workerpool
import (
"fmt"
"sync"
"testing"
)
func TestNew(t *testing.T) {
pool := New(2)
defer pool.Stop()
if pool == nil {
t.Fail()
}
}
func TestRemoveWorker(t *testing.T) {
pool := New(2)
defer pool.Stop()
worker := func(i int) {}
for i := 1; i <= 2; i++ {
if err := pool.AddWorker(worker); err != nil {
t.Fatal(err)
}
}
if err := pool.RemoveWorker(worker); err != nil {
t.Fatal(err)
}
if pool.WorkersNum() != 1 {
t.Fatal("should have one worker left")
}
if err := pool.Delegate(1); err != nil {
t.Fatal(err)
}
}
func TestInvalidWorker(t *testing.T) {
pool := New(2)
defer pool.Stop()
if pool.AddWorker("worker") == nil {
t.Fail()
}
}
func TestWorkers(t *testing.T) {
delegateWorkToWorkers(t, 2, 3, 3) // same workers as jobs
delegateWorkToWorkers(t, 2, 3, 2) // less workers then jobs
delegateWorkToWorkers(t, 2, 3, 5) // more workers than jobs
}
func delegateWorkToWorkers(t *testing.T, poolSize int, jobsAmount int, workersAmount int) {
var wg sync.WaitGroup
pool := New(poolSize)
out := make(chan int, jobsAmount)
worker := func(i int) {
defer wg.Done()
out <- i
}
for i := 1; i <= workersAmount; i++ {
if err := pool.AddWorker(worker); err != nil {
t.Fatal(err)
}
}
wg.Add(jobsAmount)
for i := 1; i <= jobsAmount; i++ {
if err := pool.Delegate(i); err != nil {
t.Fatal(err)
}
}
go func() {
wg.Wait()
close(out)
pool.Stop()
}()
sum := 0
for n := range out {
sum += n
}
if sum == 0 {
fmt.Printf("Delegating job %d to %d workers failed", jobsAmount, workersAmount)
t.Fail()
}
}