forked from alash3al/goemitter
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgoemitter_test.go
132 lines (104 loc) · 2.45 KB
/
goemitter_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
package Emitter
import (
"math/rand"
"reflect"
"sync"
"sync/atomic"
"testing"
)
func TestRemoveListener(t *testing.T) {
emitter := Construct()
counter := 0
fn1 := func(args ...interface{}) {
counter++
}
fn2 := func(args ...interface{}) {
counter++
}
emitter.On("testevent", fn1)
emitter.On("testevent", fn2)
emitter.RemoveListener("testevent", fn1)
emitter.EmitSync("testevent")
listenersCount := emitter.ListenersCount("testevent")
expect(t, 1, listenersCount)
expect(t, 1, counter)
}
func TestOnce(t *testing.T) {
emitter := Construct()
counter := 0
fn := func(args ...interface{}) {
counter++
}
emitter.Once("testevent", fn)
emitter.EmitSync("testevent")
emitter.EmitSync("testevent")
expect(t, 1, counter)
}
func TestWildCardSupport(t *testing.T) {
emitter := Construct()
counter := 0
fn1 := func(args ...interface{}) {
counter++
}
emitter.On("testevent", fn1)
emitter.On("test*", fn1)
emitter.On("t*", fn1)
emitter.On("nomatch", fn1)
emitter.EmitSync("testevent")
listenersCount := emitter.ListenersCount("testevent")
expect(t, 3, listenersCount, "wrong listeners count")
expect(t, 3, counter, "wrong fn execution")
}
func TestRandomConcurrentCalls(t *testing.T) {
emitter := Construct()
var counter int32
var err error
randomCallsFn := func() {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
fn1 := func(args ...interface{}) {
atomic.AddInt32(&counter, 1)
}
fn2 := func(args ...interface{}) {
atomic.AddInt32(&counter, 1)
}
events := []string{"event1", "event2", "event3"}
fns := []func(...interface{}){fn1, fn2}
m := map[int]interface{}{}
for i := 0; i < 100; i++ {
eventIdx := int(rand.Int31()) % len(events)
fnIdx := int(rand.Int31()) % len(fns)
key := fnIdx<<4 + eventIdx
action := int(rand.Int31())
if action%3 == 0 {
if _, ok := m[key]; !ok {
emitter.On(events[eventIdx], fns[fnIdx])
m[key] = nil
}
} else if action%7 == 0 {
emitter.RemoveListener(events[eventIdx], fns[fnIdx])
delete(m, key)
} else {
emitter.EmitAsync(events[eventIdx], nil)
}
}
}
wg := sync.WaitGroup{}
for j := 0; j < 10; j++ {
go func() {
wg.Add(1)
randomCallsFn()
wg.Done()
}()
}
wg.Wait()
expect(t, nil, err)
}
func expect(t *testing.T, a interface{}, b interface{}, desc ...string) {
if a != b {
t.Errorf("%v+ -> Expected %v (type %v) - Got %v (type %v)", desc, a, reflect.TypeOf(a), b, reflect.TypeOf(b))
}
}