-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtube_system_test.go
494 lines (405 loc) · 16 KB
/
tube_system_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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
package pts
import (
"encoding/json"
"testing"
)
type FakeSocketHandleConnectFunc func(session *FakeSocketSession)
type FakeSocketHandleDisconnectFunc func(session *FakeSocketSession)
type FakeSocketHandleMessageFunc func(session *FakeSocketSession, msg []byte)
type FakeSocketHandleOutgoingMessageFunc func(msg []byte)
type FakeSocket struct {
handleConnect FakeSocketHandleConnectFunc
handleDisconnect FakeSocketHandleDisconnectFunc
handleMessage FakeSocketHandleMessageFunc
}
// NewClientConnects simulate a new client connects from the frontend.
// Messages that would be received by the frontend are passed to outgoingMessageHandler.
func (f *FakeSocket) NewClientConnects(outgoingMessageHandler FakeSocketHandleOutgoingMessageFunc) *FakeSocketSession {
s := &FakeSocketSession{
onDisconnect: f.handleDisconnect,
onMessage: f.handleMessage,
onOutgoingMessage: outgoingMessageHandler,
}
f.handleConnect(s)
return s
}
type FakeSocketSession struct {
Id string
onDisconnect FakeSocketHandleDisconnectFunc
onMessage FakeSocketHandleMessageFunc
onOutgoingMessage FakeSocketHandleOutgoingMessageFunc
}
// / Send emulate a data message from the frontend
func (s *FakeSocketSession) Send(data []byte) {
s.onMessage(s, data)
}
// Disconnect emulate disconnecting initiated by the frontend
func (s *FakeSocketSession) Disconnect() {
s.onDisconnect(s)
}
func NewFakeConnector(errorHandler ErrorHandlerFunc) (*Connector, *FakeSocket) {
fakeSocket := &FakeSocket{}
connector := NewConnector(nil, errorHandler)
connector.clients.init()
fakeSocket.handleConnect = func(s *FakeSocketSession) {
client := Client{
Id: "",
sendMessage: func(msg []byte) error {
s.onOutgoingMessage(msg)
return nil
},
properties: map[string]interface{}{},
}
connector.clients.Join(&client)
s.Id = client.Id
if connector.hooks.OnConnect != nil {
connector.hooks.OnConnect(&client)
}
}
fakeSocket.handleDisconnect = func(s *FakeSocketSession) {
client := connector.clients.Get(s.Id)
if connector.hooks.OnDisconnect != nil {
connector.hooks.OnDisconnect(client)
}
connector.clients.Remove(client.Id)
}
fakeSocket.handleMessage = func(s *FakeSocketSession, data []byte) {
client := connector.clients.Get(s.Id)
if connector.hooks.OnMessage != nil {
connector.hooks.OnMessage(client, data)
}
}
return connector, fakeSocket
}
func SubMessage(path string) []byte {
message := Message{
Type: MessageTypeSubscribe,
Channel: path,
Payload: nil,
}
data, _ := json.Marshal(message)
return data
}
func ChannelMessage(path string, payload json.RawMessage) []byte {
message := Message{
Type: MessageTypeChannelMessage,
Channel: path,
Payload: payload,
}
data, _ := json.Marshal(message)
return data
}
func UnsubMessage(path string) []byte {
message := Message{
Type: MessageTypeUnsubscribe,
Channel: path,
Payload: nil,
}
data, _ := json.Marshal(message)
return data
}
func TestTubeSystemConnection(t *testing.T) {
t.Run("Simple Connect Disconnect", func(t *testing.T) {
fakeConnector, fakeSocket := NewFakeConnector(func(err *Error) {})
fakeClient := fakeSocket.NewClientConnects(func(_ []byte) {})
if len(fakeConnector.clients.clients) != 1 {
t.Errorf("len(fakeConnector.clients.clients) = %d, want %d", len(fakeConnector.clients.clients), 1)
return
}
if fakeConnector.clients.Get(fakeClient.Id) == nil {
t.Errorf("fakeConnector.clients.Get(fakeClient.Id) = nil, want *FakeSocketSession")
}
fakeClient.Disconnect()
if len(fakeConnector.clients.clients) != 0 {
t.Errorf("len(fakeConnector.clients.clients) = %d, want %d", len(fakeConnector.clients.clients), 0)
return
}
})
t.Run("IsConnected should return connection status", func(t *testing.T) {
fakeConnector, fakeSocket := NewFakeConnector(func(err *Error) {})
tubeSystem := New(fakeConnector)
fakeClient := fakeSocket.NewClientConnects(func(_ []byte) {})
if !tubeSystem.IsConnected(fakeClient.Id) {
t.Errorf("tubeSystem.IsConnected(fakeClient.Id) = false, want true")
return
}
fakeClient.Disconnect()
if tubeSystem.IsConnected(fakeClient.Id) {
t.Errorf("channel.IsConnected(fakeClient.Id, testChannelPath) = true, want false")
return
}
})
t.Run("GetChannel should return registered channel", func(t *testing.T) {
channelPath := "example/path"
channelPathInvalid := "example/path/testy"
fakeConnector, _ := NewFakeConnector(func(err *Error) {})
tubeSystem := New(fakeConnector)
channel := tubeSystem.RegisterChannel(channelPath, ChannelHandlers{})
if found, foundChannel := tubeSystem.GetChannel(channelPath); !found {
t.Errorf("tubeSystem.GetChannel(channelPath) = (false, ...), want (true, ...)")
return
} else if foundChannel != channel {
t.Errorf("tubeSystem.GetChannel(channelPath) returns wrong channel.")
return
}
if found, foundChannel := tubeSystem.GetChannel(channelPathInvalid); found {
t.Errorf("tubeSystem.GetChannel(channelPath) = (true, ...), want (false, ...)")
return
} else if foundChannel != nil {
t.Errorf("tubeSystem.GetChannel(channelPath) returns not nil as channel, want nil")
return
}
})
t.Run("GetChannel should return registered channel with variable", func(t *testing.T) {
channelPath := "example/path/:var"
channelPathInvalid := "example/path/testy"
fakeConnector, _ := NewFakeConnector(func(err *Error) {})
tubeSystem := New(fakeConnector)
channel := tubeSystem.RegisterChannel(channelPath, ChannelHandlers{})
if found, foundChannel := tubeSystem.GetChannel(channelPath); !found {
t.Errorf("tubeSystem.GetChannel(channelPath) = (false, ...), want (true, ...)")
return
} else if foundChannel != channel {
t.Errorf("tubeSystem.GetChannel(channelPath) returns wrong channel.")
return
}
if found, foundChannel := tubeSystem.GetChannel(channelPathInvalid); found {
t.Errorf("tubeSystem.GetChannel(channelPath) = (true, ...), want (false, ...)")
return
} else if foundChannel != nil {
t.Errorf("tubeSystem.GetChannel(channelPath) returns not nil as channel, want nil")
return
}
})
t.Run("Handle Sub/Unsub", func(t *testing.T) {
channelPath := "example/path/:var"
testVar := "test"
testChannelPath := "example/path/" + testVar
testChannelPath2 := "example/path/foobar"
fakeConnector, fakeSocket := NewFakeConnector(func(err *Error) {})
tubeSystem := New(fakeConnector)
var subContext *Context
var unsubContext *Context
channel := tubeSystem.RegisterChannel(channelPath, ChannelHandlers{
OnSubscribe: func(s *Context) {
subContext = s
},
OnUnsubscribe: func(s *Context) {
unsubContext = s
},
})
fakeClient := fakeSocket.NewClientConnects(func(_ []byte) {})
fakeClient.Send(SubMessage(testChannelPath))
if !tubeSystem.IsSubscribed(testChannelPath, fakeClient.Id) {
t.Errorf("tubeSystem.IsSubscribed(testChannelPath, fakeClient.Id) = false, want true")
return
}
if tubeSystem.IsSubscribed(channelPath, fakeClient.Id) {
t.Errorf("tubeSystem.IsSubscribed(channelPath, fakeClient.Id) = true, want false")
return
}
if tubeSystem.IsSubscribed(testChannelPath2, fakeClient.Id) {
t.Errorf("tubeSystem.IsSubscribed(testChannelPath2, fakeClient.Id) = true, want false")
return
}
if !channel.IsSubscribed(fakeClient.Id, testChannelPath) {
t.Errorf("channel.IsSubscribed(fakeClient.Id, testChannelPath) = false, want true")
return
}
if channel.IsSubscribed(fakeClient.Id, channelPath) {
t.Errorf("channel.IsSubscribed(fakeClient.Id, channelPath) = true, want false")
return
}
if channel.IsSubscribed(fakeClient.Id, testChannelPath2) {
t.Errorf("channel.IsSubscribed(fakeClient.Id, testChannelPath2) = true, want false")
return
}
if subContext == nil {
t.Errorf("subContext = nil, want *Context")
return
}
if subContext.FullPath != testChannelPath {
t.Errorf("subContext = %s, want %s", subContext.FullPath, testChannelPath)
return
}
fakeClient.Send(UnsubMessage(testChannelPath))
if channel.IsSubscribed(fakeClient.Id, testChannelPath) {
t.Errorf("channel.IsSubscribed(fakeClient.Id, testChannelPath) = true, want false")
return
}
if unsubContext == nil {
t.Errorf("unsubContext = nil, want *Context")
return
}
})
}
func TestTubeSystemMessaging(t *testing.T) {
t.Run("Client Sends Message", func(t *testing.T) {
testChannelPath := "example/path/foobar"
testPayload := map[string]interface{}{"name": "Jon Doe", "admin": false}
testPayloadJson, _ := json.Marshal(testPayload)
fakeConnector, fakeSocket := NewFakeConnector(func(err *Error) {})
tubeSystem := New(fakeConnector)
var receivedMessage *Message
tubeSystem.RegisterChannel(testChannelPath, ChannelHandlers{
OnMessage: func(s *Context, message *Message) {
receivedMessage = message
},
})
fakeClient := fakeSocket.NewClientConnects(func(_ []byte) {})
fakeClient.Send(SubMessage(testChannelPath))
fakeClient.Send(ChannelMessage(testChannelPath, testPayloadJson))
var receivedPayload map[string]interface{}
_ = json.Unmarshal(receivedMessage.Payload, &receivedPayload)
if receivedPayload["name"] != testPayload["name"] || receivedPayload["admin"] != testPayload["admin"] {
t.Errorf(`equal({ "name": "%s", "admin": %b }, { "name": "%s", "admin": %b }) = false, want true`, receivedPayload["name"], receivedPayload["admin"], testPayload["name"], testPayload["admin"])
return
}
})
t.Run("Client sends Messages to different channels", func(t *testing.T) {
channelA := "example/path/a"
channelB := "example/path/b"
payloadA := map[string]interface{}{"name": "Jon Doe", "admin": false}
payloadB := map[string]interface{}{"name": "Tom Ford", "admin": true}
payloadJsonA, _ := json.Marshal(payloadA)
payloadJsonB, _ := json.Marshal(payloadB)
fakeConnector, fakeSocket := NewFakeConnector(func(err *Error) {})
tubeSystem := New(fakeConnector)
var recMessageChannelA *Message
var recMessageChannelB *Message
tubeSystem.RegisterChannel(channelA, ChannelHandlers{
OnMessage: func(s *Context, message *Message) {
recMessageChannelA = message
},
})
tubeSystem.RegisterChannel(channelB, ChannelHandlers{
OnMessage: func(s *Context, message *Message) {
recMessageChannelB = message
},
})
fakeClient := fakeSocket.NewClientConnects(func(msg []byte) {
})
fakeClient.Send(SubMessage(channelA))
fakeClient.Send(SubMessage(channelB))
fakeClient.Send(ChannelMessage(channelB, payloadJsonB))
fakeClient.Send(ChannelMessage(channelA, payloadJsonA))
var receivedPayload map[string]interface{}
_ = json.Unmarshal(recMessageChannelA.Payload, &receivedPayload)
if receivedPayload["name"] != payloadA["name"] || receivedPayload["admin"] != payloadA["admin"] {
t.Errorf(`equal({ "name": "%s", "admin": %b }, { "name": "%s", "admin": %b }) = false, want true`, receivedPayload["name"], receivedPayload["admin"], payloadA["name"], payloadA["admin"])
return
}
_ = json.Unmarshal(recMessageChannelB.Payload, &receivedPayload)
if receivedPayload["name"] != payloadB["name"] || receivedPayload["admin"] != payloadB["admin"] {
t.Errorf(`equal({ "name": "%s", "admin": %b }, { "name": "%s", "admin": %b }) = false, want true`, receivedPayload["name"], receivedPayload["admin"], payloadB["name"], payloadB["admin"])
return
}
})
t.Run("Client Receives Message", func(t *testing.T) {
testChannelPath := "example/path/foobar"
testPayload := map[string]interface{}{"name": "Jon Doe", "admin": false}
testPayloadJson, _ := json.Marshal(testPayload)
fakeConnector, fakeSocket := NewFakeConnector(func(err *Error) {})
tubeSystem := New(fakeConnector)
var receivedMessage *Message
tubeSystem.RegisterChannel(testChannelPath, ChannelHandlers{})
fakeClient := fakeSocket.NewClientConnects(func(msg []byte) {
if err := json.Unmarshal(msg, &receivedMessage); err != nil {
t.Errorf("could not unmarshal message: %e", err)
}
})
fakeClient.Send(SubMessage(testChannelPath))
if err := tubeSystem.Send(testChannelPath, fakeClient.Id, testPayloadJson); err != nil {
t.Errorf("tubeSystem.Send(...) throws an error: %s", err.Description)
return
}
if receivedMessage.Channel != testChannelPath {
t.Errorf("receivedMessage.Channel = %s, want %s", receivedMessage.Channel, testChannelPath)
return
}
var receivedPayload map[string]interface{}
_ = json.Unmarshal(receivedMessage.Payload, &receivedPayload)
if receivedPayload["name"] != testPayload["name"] || receivedPayload["admin"] != testPayload["admin"] {
t.Errorf(`equal({ "name": "%s", "admin": %b }, { "name": "%s", "admin": %b }) = false, want true`, receivedPayload["name"], receivedPayload["admin"], testPayload["name"], testPayload["admin"])
return
}
})
t.Run("TubeSystem send errors", func(t *testing.T) {
testChannelPath := "example/path/foobar"
testPayload := map[string]interface{}{"name": "Jon Doe", "admin": false}
testPayloadJson, _ := json.Marshal(testPayload)
fakeConnector, fakeSocket := NewFakeConnector(func(err *Error) {})
tubeSystem := New(fakeConnector)
var receivedMessage *Message
tubeSystem.RegisterChannel(testChannelPath, ChannelHandlers{})
fakeClient := fakeSocket.NewClientConnects(func(msg []byte) {
if err := json.Unmarshal(msg, &receivedMessage); err != nil {
t.Errorf("could not unmarshal message: %e", err)
}
})
fakeClient.Send(SubMessage(testChannelPath))
if err := tubeSystem.Send(testChannelPath, fakeClient.Id, testPayloadJson); err != nil {
t.Errorf("tubeSystem.Send(...) throws an error: %s", err.Description)
return
}
channelNotExistingErr := tubeSystem.Send("example/non-existent/foobar", fakeClient.Id, testPayloadJson)
if channelNotExistingErr == nil {
t.Errorf("tubeSystem.Send(...) return nil, want channel not exists error.")
return
} else if channelNotExistingErr.Code != ErrorUnknownChannel {
t.Errorf("tubeSystem.Send(...) return Error{Code: %d}, want Error{Code: %d}.", channelNotExistingErr.Code, ErrorUnknownChannel)
return
}
fakeClient.Send(UnsubMessage(testChannelPath))
notSubscribedErr := tubeSystem.Send(testChannelPath, fakeClient.Id, testPayloadJson)
if notSubscribedErr == nil {
t.Errorf("tubeSystem.Send(...) return nil, want not subscribed error.")
return
} else if notSubscribedErr.Code != ErrorClientNotSubscribed {
t.Errorf("tubeSystem.Send(...) return Error{Code: %d}, want Error{Code: %d}.", channelNotExistingErr.Code, ErrorClientNotSubscribed)
return
}
})
t.Run("Client send errors", func(t *testing.T) {
testChannelPath := "example/path/foobar"
testPayload := map[string]interface{}{"name": "Jon Doe", "admin": false}
testPayloadJson, _ := json.Marshal(testPayload)
var retrievedErr *Error
fakeConnector, fakeSocket := NewFakeConnector(func(err *Error) {
retrievedErr = err
})
tubeSystem := New(fakeConnector)
var receivedMessage *Message
tubeSystem.RegisterChannel(testChannelPath, ChannelHandlers{})
fakeClient := fakeSocket.NewClientConnects(func(msg []byte) {
if err := json.Unmarshal(msg, &receivedMessage); err != nil {
t.Errorf("could not unmarshal message: %e", err)
}
})
fakeClient.Send(SubMessage(testChannelPath))
if err := tubeSystem.Send(testChannelPath, fakeClient.Id, testPayloadJson); err != nil {
t.Errorf("tubeSystem.Send(...) throws an error: %s", err.Description)
return
}
invalidTypeMessage := Message{
Type: "_INVALID_TYPE_",
Channel: testChannelPath,
Payload: nil,
}
data, _ := json.Marshal(invalidTypeMessage)
fakeClient.Send(data)
if retrievedErr == nil {
t.Errorf("tubeSystem.messageHandler(...) did not throw any error, want invalid type error.")
} else if retrievedErr.Code != ErrorUnknownType {
t.Errorf("tubeSystem.messageHandler(...) return Error{Code: %d}, want Error{Code: %d}.", retrievedErr.Code, ErrorUnknownType)
return
}
fakeClient.Send([]byte{1, 2, 3})
if retrievedErr == nil {
t.Errorf("tubeSystem.messageHandler(...) did not throw any error, want invalid message error.")
} else if retrievedErr.Code != ErrorInvalidMessage {
t.Errorf("tubeSystem.messageHandler(...) return Error{Code: %d}, want Error{Code: %d}.", retrievedErr.Code, ErrorInvalidMessage)
return
}
})
}