-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker_queue_test.go
144 lines (126 loc) · 2.31 KB
/
worker_queue_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
138
139
140
141
142
143
144
package queue
import (
"fmt"
"sync"
"testing"
)
type spy struct {
sync.Mutex
called uint16
}
func newMockJob() (Job, *spy) {
s := &spy{}
return func() JobResult {
s.Lock()
s.called++
s.Unlock()
return Success
}, s
}
func TestQueue(t *testing.T) {
cases := []struct {
capacity uint32
concurrency uint32
enqueue int
calledExpected uint16
}{
{
capacity: 2,
concurrency: 0,
enqueue: 2,
calledExpected: 0,
},
{
capacity: 2,
concurrency: 1,
enqueue: 2,
calledExpected: 2,
},
{
capacity: 2,
concurrency: 2,
enqueue: 500,
calledExpected: 500,
},
}
for i, c := range cases {
t.Run(fmt.Sprintf("EnqueueBlock-%d", i), func(t *testing.T) {
j, s := newMockJob()
q := NewWorkerQueue(c.capacity, c.concurrency)
wg := new(sync.WaitGroup)
for i := 0; i < c.enqueue; i++ {
wg.Add(1)
go func() {
defer wg.Done()
q.EnqueueBlock(j)
}()
}
wg.Wait()
q.CloseAndWait()
s.Lock()
if s.called != c.calledExpected {
t.Errorf("called should be %d but is %d", c.calledExpected, s.called)
}
s.Unlock()
})
}
}
func TestEnqueue(t *testing.T) {
j, s := newMockJob()
q := NewWorkerQueue(2, 0)
failed := 0
for i := 0; i < 4; i++ {
if ok := q.Enqueue(j); !ok {
failed++
}
}
if failed != 2 {
t.Errorf("expected 2 queue failures, got %d", failed)
}
if s.called != 0 {
t.Errorf("called should be 0 but is %d", s.called)
}
<-q.ch
if ok := q.Enqueue(j); !ok {
failed++
}
if failed != 2 {
t.Errorf("expected 2 queue failures, got %d", failed)
}
}
func TestEnqueueBlock(t *testing.T) {
j, s := newMockJob()
q := NewWorkerQueue(2, 0)
outterWg := new(sync.WaitGroup)
innerWg := new(sync.WaitGroup)
mu := new(sync.Mutex)
innerComplete := 0
for i := 0; i < 4; i++ {
outterWg.Add(1)
go func() {
defer outterWg.Done()
innerWg.Add(1)
go func() {
defer innerWg.Done()
q.EnqueueBlock(j)
mu.Lock()
innerComplete++
mu.Unlock()
}()
}()
}
outterWg.Wait()
innerWg.Done()
innerWg.Done()
innerWg.Wait()
s.Lock()
if s.called != 0 {
t.Errorf("called should be 0 but is %d", s.called)
}
s.Unlock()
mu.Lock()
if innerComplete != 2 {
t.Errorf("inner complete should be 2 but is %d", innerComplete)
}
mu.Unlock()
}