-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws_test.go
117 lines (88 loc) · 2.57 KB
/
ws_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
package ws
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gorilla/websocket"
"github.com/stretchr/testify/assert"
)
func createTestServer() *httptest.Server {
server := httptest.NewServer(http.HandlerFunc(WebsocketHandler))
return server
}
func createTestWebSocketConnection(server *httptest.Server) (*websocket.Conn, error) {
conn, _, err := websocket.DefaultDialer.Dial(strings.Replace(server.URL, "http", "ws", 1), nil)
return conn, err
}
func TestPingPongHandler(t *testing.T) {
server := createTestServer()
conn, err := createTestWebSocketConnection(server)
assert.Nil(t, err, err)
response := make(chan ResponseMessage)
go SendMessageAndWaitForResponse(conn, PING, response)
result := <-response
assert.Equal(t, PONG, result.Result)
}
func TestRegisterChannel(t *testing.T) {
server := createTestServer()
conn, err := createTestWebSocketConnection(server)
assert.Nil(t, err, err)
RegisterChannelHandler("handler-channel", func(msg RequestMessage, c *Client) {
c.Send(ResponseMessage{
Result: "hello",
})
})
id := uint64(1234)
req := RequestMessage{
JSONRPC: JSONRPC,
Method: "handler-channel",
ID: &id,
}
response := make(chan ResponseMessage)
go SendMessageAndWaitForResponse(conn, req, response)
result := <-response
assert.Equal(t, "hello", result.Result)
req = RequestMessage{
JSONRPC: JSONRPC,
Method: "invalid-handler-channel",
ID: &id,
}
go SendMessageAndWaitForResponse(conn, req, response)
result = <-response
assert.Nil(t, result.Result)
assert.Equal(t, MethodNotFound, result.Error.Code)
assert.Equal(t, "method not found", result.Error.Message)
}
func TestRegisterWithMiddlewareChannel(t *testing.T) {
server := createTestServer()
conn, err := createTestWebSocketConnection(server)
assert.Nil(t, err, err)
middleware := func(msg RequestMessage, c *Client) *ResponseMessage {
res := ResponseMessage{
Error: &ErrorMessage{
Message: "blocked by middleware",
Data: nil,
Code: InvalidRequest,
},
}
return &res
}
handler := func(msg RequestMessage, c *Client) {
c.Send(ResponseMessage{
Result: "hello",
})
}
RegisterChannelHandler("handler-private-channel", MiddlewaresWrapper(handler, middleware))
id := uint64(1234)
req := RequestMessage{
JSONRPC: JSONRPC,
Method: "handler-private-channel",
ID: &id,
}
response := make(chan ResponseMessage)
go SendMessageAndWaitForResponse(conn, req, response)
result := <-response
assert.Equal(t, InvalidRequest, result.Error.Code)
assert.Equal(t, "blocked by middleware", result.Error.Message)
}