-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventcenter_test.go
99 lines (79 loc) · 2.46 KB
/
eventcenter_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
package eventcenter
import (
"fmt"
"sync"
"testing"
"time"
"github.com/agiledragon/gomonkey/v2"
"github.com/gorilla/websocket"
. "github.com/smartystreets/goconvey/convey"
"github.com/tianluoding/eventcenter/eventbus"
)
func TestEventCenter(t *testing.T) {
Convey("Given an EventCenter instance", t, func() {
eb := &eventbus.EventBus{}
center := NewEventCenter(eb)
Convey("When publishing an event", func() {
var called bool
patches := gomonkey.ApplyMethod(eb, "Publish", func(eb *eventbus.EventBus, event eventbus.Event) {
called = true
})
defer patches.Reset()
center.Publish(eventbus.Event{})
So(called, ShouldBeTrue)
})
Convey("When listening and writing to WebSocket", func() {
fakeConn := &websocket.Conn{}
eventCh := make(chan eventbus.Event)
handleFinished := make(chan bool)
msg := &Message{ID: "testID", MsgType: "subscription"}
patches := gomonkey.ApplyMethodReturn(fakeConn, "WriteJSON", nil)
defer patches.Reset()
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
center.listenAndWrite(eventCh, fakeConn, msg, handleFinished)
}()
// Simulate receiving an event
eventCh <- eventbus.Event{}
time.Sleep(10 * time.Millisecond) // Allow time for the goroutine to process the event
close(handleFinished)
wg.Wait()
})
Convey("When listening and writing to WebSocket, handleFinished", func() {
fakeConn := &websocket.Conn{}
eventCh := make(chan eventbus.Event)
handleFinished := make(chan bool)
msg := &Message{ID: "testID", MsgType: "subscription"}
patches := gomonkey.ApplyMethodReturn(fakeConn, "WriteJSON", nil)
defer patches.Reset()
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
center.listenAndWrite(eventCh, fakeConn, msg, handleFinished)
}()
// Simulate receiving an event
eventCh <- eventbus.Event{}
time.Sleep(10 * time.Millisecond) // Allow time for the goroutine to process the event
handleFinished <- true
wg.Wait()
})
Convey("When listening and writing to WebSocket, ReadJSON err", func() {
fakeConn := &websocket.Conn{}
patches := gomonkey.
ApplyMethodReturn(&upgrader, "Upgrade", fakeConn, nil).
ApplyMethodReturn(fakeConn, "Close", nil).
ApplyMethodReturn(fakeConn, "ReadJSON", fmt.Errorf("read error"))
defer patches.Reset()
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
center.HandleWebSocket(nil, nil)
}()
wg.Wait()
})
})
}