-
Notifications
You must be signed in to change notification settings - Fork 1
/
eventbus_test.go
144 lines (118 loc) · 2.38 KB
/
eventbus_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 eventbus
import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type testEvent struct {
t Topic
}
func newTestEvent() *testEvent {
return &testEvent{}
}
func (e *testEvent) Type() EventType {
return "test"
}
func (e *testEvent) Topic() Topic {
return e.t
}
func (e *testEvent) SetTopic(t Topic) {
e.t = t
}
func TestEventBus_Subscribe(t *testing.T) {
bus := NewEventBus()
var ev1 Topic = "foo"
var ev2 Topic = "bar"
_ = bus.Subscribe(ev1)
_ = bus.Subscribe(ev1)
_ = bus.Subscribe(ev2)
assert.Len(t, bus.topics, 2)
assert.Len(t, bus.topics[ev1].subscribers, 2)
assert.Len(t, bus.topics[ev2].subscribers, 1)
}
func TestEventBus_Unsubscribe(t *testing.T) {
bus := NewEventBus()
var ev1 Topic = "foo"
c := bus.Subscribe(ev1)
assert.Len(t, bus.topics, 1)
assert.Len(t, bus.topics[ev1].subscribers, 1)
assert.NoError(t, bus.Unsubscribe(ev1, c))
assert.Len(t, bus.topics, 0)
}
func TestEventBus_Publish(t *testing.T) {
bus := NewEventBus()
var ev1 Topic = "foo"
e := newTestEvent()
c := bus.Subscribe(ev1)
var wg sync.WaitGroup
wg.Add(1)
go func() {
select {
case evt := <-c:
assert.Equal(t, e, evt)
case <-time.After(time.Second):
assert.Fail(t, "test timed out")
}
wg.Done()
}()
bus.Publish(ev1, e)
wg.Wait()
}
func TestEventBus_Concurrency(t *testing.T) {
bus := NewEventBus()
var ev1 Topic = "foo"
e := newTestEvent()
n := 10
var wg sync.WaitGroup
wg.Add(n)
chans := make([]chan Event, n)
for i := 0; i < n; i++ {
c := bus.Subscribe(ev1)
chans[i] = c
go func() {
select {
case evt := <-c:
assert.Equal(t, e, evt)
case <-time.After(time.Second):
assert.Fail(t, "test timed out")
}
wg.Done()
}()
}
bus.Publish(ev1, e)
wg.Wait()
for _, c := range chans {
go func(ch chan Event) {
assert.NoError(t, bus.Unsubscribe(ev1, ch))
}(c)
}
}
func TestEventBus_ClosedChannel(t *testing.T) {
bus := NewEventBus()
var ev1 Topic = "foo"
e := newTestEvent()
n := 10
var wg sync.WaitGroup
wg.Add(n)
chans := make([]chan Event, n)
for i := 0; i < n; i++ {
c := bus.Subscribe(ev1)
chans[i] = c
go func() {
select {
case evt := <-c:
if evt != nil {
assert.Equal(t, e, evt)
}
case <-time.After(time.Second):
assert.Fail(t, "test timed out")
}
wg.Done()
}()
}
close(chans[5])
bus.Publish(ev1, e)
wg.Wait()
assert.Len(t, bus.topics[ev1].subscribers, n-1)
}