-
Notifications
You must be signed in to change notification settings - Fork 5
/
rtm_broker_test.go
83 lines (66 loc) · 1.99 KB
/
rtm_broker_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
package slacker
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gorilla/websocket"
. "github.com/smartystreets/goconvey/convey"
)
var voidConnHandler = func(c *websocket.Conn) {}
func TestRTMBroker(t *testing.T) {
Convey("RTM Broker", t, func() {
Convey("Events() returns RTMEvents on a channel", func() {
server := generateServerWithResponse(`{"type":"message"}`, voidConnHandler)
defer server.Close()
start := &RTMStartResult{URL: server.URL}
broker := NewRTMBroker(start)
err := broker.Connect()
So(err, ShouldBeNil)
select {
case event := <-broker.Events():
So(event.Type, ShouldEqual, "message")
case <-time.After(1 * time.Second):
So(true, ShouldBeFalse)
}
})
Convey("Publish() pushes an event to the server", func() {
msg := RTMMessage{}
done := make(chan bool)
server := generateServerWithResponse(`{"type":"message"}`, func(c *websocket.Conn) {
c.ReadJSON(&msg)
done <- true
})
defer server.Close()
start := &RTMStartResult{URL: server.URL}
broker := NewRTMBroker(start)
err := broker.Connect()
So(err, ShouldBeNil)
broker.Publish(RTMMessage{Text: "hello world!"})
select {
case <-done:
So(msg.Type, ShouldEqual, "message")
So(msg.Text, ShouldEqual, "hello world!")
So(msg.ID, ShouldBeGreaterThan, 0)
case <-time.After(1 * time.Second):
So(true, ShouldBeFalse)
}
})
})
}
func generateServerWithResponse(event string, f func(c *websocket.Conn)) *httptest.Server {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, "could not create websock connection", http.StatusInternalServerError)
}
conn.WriteMessage(websocket.TextMessage, []byte(event))
go f(conn)
}))
server.URL = "ws" + strings.TrimPrefix(server.URL, "http")
return server
}