This repository has been archived by the owner on Aug 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
signalr_test.go
1046 lines (919 loc) · 24.2 KB
/
signalr_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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package signalr_test
import (
"crypto/tls"
"errors"
"log"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"testing"
"time"
"github.com/carterjones/signalr"
"github.com/carterjones/signalr/hubs"
"github.com/gorilla/websocket"
)
func ExampleClient_Run() {
// Prepare a SignalR client.
c := signalr.New(
"fake-server.definitely-not-real",
"1.5",
"/signalr",
`[{"name":"awesomehub"}]`,
nil,
)
// Define handlers.
msgHandler := func(msg signalr.Message) { log.Println(msg) }
panicIfErr := func(err error) {
if err != nil {
log.Panic(err)
}
}
// Start the connection.
err := c.Run(msgHandler, panicIfErr)
if err != nil {
log.Panic(err)
}
// Wait indefinitely.
select {}
}
// This example shows the most basic way to start a websocket connection.
func Example_basic() {
// Prepare a SignalR client.
c := signalr.New(
"fake-server.definitely-not-real",
"1.5",
"/signalr",
`[{"name":"awesomehub"}]`,
nil,
)
// Define message and error handlers.
msgHandler := func(msg signalr.Message) { log.Println(msg) }
panicIfErr := func(err error) {
if err != nil {
log.Panic(err)
}
}
// Start the connection.
err := c.Run(msgHandler, panicIfErr)
panicIfErr(err)
// Wait indefinitely.
select {}
}
// This example shows how to manually perform each of the initialization steps.
func Example_complex() {
// Prepare a SignalR client.
c := signalr.New(
"fake-server.definitely-not-real",
"1.5",
"/signalr",
`[{"name":"awesomehub"}]`,
map[string]string{"custom-key": "custom-value"},
)
// Perform any optional modifications to the client here. Read the docs for
// all the available options that are exposed via public fields.
// Define message and error handlers.
msgHandler := func(msg signalr.Message) { log.Println(msg) }
panicIfErr := func(err error) {
if err != nil {
log.Panic(err)
}
}
// Manually perform the initialization routine.
err := c.Negotiate()
panicIfErr(err)
conn, err := c.Connect()
panicIfErr(err)
err = c.Start(conn)
panicIfErr(err)
// Begin the message reading loop.
go c.ReadMessages(msgHandler, panicIfErr)
// Wait indefinitely.
select {}
}
func red(s string) string {
return "\033[31m" + s + "\033[39m"
}
func equals(tb testing.TB, id string, exp, act interface{}) {
if !reflect.DeepEqual(exp, act) {
_, file, line, _ := runtime.Caller(1)
tb.Errorf(red("%s:%d %s: \n\texp: %#v\n\tgot: %#v\n"),
filepath.Base(file), line, id, exp, act)
}
}
func ok(tb testing.TB, id string, err error) {
if err != nil {
_, file, line, _ := runtime.Caller(1)
tb.Errorf(red("%s:%d %s | unexpected error: %s\n"),
filepath.Base(file), line, id, err.Error())
}
}
func notNil(tb testing.TB, id string, act interface{}) {
if act == nil {
_, file, line, _ := runtime.Caller(1)
tb.Errorf(red("%s:%d (%s):\n\texp: a non-nil value\n\tgot: %#v\n"),
filepath.Base(file), line, id, act)
}
}
func notEmpty(tb testing.TB, id string, act string) {
if act == "" {
_, file, line, _ := runtime.Caller(1)
tb.Errorf(red("%s:%d (%s):\n\texp: a non-empty value\n\tgot: %#v\n"),
filepath.Base(file), line, id, act)
}
}
// Note: this is largely derived from
// https://github.com/golang/go/blob/1c69384da4fb4a1323e011941c101189247fea67/src/net/http/response_test.go#L915-L940
func errMatches(tb testing.TB, id string, err error, wantErr interface{}) {
if err == nil {
if wantErr == nil {
return
}
if sub, ok := wantErr.(string); ok {
tb.Errorf(red("%s | unexpected success; want error with substring %q"), id, sub)
return
}
tb.Errorf(red("%s | unexpected success; want error %v"), id, wantErr)
return
}
if wantErr == nil {
tb.Errorf(red("%s | %v; want success"), id, err)
return
}
if sub, ok := wantErr.(string); ok {
if strings.Contains(err.Error(), sub) {
return
}
tb.Errorf(red("%s | error = %v; want an error with substring %q"), id, err, sub)
return
}
if err == wantErr {
return
}
tb.Errorf(red("%s | %v; want %v"), id, err, wantErr)
}
func hostFromServerURL(url string) (host string) {
host = strings.TrimPrefix(url, "https://")
host = strings.TrimPrefix(host, "http://")
return
}
const (
serverResponseWriteTimeout = 500 * time.Millisecond
)
func newTestServer(fn http.HandlerFunc, useTLS bool) *httptest.Server {
// Create the server.
ts := httptest.NewUnstartedServer(fn)
// Set the write timeout so that we can test timeouts later on.
ts.Config.WriteTimeout = serverResponseWriteTimeout
if useTLS {
ts.StartTLS()
} else {
ts.Start()
}
return ts
}
func newTestClient(
protocol, endpoint, connectionData string,
params map[string]string,
ts *httptest.Server,
) *signalr.Client {
// Prepare a SignalR client.
c := signalr.New(hostFromServerURL(ts.URL), protocol, endpoint, connectionData, params)
c.HTTPClient = ts.Client()
// Save the TLS config in case this is using TLS.
if ts.TLS != nil {
// This is a local-only test, so we don't care about validating
// certificates. This simplifies things greatly.
// nolint:gosec
c.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
c.Scheme = signalr.HTTPS
} else {
c.Scheme = signalr.HTTP
}
return c
}
func throw503Error(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
_, err := w.Write([]byte("503 error"))
if err != nil {
log.Panic(err)
}
}
func throw678Error(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(678)
_, err := w.Write([]byte("678 error"))
if err != nil {
log.Panic(err)
}
}
func throw404Error(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, err := w.Write([]byte("404 error"))
if err != nil {
log.Panic(err)
}
}
func causeWriteResponseTimeout(w http.ResponseWriter, r *http.Request) {
time.Sleep(3 * serverResponseWriteTimeout)
}
func TestClient_Negotiate(t *testing.T) {
t.Parallel()
// Make a requestID available to test cases in the event that multiple
// requests are sent that should have different responses based on which
// request is being sent.
var requestID int
log.Println(requestID)
cases := map[string]struct {
fn http.HandlerFunc
in *signalr.Client
TLS bool
useDebug bool
exp *signalr.Client
scheme signalr.Scheme
params map[string]string
wantErr string
}{
"successful http": {
fn: signalr.TestNegotiate,
in: &signalr.Client{
Protocol: "1337",
Endpoint: "/signalr",
ConnectionData: "all the data",
},
TLS: false,
exp: &signalr.Client{
Protocol: "1337",
Endpoint: "/signalr",
ConnectionToken: "hello world",
ConnectionID: "1234-ABC",
ConnectionData: "",
},
},
"successful https": {
fn: signalr.TestNegotiate,
in: &signalr.Client{
Protocol: "1337",
Endpoint: "/signalr",
ConnectionData: "all the data",
},
TLS: true,
exp: &signalr.Client{
Protocol: "1337",
Endpoint: "/signalr",
ConnectionToken: "hello world",
ConnectionID: "1234-ABC",
},
},
"503 error": {
fn: throw503Error,
in: &signalr.Client{},
exp: &signalr.Client{},
wantErr: "503 Service Unavailable",
},
"default error": {
fn: throw678Error,
in: &signalr.Client{},
exp: &signalr.Client{},
wantErr: "678 status code",
},
"failed get request": {
fn: causeWriteResponseTimeout,
in: &signalr.Client{},
exp: &signalr.Client{},
wantErr: "EOF",
},
"invalid json": {
fn: func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("invalid json"))
if err != nil {
log.Panic(err)
}
},
in: &signalr.Client{},
exp: &signalr.Client{},
wantErr: "invalid character 'i' looking for beginning of value",
},
"request preparation failure": {
fn: signalr.TestNegotiate,
in: &signalr.Client{},
scheme: ":",
exp: &signalr.Client{},
wantErr: "request preparation failed",
},
"call debug messages": {
fn: throw503Error,
in: &signalr.Client{},
exp: &signalr.Client{},
useDebug: true,
wantErr: "503 Service Unavailable",
},
"recover after failure": {
fn: func(w http.ResponseWriter, r *http.Request) {
if requestID == 0 {
throw503Error(w, r)
requestID++
} else {
signalr.TestNegotiate(w, r)
}
},
in: &signalr.Client{
Protocol: "1337",
Endpoint: "/signalr",
ConnectionData: "all the data",
},
TLS: false,
exp: &signalr.Client{
Protocol: "1337",
Endpoint: "/signalr",
ConnectionToken: "hello world",
ConnectionID: "1234-ABC",
ConnectionData: "",
},
},
"custom parameters": {
fn: signalr.TestNegotiate,
in: &signalr.Client{
Protocol: "1337",
Endpoint: "/signalr",
ConnectionData: "all the data",
},
TLS: false,
params: map[string]string{"custom-key": "custom-value"},
exp: &signalr.Client{
Protocol: "1337",
Endpoint: "/signalr",
ConnectionToken: "hello world",
ConnectionID: "1234-ABC",
ConnectionData: "",
},
},
}
for id, tc := range cases {
tc := tc
// Set the debug flag.
if tc.useDebug {
os.Setenv("DEBUG", "true")
}
// Reset the request ID.
requestID = 0
// Prepare to save parameters.
var params map[string]string
done := make(chan struct{})
// Create a test server.
ts := newTestServer(func(w http.ResponseWriter, r *http.Request) {
params = extractCustomParams(r.URL.Query())
tc.fn(w, r)
go func() { done <- struct{}{} }()
}, tc.TLS)
// Create a test client.
c := newTestClient(tc.in.Protocol, tc.in.Endpoint, tc.in.ConnectionData, tc.params, ts)
// Set the wait time to milliseconds.
c.RetryWaitDuration = 1 * time.Millisecond
// Set a custom scheme if one is specified.
if tc.scheme != "" {
c.Scheme = tc.scheme
}
// Perform the negotiation.
err := c.Negotiate()
// If the scheme is invalid, this will never send a request, so we move
// on. Otherwise, we wait for the request to complete.
if tc.scheme != ":" {
<-done
}
// Make sure the error matches the expected error.
if tc.wantErr != "" {
errMatches(t, id, err, tc.wantErr)
} else {
ok(t, id, err)
}
// Validate the things we expect.
equals(t, id, tc.exp.ConnectionToken, c.ConnectionToken)
equals(t, id, tc.exp.ConnectionID, c.ConnectionID)
equals(t, id, tc.exp.Protocol, c.Protocol)
equals(t, id, tc.exp.Endpoint, c.Endpoint)
equals(t, id, tc.params, params)
ts.Close()
// Unset the debug flag.
if tc.useDebug {
os.Unsetenv("DEBUG")
}
}
}
func extractCustomParams(values url.Values) map[string]string {
// Remove the parameters that we know will be there.
values.Del("transport")
values.Del("clientProtocol")
values.Del("connectionData")
values.Del("tid")
// Return nil if nothing remains.
if len(values) == 0 {
return nil
}
// Save the custom parameters.
params := make(map[string]string)
for k, v := range values {
params[k] = v[0]
}
// Return the custom parameters.
return params
}
func TestClient_Connect(t *testing.T) {
t.Parallel()
cases := map[string]struct {
fn http.HandlerFunc
TLS bool
cookies []*http.Cookie
params map[string]string
wantErr string
}{
"successful https connect": {
fn: signalr.TestConnect,
TLS: true,
},
"successful http connect": {
fn: signalr.TestConnect,
TLS: false,
},
"service not available": {
fn: throw503Error,
TLS: true,
wantErr: websocket.ErrBadHandshake.Error(),
},
"generic error": {
fn: throw404Error,
TLS: true,
wantErr: "xconnect failed: 404 Not Found, retry 0: websocket: bad handshake",
},
"custom cookie jar": {
fn: signalr.TestConnect,
TLS: false,
cookies: []*http.Cookie{{
Name: "hello",
Value: "world",
}},
},
"custom parameters": {
fn: signalr.TestConnect,
TLS: true,
params: map[string]string{"custom-key": "custom-value"},
},
}
for id, tc := range cases {
tc := tc
// Make a cookie recording wrapper function.
done := make(chan struct{})
var cookies []*http.Cookie
var params map[string]string
var tid string
recordResponse := func(w http.ResponseWriter, r *http.Request) {
cookies = r.Cookies()
params = extractCustomParams(r.URL.Query())
tid = r.URL.Query().Get("tid")
tc.fn(w, r)
go func() { done <- struct{}{} }()
}
// Set up the test server.
ts := newTestServer(recordResponse, tc.TLS)
// Prepare a new client.
c := newTestClient("", "", "", tc.params, ts)
// Set cookies if they have been configured.
if tc.cookies != nil {
u, err := url.Parse(ts.URL)
if err != nil {
log.Panic(err)
}
c.HTTPClient.Jar, err = cookiejar.New(nil)
if err != nil {
log.Panic(err)
}
c.HTTPClient.Jar.SetCookies(u, tc.cookies)
}
// Set the wait time to milliseconds.
c.RetryWaitDuration = 1 * time.Millisecond
// Perform the connection.
conn, err := c.Connect()
<-done
if tc.wantErr != "" {
errMatches(t, id, err, tc.wantErr)
} else {
if len(tc.cookies) > 0 {
equals(t, id, tc.cookies, cookies)
}
equals(t, id, tc.params, params)
ok(t, id, err)
notEmpty(t, id, tid)
_, cerr := strconv.Atoi(tid)
ok(t, id, cerr)
}
notNil(t, id, conn)
ts.Close()
}
}
func TestClient_Reconnect(t *testing.T) {
t.Parallel()
cases := map[string]struct {
fn http.HandlerFunc
groupsToken string
messageID string
wantErr string
}{
"successful reconnect": {
fn: signalr.TestReconnect,
},
"groups token": {
fn: signalr.TestReconnect,
groupsToken: "my-custom-token",
},
"message id": {
fn: signalr.TestReconnect,
messageID: "unique-message-id",
},
}
for id, tc := range cases {
tc := tc
// Make a cookie recording wrapper function.
done := make(chan struct{})
var groupsToken string
var messageID string
recordResponse := func(w http.ResponseWriter, r *http.Request) {
groupsToken = r.URL.Query().Get("groupsToken")
messageID = r.URL.Query().Get("messageId")
tc.fn(w, r)
go func() { done <- struct{}{} }()
}
// Set up the test server.
ts := newTestServer(recordResponse, true)
// Prepare a new client.
c := newTestClient("", "", "", nil, ts)
// Set the wait time to milliseconds.
c.RetryWaitDuration = 1 * time.Millisecond
// Set the group token.
c.GroupsToken.Set(tc.groupsToken)
c.MessageID.Set(tc.messageID)
// Perform the connection.
conn, err := c.Reconnect()
<-done
if tc.wantErr != "" {
errMatches(t, id, err, tc.wantErr)
} else {
ok(t, id, err)
equals(t, id, tc.groupsToken, groupsToken)
equals(t, id, tc.messageID, messageID)
}
notNil(t, id, conn)
ts.Close()
}
}
func handleWebsocketWithCustomMsg(w http.ResponseWriter, r *http.Request, msg string) {
upgrader := websocket.Upgrader{}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Panic(err)
}
go func() {
for {
_, _, rerr := c.ReadMessage()
if rerr != nil {
return
}
}
}()
go func() {
for {
werr := c.WriteMessage(websocket.TextMessage, []byte(msg))
if werr != nil {
return
}
}
}()
}
func TestClient_Start(t *testing.T) {
t.Parallel()
cases := map[string]struct {
skipConnect bool
skipRetries bool
startFn http.HandlerFunc
connectFn http.HandlerFunc
scheme signalr.Scheme
params map[string]string
groupsToken string
messageID string
wantErr string
}{
"successful start": {
startFn: signalr.TestStart,
connectFn: signalr.TestConnect,
},
"nil connection": {
skipConnect: true,
wantErr: "connection is nil",
},
"failed get request": {
startFn: causeWriteResponseTimeout,
connectFn: signalr.TestConnect,
wantErr: "EOF",
},
"invalid json sent in response to get request": {
startFn: func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("invalid json"))
if err != nil {
log.Panic(err)
}
},
connectFn: signalr.TestConnect,
wantErr: "invalid character 'i' looking for beginning of value",
},
"non-'started' response": {
startFn: func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte(`{"Response":"not expecting this"}`))
if err != nil {
log.Panic(err)
}
},
connectFn: signalr.TestConnect,
wantErr: "start response is not 'started': not expecting this",
},
"non-text message from websocket": {
startFn: signalr.TestStart,
connectFn: func(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Panic(err)
}
err = c.WriteMessage(websocket.BinaryMessage, []byte("non-text message"))
if err != nil {
log.Panic(err)
}
},
wantErr: "unexpected websocket control type",
},
"invalid json sent in init message": {
startFn: signalr.TestStart,
connectFn: func(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Panic(err)
}
err = c.WriteMessage(websocket.TextMessage, []byte("invalid json"))
if err != nil {
log.Panic(err)
}
},
wantErr: "invalid character 'i' looking for beginning of value",
},
"wrong S value from server": {
startFn: signalr.TestStart,
connectFn: func(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Panic(err)
}
err = c.WriteMessage(websocket.TextMessage, []byte(`{"S":3}`))
if err != nil {
log.Panic(err)
}
},
wantErr: "unexpected S value received from server",
},
"request preparation failure": {
startFn: signalr.TestStart,
connectFn: signalr.TestConnect,
scheme: ":",
wantErr: "request preparation failed",
},
"empty response": {
skipRetries: true,
startFn: signalr.TestStart,
connectFn: signalr.TestConnect,
wantErr: "response is nil",
},
"custom parameters": {
startFn: signalr.TestStart,
connectFn: signalr.TestConnect,
params: map[string]string{"custom-key": "custom-value"},
},
"groups token": {
startFn: signalr.TestStart,
groupsToken: "my-custom-groups-token",
connectFn: func(w http.ResponseWriter, r *http.Request) {
handleWebsocketWithCustomMsg(w, r, `{"S":1,"G":"my-custom-groups-token"}`)
},
},
"message id": {
startFn: signalr.TestStart,
messageID: "my-custom-message-id",
connectFn: func(w http.ResponseWriter, r *http.Request) {
handleWebsocketWithCustomMsg(w, r, `{"S":1,"C":"my-custom-message-id"}`)
},
},
}
for id, tc := range cases {
tc := tc
var params map[string]string
// Create a test server that is initialized with this test
// case's "start handler".
ts := newTestServer(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/start") {
params = extractCustomParams(r.URL.Query())
tc.startFn(w, r)
} else if strings.Contains(r.URL.Path, "/connect") {
tc.connectFn(w, r)
}
}, true)
// Create a test client and establish the initial connection.
c := newTestClient("", "", "", tc.params, ts)
// Set the wait time to milliseconds.
c.RetryWaitDuration = 1 * time.Millisecond
// Don't perform any retries.
if tc.skipRetries {
c.MaxStartRetries = 0
}
// Perform the connection.
var conn signalr.WebsocketConn
var err error
if !tc.skipConnect {
conn, err = c.Connect()
if err != nil {
// If this fails, it is not part of the test, so we
// panic here.
log.Panic(err)
}
}
// Set a custom scheme if one is specified.
if tc.scheme != "" {
c.Scheme = tc.scheme
}
// Execute the start function.
err = c.Start(conn)
if tc.wantErr != "" {
errMatches(t, id, err, tc.wantErr)
} else {
// Verify that the connection was properly set.
equals(t, id, conn, c.Conn())
// Verify no error occurred.
ok(t, id, err)
// Verify parameters were properly set.
equals(t, id, tc.params, params)
// Verify the groups token was properly set.
equals(t, id, tc.groupsToken, c.GroupsToken.Get())
// Verify the message ID was properly set.
equals(t, id, tc.messageID, c.MessageID.Get())
}
ts.Close()
}
}
func TestClient_Init(t *testing.T) {
t.Parallel()
cases := map[string]struct {
negotiateFn func(http.ResponseWriter, *http.Request)
connectFn func(http.ResponseWriter, *http.Request)
startFn func(http.ResponseWriter, *http.Request)
wantErr string
}{
"successful init": {
negotiateFn: signalr.TestNegotiate,
connectFn: signalr.TestConnect,
startFn: signalr.TestStart,
wantErr: "",
},
"failed negotiate": {
negotiateFn: func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("invalid json"))
if err != nil {
log.Panic(err)
}
},
wantErr: "json unmarshal failed: invalid character 'i' looking for beginning of value",
},
"failed connect": {
negotiateFn: signalr.TestNegotiate,
connectFn: throw678Error,
wantErr: "connect failed: xconnect failed: 678 status code 678",
},
"failed start": {
negotiateFn: signalr.TestNegotiate,
connectFn: signalr.TestConnect,
startFn: causeWriteResponseTimeout,
wantErr: "EOF",
},
}
for id, tc := range cases {
tc := tc
ts := newTestServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.Contains(r.URL.Path, "/negotiate"):
tc.negotiateFn(w, r)
case strings.Contains(r.URL.Path, "/connect"):
tc.connectFn(w, r)
case strings.Contains(r.URL.Path, "/start"):
tc.startFn(w, r)
default:
log.Println("url:", r.URL)
}
}), true)
c := newTestClient("1.5", "/signalr", "all the data", nil, ts)
c.RetryWaitDuration = 1 * time.Millisecond
// Define handlers.
msgHandler := func(signalr.Message) {}
errHandler := func(error) {}
// Run the client.
err := c.Run(msgHandler, errHandler)
if tc.wantErr != "" {
errMatches(t, id, err, tc.wantErr)
} else {
ok(t, id, err)
}
ts.Close()
}
}
type FakeConn struct {
err error
data interface{}
}
func (c *FakeConn) ReadMessage() (messageType int, p []byte, err error) {
return
}
func (c *FakeConn) WriteJSON(v interface{}) error {
// Save the data that is supposedly being written, so it can be
// inspected later.
c.data = v
return c.err
}
func TestClient_Send(t *testing.T) {
t.Parallel()
cases := map[string]struct {
conn *FakeConn
err error
wantErr string
}{
"successful write": {
conn: new(FakeConn),
err: nil,
wantErr: "",
},
"connection not set": {
conn: nil,
err: nil,
wantErr: "send: connection not set",
},
"write error": {
conn: new(FakeConn),
err: errors.New("test error"),
wantErr: "test error",
},
}
for id, tc := range cases {
// Set up a new test client.
c := signalr.New("", "", "", "", nil)
// Set up a fake connection, if one has been created.
if tc.conn != nil {
tc.conn.err = tc.err