-
Notifications
You must be signed in to change notification settings - Fork 35
/
msg_test.go
103 lines (89 loc) · 1.78 KB
/
msg_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
package beehive
import (
"sync"
"testing"
)
func TestMsgChannelQueue(t *testing.T) {
ch := newMsgChannel(7)
ch.enque(msgAndHandler{msg: &msg{}})
if _, ok := ch.deque(); !ok {
t.Errorf("cannot deque")
}
for i := 0; i < 13; i++ {
ch.enque(msgAndHandler{msg: &msg{MsgData: i}})
if ch.len() != i+1 {
t.Errorf("invalid len: actual=%v want=%v", ch.len(), i+1)
}
}
for i := 0; i < 13; i++ {
mh, ok := ch.deque()
if !ok {
t.Errorf("cannot deque the %v'th element", i)
}
if mh.msg.MsgData != i {
t.Errorf("invalid data: actual=%v want=%v", mh.msg.MsgData, i)
}
}
}
func TestMsgChannel(t *testing.T) {
sent := uint(1024 * 10)
ch := newMsgChannel(sent / 10)
in := ch.in()
for i := uint(0); i < sent; i++ {
in <- msgAndHandler{msg: &msg{MsgData: i}}
}
out := ch.out()
for i := uint(0); i < sent; i++ {
mh := <-out
if mh.msg.MsgData != i {
t.Errorf("invalid message: actual=%v want=%v", mh.msg.Data, i)
}
}
}
func TestMsgChannelParallel(t *testing.T) {
sent := uint(1024 * 10)
ch := newMsgChannel(sent / 10)
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
in := ch.in()
for i := uint(0); i < sent; i++ {
in <- msgAndHandler{msg: &msg{MsgData: i}}
}
wg.Done()
}()
go func() {
out := ch.out()
for i := uint(0); i < sent; i++ {
mh := <-out
if mh.msg.MsgData != i {
t.Errorf("invalid message: actual=%v want=%v", mh.msg.Data, i)
}
}
wg.Done()
}()
wg.Wait()
}
func BenchmarkMsgChannel(b *testing.B) {
b.StopTimer()
sent := uint(b.N)
ch := newMsgChannel(1)
wg := sync.WaitGroup{}
wg.Add(2)
b.StartTimer()
go func() {
in := ch.in()
for i := uint(0); i < sent; i++ {
in <- msgAndHandler{}
}
wg.Done()
}()
go func() {
out := ch.out()
for i := uint(0); i < sent; i++ {
<-out
}
wg.Done()
}()
wg.Wait()
}