forked from goraft/raft
-
Notifications
You must be signed in to change notification settings - Fork 1
/
event_dispatcher_test.go
64 lines (57 loc) · 1.66 KB
/
event_dispatcher_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
package raft
import (
"testing"
"github.com/stretchr/testify/assert"
)
// Ensure that we can listen and dispatch events.
func TestDispatchEvent(t *testing.T) {
var count int
dispatcher := newEventDispatcher(nil)
dispatcher.AddEventListener("foo", func(e Event) {
count += 1
})
dispatcher.AddEventListener("foo", func(e Event) {
count += 10
})
dispatcher.AddEventListener("bar", func(e Event) {
count += 100
})
dispatcher.DispatchEvent(&event{typ: "foo", value: nil, prevValue: nil})
assert.Equal(t, 11, count)
}
// Ensure that we can add and remove a listener.
func TestRemoveEventListener(t *testing.T) {
var count int
f0 := func(e Event) {
count += 1
}
f1 := func(e Event) {
count += 10
}
dispatcher := newEventDispatcher(nil)
dispatcher.AddEventListener("foo", f0)
dispatcher.AddEventListener("foo", f1)
dispatcher.DispatchEvent(&event{typ: "foo"})
dispatcher.RemoveEventListener("foo", f0)
dispatcher.DispatchEvent(&event{typ: "foo"})
assert.Equal(t, 21, count)
}
// Ensure that event is properly passed to listener.
func TestEventListener(t *testing.T) {
dispatcher := newEventDispatcher("X")
dispatcher.AddEventListener("foo", func(e Event) {
assert.Equal(t, "foo", e.Type())
assert.Equal(t, "X", e.Source())
assert.Equal(t, 10, e.Value())
assert.Equal(t, 20, e.PrevValue())
})
dispatcher.DispatchEvent(&event{typ: "foo", value: 10, prevValue: 20})
}
// Benchmark the performance of event dispatch.
func BenchmarkEventDispatch(b *testing.B) {
dispatcher := newEventDispatcher(nil)
dispatcher.AddEventListener("xxx", func(e Event) {})
for i := 0; i < b.N; i++ {
dispatcher.DispatchEvent(&event{typ: "foo", value: 10, prevValue: 20})
}
}