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
|
package eventer
import (
"math/rand"
"testing"
"time"
)
func TestChannel(t *testing.T) {
eventer := New()
c := make(Channel, 1)
eventer.RegisterChannel("test", c)
eventer.Post("test", "hello world")
res := <-c
if res.Data.(string) != "hello world" {
t.Error("Expected event with data 'hello world'. Got", res.Data)
}
}
func TestFunction(t *testing.T) {
eventer := New()
var data string
eventer.RegisterFunc("test", func(ev Event) {
data = ev.Data.(string)
})
eventer.Post("test", "hello world")
if data != "hello world" {
t.Error("Expected event with data 'hello world'. Got", data)
}
}
func TestRegister(t *testing.T) {
eventer := New()
c := eventer.Register("test")
eventer.Post("test", "hello world")
res := <-c
if res.Data.(string) != "hello world" {
t.Error("Expected event with data 'hello world'. Got", res.Data)
}
}
func TestOn(t *testing.T) {
eventer := New()
c := make(Channel, 1)
eventer.On("test", c)
var data string
eventer.On("test", func(ev Event) {
data = ev.Data.(string)
})
eventer.Post("test", "hello world")
res := <-c
if res.Data.(string) != "hello world" {
t.Error("Expected channel event with data 'hello world'. Got", res.Data)
}
if data != "hello world" {
t.Error("Expected function event with data 'hello world'. Got", data)
}
}
func TestConcurrentUsage(t *testing.T) {
rand.Seed(time.Now().Unix())
eventer := New()
stop := make(chan struct{})
recv := make(chan int)
poster := func() {
for {
select {
case <-stop:
return
default:
eventer.Post("test", "hi")
}
}
}
listener := func(i int) {
time.Sleep(time.Duration(rand.Intn(99)) * time.Millisecond)
c := eventer.Register("test")
// wait for the first event
<-c
recv <- i
// keep receiving to prevent deadlock
for {
select {
case <-stop:
return
case <-c:
}
}
}
nlisteners := 200
go poster()
for i := 0; i < nlisteners; i++ {
go listener(i)
}
// wait until everyone has been served
for i := 0; i < nlisteners; i++ {
<-recv
}
close(stop)
}
|