-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathevent_test.go
121 lines (97 loc) · 2.2 KB
/
event_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
package event_test
import (
"fmt"
"testing"
"github.com/gookit/event"
"github.com/gookit/goutil/testutil/assert"
)
type testListener struct {
userData string
}
func (l *testListener) Handle(e event.Event) error {
if ret := e.Get("result"); ret != nil {
str := ret.(string) + fmt.Sprintf(" -> %s(%s)", e.Name(), l.userData)
e.Set("result", str)
} else {
e.Set("result", fmt.Sprintf("handled: %s(%s)", e.Name(), l.userData))
}
return nil
}
type testSubscriber struct {
// ooo
}
func (s *testSubscriber) SubscribedEvents() map[string]any {
return map[string]any{
"e1": event.ListenerFunc(s.e1Handler),
"e2": event.ListenerItem{
Priority: event.AboveNormal,
Listener: event.ListenerFunc(func(e event.Event) error {
return fmt.Errorf("an error")
}),
},
"e3": &testListener{},
}
}
func (s *testSubscriber) e1Handler(e event.Event) error {
e.Set("e1-key", "val1")
return nil
}
type testSubscriber2 struct{}
func (s testSubscriber2) SubscribedEvents() map[string]any {
return map[string]any{
"e1": "invalid",
}
}
type testEvent struct {
name string
data map[string]any
abort bool
}
func (t *testEvent) Name() string {
return t.name
}
func (t *testEvent) Get(key string) any {
return t.data[key]
}
func (t *testEvent) Set(key string, val any) {
t.data[key] = val
}
func (t *testEvent) Add(key string, val any) {
t.data[key] = val
}
func (t *testEvent) Data() map[string]any {
return t.data
}
func (t *testEvent) SetData(m event.M) event.Event {
t.data = m
return t
}
func (t *testEvent) Abort(b bool) {
t.abort = b
}
func (t *testEvent) IsAborted() bool {
return t.abort
}
func TestEvent(t *testing.T) {
e := &event.BasicEvent{}
e.SetName("n1")
e.SetData(event.M{
"arg0": "val0",
})
e.SetTarget("tgt")
e.Add("arg1", "val1")
assert.False(t, e.IsAborted())
e.Abort(true)
assert.True(t, e.IsAborted())
assert.Equal(t, "n1", e.Name())
assert.Equal(t, "tgt", e.Target())
assert.Contains(t, e.Data(), "arg1")
assert.Equal(t, "val0", e.Get("arg0"))
assert.Equal(t, nil, e.Get("not-exist"))
e.Set("arg1", "new val")
assert.Equal(t, "new val", e.Get("arg1"))
e1 := &event.BasicEvent{}
e1.Set("k", "v")
assert.Equal(t, "v", e1.Get("k"))
assert.NotEmpty(t, e1.Clone())
}