-
Notifications
You must be signed in to change notification settings - Fork 2
/
pool_test.go
104 lines (84 loc) · 1.28 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
98
99
100
101
102
103
104
package pool
import (
"github.com/stretchr/testify/assert"
"sync"
"testing"
)
func TestNewPool(t *testing.T) {
p := NewPool(1, 2)
assert.Equal(t, 1, p.queueSize)
assert.Equal(t, 2, p.numWorkers)
assert.NotNil(t, p.ch)
}
type Summer struct {
sync.RWMutex
Value int
}
func (s *Summer) Plus(n int) {
s.Lock()
s.Value += n
s.Unlock()
}
type PlusUnit struct {
Sum *Summer
Num int
}
func (u PlusUnit) Perform() {
u.Sum.Plus(u.Num)
}
func TestAddBeforeStart(t *testing.T) {
summer := Summer{}
p := NewPool(1, 1)
p.Add(PlusUnit{
Sum: &summer,
Num: 1,
})
p.Close()
assert.Equal(t, 0, summer.Value)
}
func TestSharedData(t *testing.T) {
summer := Summer{}
p := NewPool(1, 1)
p.Start()
p.Add(PlusUnit{
Sum: &summer,
Num: 2,
})
p.Add(PlusUnit{
Sum: &summer,
Num: 3,
})
p.Add(PlusUnit{
Sum: &summer,
Num: 4,
})
p.Close()
assert.Equal(t, 9, summer.Value)
}
type OutChanUnit struct {
Chan chan int
In int
}
func (u OutChanUnit) Perform() {
u.Chan <- 2 * u.In
}
func TestOutputChannel(t *testing.T) {
p := NewPool(5, 5)
ch := make(chan int, 10)
p.Start()
p.Add(OutChanUnit{
Chan: ch,
In: 1,
})
p.Add(OutChanUnit{
Chan: ch,
In: 2,
})
p.Close()
close(ch)
total := 0
for n := range ch {
total += n
}
assert.Equal(t, 6, total)
}