-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_emitter_test.go
139 lines (100 loc) · 2.23 KB
/
event_emitter_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
package eventemitter
import (
"math/rand"
"testing"
"time"
)
func Test_EventEmitter_On(t *testing.T) {
rand.Seed(time.Now().UnixNano())
ee := New()
eventX := "x only"
eventY := "y only"
ee.On(eventX, func(args ...any) {})
if len(ee.listeners) != 1 {
t.Errorf("unexpected listener count")
}
ee.On(eventY, func(args ...any) {})
if len(ee.listeners) != 2 {
t.Errorf("unexpected listener count")
}
}
func Test_EventEmitter_Off(t *testing.T) {
ee := New()
eventX := "x"
eventY := "y"
handler := func(...any) {}
ee.On(eventX, handler)
ee.On(eventY, handler)
if len(ee.listeners) != 2 {
t.Errorf("unexpected listener count")
}
ee.Off(eventX, handler)
if len(ee.listeners[eventX]) != 0 {
t.Errorf("unexpected listener count")
}
if len(ee.listeners) != 1 {
t.Errorf("unexpected listener count")
}
ee.Off(eventY, handler)
if len(ee.listeners[eventY]) != 0 {
t.Errorf("unexpected listener count")
}
if len(ee.listeners) != 0 {
t.Errorf("unexpected listener count")
}
}
func Test_EventEmitter_Emit(t *testing.T) {
rand.Seed(time.Now().UnixNano())
ee := New()
eventX := "x only"
eventY := "y only"
eventBoth := "both"
var x, y int
ee.On(eventX, func(args ...any) {
x++
})
ee.On(eventY, func(args ...any) {
y++
})
ee.On(eventBoth, func(args ...any) {
ee.Emit(eventX).Wait()
ee.Emit(eventY).Wait()
})
// Emit eventX and wait for it to complete.
ee.Emit(eventX).Wait()
if x != 1 {
t.Errorf("unexpected value: %v != %v", x, 1)
}
if y != 0 {
t.Errorf("unexpected value: %v != %v", y, 0)
}
// Emit eventY twice and wait for them to complete.
ee.Emit(eventY).Wait()
ee.Emit(eventY).Wait()
if x != 1 {
t.Errorf("unexpected value: %v != %v", x, 1)
}
if y != 2 {
t.Errorf("unexpected value: %v != %v", y, 2)
}
// Emit eventBoth and wait for it to complete.
ee.Emit(eventBoth).Wait()
if x != 2 {
t.Errorf("unexpected value: %v != %v", x, 2)
}
if y != 3 {
t.Errorf("unexpected value: %v != %v", y, 3)
}
}
func Benchmark_EventEmitter(b *testing.B) {
rand.Seed(time.Now().UnixNano())
ee := New()
e1 := "testing"
for idx := 0; idx < b.N; idx++ {
ee.Once(e1, func(...any) {})
}
ee.Emit(e1).Wait()
if len(ee.listeners) > 0 {
b.Error("listener count should be 0")
}
}