forked from phenixsh/sockets
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sockets_test.go
363 lines (310 loc) · 8.85 KB
/
sockets_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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Copyright 2014 Beat Richartz
// Copyright 2014 Unknwon
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package sockets
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/Unknwon/macaron"
"github.com/gorilla/websocket"
)
const (
host string = "http://localhost:3000"
endpoint string = "ws://localhost:3000"
recvPath string = "/receiver"
sendPath string = "/sender"
pingPath string = "/ping"
recvStringsPath string = "/strings/receiver"
sendStringsPath string = "/strings/sender"
pingStringsPath string = "/strings/ping"
)
type Message struct {
Text string `json:"text"`
}
var (
once sync.Once
recvMessages []*Message
recvCount int
recvDone bool
sendMessages []*Message
sendCount int
sendDone bool
recvStrings []string
recvStringsCount int
recvStringsDone bool
sendStrings []string
sendStringsCount int
sendStringsDone bool
)
// Test Helpers
func expectSame(t *testing.T, a interface{}, b interface{}) {
if a != b {
t.Errorf("Expected %T: %v to be %T: %v", b, b, a, a)
}
}
func expectStringsToBeEmpty(t *testing.T, strings []string) {
if len(strings) > 0 {
t.Errorf("Expected strings array to be empty, but they contained %d values", len(strings))
}
}
func expectMessagesToBeEmpty(t *testing.T, messages []*Message) {
if len(messages) > 0 {
t.Errorf("Expected messages array to be empty, but they contained %d values", len(messages))
}
}
func expectStringsToHaveArrived(t *testing.T, count int, strings []string) {
if len(strings) < count {
t.Errorf("Expected strings array to contain 3 values, but contained %d", len(strings))
} else {
for i, s := range strings {
if s != "Hello World" {
t.Errorf("Expected string %d to be \"Hello World\", but was \"%v\"", i+1, s)
}
}
}
}
func expectMessagesToHaveArrived(t *testing.T, count int, messages []*Message) {
if len(messages) < count {
t.Errorf("Expected messages array to contain 3 values, but contained %d", len(messages))
} else {
for i, m := range messages {
if m.Text != "Hello World" {
t.Errorf("Expected message %d to contain \"Hello World\", but contained %v", i+1, m)
}
}
}
}
func expectPingsToHaveBeenExecuted(t *testing.T, count int, messages []*Message) {
if len(messages) < count {
t.Errorf("Expected messages array to contain 3 ping values, but contained %d", len(messages))
} else {
for i, m := range messages {
if m.Text != "" {
t.Errorf("Expected message %d to contain \"\", but contained %v", i+1, m)
}
}
}
}
func expectStatusCode(t *testing.T, expectedStatusCode int, actualStatusCode int) {
if actualStatusCode != expectedStatusCode {
t.Errorf("Expected StatusCode %d, but received %d", expectedStatusCode, actualStatusCode)
}
}
func expectIsDone(t *testing.T, done bool) {
if !done {
t.Errorf("Expected to be done, but was not")
}
}
func startServer() {
m := macaron.Classic()
m.Get(recvPath, JSON(Message{}), func(ctx *macaron.Context, receiver <-chan *Message, done <-chan bool) int {
for {
select {
case msg := <-receiver:
recvMessages = append(recvMessages, msg)
case <-done:
recvDone = true
return http.StatusOK
}
}
return http.StatusOK
})
m.Get(sendPath, JSON(Message{}), func(ctx *macaron.Context, sender chan<- *Message, done <-chan bool, disconnect chan<- int) int {
ticker := time.NewTicker(1 * time.Millisecond)
bomb := time.After(4 * time.Millisecond)
for {
select {
case <-ticker.C:
sender <- &Message{"Hello World"}
case <-done:
ticker.Stop()
sendDone = true
return http.StatusOK
case <-bomb:
disconnect <- websocket.CloseGoingAway
return http.StatusOK
}
}
return http.StatusOK
})
m.Get(recvStringsPath, Messages(), func(ctx *macaron.Context, receiver <-chan string, done <-chan bool) int {
for {
select {
case msg := <-receiver:
recvStrings = append(recvStrings, msg)
case <-done:
recvStringsDone = true
return http.StatusOK
}
}
return http.StatusOK
})
m.Get(sendStringsPath, Messages(), func(ctx *macaron.Context, sender chan<- string, done <-chan bool, disconnect chan<- int) int {
ticker := time.NewTicker(1 * time.Millisecond)
bomb := time.After(4 * time.Millisecond)
for {
select {
case <-ticker.C:
sender <- "Hello World"
case <-done:
ticker.Stop()
sendStringsDone = true
return http.StatusOK
case <-bomb:
disconnect <- websocket.CloseGoingAway
return http.StatusOK
}
}
return http.StatusOK
})
go m.Run(3000)
time.Sleep(5 * time.Millisecond)
}
func connectSocket(t *testing.T, path string) (*websocket.Conn, *http.Response) {
header := make(http.Header)
header.Add("Origin", host)
ws, resp, err := websocket.DefaultDialer.Dial(endpoint+path, header)
if err != nil {
t.Fatalf("Connecting the socket failed: %s", err.Error())
}
return ws, resp
}
func TestStringReceive(t *testing.T) {
once.Do(startServer)
expectStringsToBeEmpty(t, recvStrings)
ws, resp := connectSocket(t, recvStringsPath)
ticker := time.NewTicker(time.Millisecond)
for {
<-ticker.C
s := "Hello World"
err := ws.WriteMessage(websocket.TextMessage, []byte(s))
if err != nil {
t.Errorf("Writing to the socket failed with %s", err.Error())
}
recvStringsCount++
if recvStringsCount == 4 {
ws.Close()
return
}
}
expectStringsToHaveArrived(t, 3, recvStrings)
expectStatusCode(t, http.StatusSwitchingProtocols, resp.StatusCode)
expectIsDone(t, recvStringsDone)
}
func TestStringSend(t *testing.T) {
once.Do(startServer)
expectStringsToBeEmpty(t, sendStrings)
ws, resp := connectSocket(t, sendStringsPath)
defer ws.Close()
for {
_, msgArray, err := ws.ReadMessage()
msg := string(msgArray)
sendStrings = append(sendStrings, msg)
if err != nil && err != io.EOF {
t.Errorf("Receiving from the socket failed with %v", err)
}
if sendStringsCount == 3 {
return
}
sendStringsCount++
}
expectStringsToHaveArrived(t, 3, sendStrings)
expectStatusCode(t, http.StatusSwitchingProtocols, resp.StatusCode)
expectIsDone(t, sendStringsDone)
}
func TestJSONReceive(t *testing.T) {
once.Do(startServer)
expectMessagesToBeEmpty(t, recvMessages)
ws, resp := connectSocket(t, recvPath)
message := &Message{"Hello World"}
ticker := time.NewTicker(time.Millisecond)
for {
<-ticker.C
err := ws.WriteJSON(message)
if err != nil {
t.Errorf("Writing to the socket failed with %v", err)
}
recvCount++
if recvCount == 4 {
ws.Close()
return
}
}
expectMessagesToHaveArrived(t, 3, recvMessages)
expectStatusCode(t, http.StatusSwitchingProtocols, resp.StatusCode)
expectIsDone(t, recvDone)
}
func TestJSONSend(t *testing.T) {
once.Do(startServer)
expectMessagesToBeEmpty(t, sendMessages)
ws, resp := connectSocket(t, sendPath)
defer ws.Close()
for {
msg := &Message{}
err := ws.ReadJSON(msg)
sendMessages = append(sendMessages, msg)
if err != nil && err != io.EOF {
t.Errorf("Receiving from the socket failed with %v", err)
}
if sendCount == 3 {
return
}
sendCount++
}
expectMessagesToHaveArrived(t, 3, sendMessages)
expectStatusCode(t, http.StatusSwitchingProtocols, resp.StatusCode)
expectIsDone(t, sendDone)
}
func TestOptionsDefaultHandling(t *testing.T) {
o := newOptions([]*Options{
&Options{
LogLevel: LEVEL_DEBUG,
WriteWait: 15 * time.Second,
PingPeriod: 10 * time.Second,
},
})
expectSame(t, o.LogLevel, LEVEL_DEBUG)
expectSame(t, o.PingPeriod, 10*time.Second)
expectSame(t, o.WriteWait, 15*time.Second)
expectSame(t, o.MaxMessageSize, defaultMaxMessageSize)
expectSame(t, o.SendChannelBuffer, defaultSendChannelBuffer)
expectSame(t, o.RecvChannelBuffer, defaultRecvChannelBuffer)
}
func TestCrossOrigin(t *testing.T) {
header := make(http.Header)
header.Add("Origin", "http://somewhere.com")
_, resp, err := websocket.DefaultDialer.Dial(endpoint+sendPath, header)
if err == nil {
t.Fatalf("Connecting to the socket succeeded with a cross origin request")
}
expectStatusCode(t, http.StatusForbidden, resp.StatusCode)
}
func TestUnallowedMethods(t *testing.T) {
m := macaron.Classic()
recorder := httptest.NewRecorder()
req, err := http.NewRequest("POST", "/test", strings.NewReader(""))
if err != nil {
t.Error(err)
}
m.Any("/test", Messages(), func() int {
return http.StatusOK
})
m.ServeHTTP(recorder, req)
expectStatusCode(t, http.StatusMethodNotAllowed, recorder.Code)
}