-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlongpoll_test.go
1565 lines (1490 loc) · 62 KB
/
longpoll_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 golongpoll
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
)
type CloseNotifierRecorder struct {
httptest.ResponseRecorder
CloseNotifier chan bool
}
// As it turns out, httptest.ResponseRecorder (returned by httptest.NewRecorder)
// does not support CloseNotify, so mock it to avoid panics about not supporting
// the interface
func (cnr *CloseNotifierRecorder) CloseNotify() <-chan bool {
return cnr.CloseNotifier
}
func NewCloseNotifierRecorder() *CloseNotifierRecorder {
return &CloseNotifierRecorder{
httptest.ResponseRecorder{
HeaderMap: make(http.Header),
Body: new(bytes.Buffer),
Code: 200,
},
make(chan bool, 1),
}
}
func Test_LongpollManager_CreateManager(t *testing.T) {
manager, err := CreateManager()
// Confirm the create call worked, and our manager has the expected values
if err != nil {
t.Errorf("Failed to create default LongpollManager. Error was: %q", err)
}
// Channel size defaults to 100
if cap(manager.eventsIn) != 100 {
t.Errorf("Unexpected event channel capacity. Expected: %d, got: %d",
100, cap(manager.eventsIn))
}
if cap(manager.subManager.clientSubscriptions) != 100 {
t.Errorf("Unexpected client subscription channel capacity. Expected: %d, got: %d",
100, cap(manager.subManager.clientSubscriptions))
}
if cap(manager.subManager.ClientTimeouts) != 100 {
t.Errorf("Unexpected client timeout channel capacity. Expected: %d, got: %d",
100, cap(manager.subManager.ClientTimeouts))
}
// Max event buffer size defaults to 250
if manager.subManager.MaxEventBufferSize != 250 {
t.Errorf("Unexpected client timeout channel capacity. Expected: %d, got: %d",
250, manager.subManager.MaxEventBufferSize)
}
// Don't forget to kill subscription manager's running goroutine
manager.Shutdown()
}
func Test_LongpollManager_CreateCustomManager(t *testing.T) {
manager, err := CreateCustomManager(360, 700, true)
// Confirm the create call worked, and our manager has the expected values
if err != nil {
t.Errorf("Failed to create default LongpollManager. Error was: %q", err)
}
// Channel size defaults to 100
if cap(manager.eventsIn) != 100 {
t.Errorf("Unexpected event channel capacity. Expected: %d, got: %d",
100, cap(manager.eventsIn))
}
if cap(manager.subManager.clientSubscriptions) != 100 {
t.Errorf("Unexpected client subscription channel capacity. Expected: %d, got: %d",
100, cap(manager.subManager.clientSubscriptions))
}
if cap(manager.subManager.ClientTimeouts) != 100 {
t.Errorf("Unexpected client timeout channel capacity. Expected: %d, got: %d",
100, cap(manager.subManager.ClientTimeouts))
}
// Max event buffer size set to 700
if manager.subManager.MaxEventBufferSize != 700 {
t.Errorf("Unexpected client timeout channel capacity. Expected: %d, got: %d",
700, manager.subManager.MaxEventBufferSize)
}
// Don't forget to kill subscription manager's running goroutine
manager.Shutdown()
}
func Test_LongpollManager_CreateCustomManager_InvalidArgs(t *testing.T) {
manager, err := CreateCustomManager(360, -1, false) // buffer size == -1
if err == nil {
t.Errorf("Expected error when creating custom manager with invalid event buffer size ")
}
if manager != nil {
t.Errorf("Expected nil response for manager when create call returned error.")
}
manager, err = CreateCustomManager(-1, 200, false) // timeout == -1
if err == nil {
t.Errorf("Expected error when creating custom manager with invalid timeout.")
}
if manager != nil {
t.Errorf("Expected nil response for manager when create call returned error.")
}
}
func Test_LongpollManager_Publish(t *testing.T) {
manager, err := CreateManager()
// Confirm the create call worked, and our manager has the expected values
if err != nil {
t.Errorf("Failed to create default LongpollManager. Error was: %q", err)
}
if len(manager.eventsIn) != 0 {
t.Errorf("Expected event channel to be initially empty. Instead len: %d",
len(manager.eventsIn))
}
if len(manager.subManager.SubEventBuffer) != 0 {
t.Errorf("Expected sub manager's event map to be initially empty. Instead len: %d",
len(manager.subManager.SubEventBuffer))
}
err = manager.Publish("fruits", "apple")
if err != nil {
t.Errorf("Unexpected error publishing event: %q", err)
}
// SubscriptionManager's goroutine should not have picked up event yet:
// I *think* this should always work because we don't typically yield
// execution to other goroutines until an end of a func reached,
// or a channel/network/sleep call is invoked.
if len(manager.eventsIn) != 1 {
t.Errorf("Expected event channel to have 1 event. Instead len: %d",
len(manager.eventsIn))
}
// Allow sub manager's goroutine time to pull from channel.
// This sleep should cause us to yield and let the other goroutine run
time.Sleep(50 * time.Millisecond)
if len(manager.eventsIn) != 0 {
t.Errorf("Expected event channel to have 0 events. Instead len: %d",
len(manager.eventsIn))
}
// Confirm event wound up in the sub manager's internal map:
if len(manager.subManager.SubEventBuffer) != 1 {
t.Errorf("Expected sub manager's event map to have 1 item. Instead len: %d",
len(manager.subManager.SubEventBuffer))
}
buf, found := manager.subManager.SubEventBuffer["fruits"]
if !found {
t.Errorf("Failed to find event in sub manager's category-to-eventBuffer map")
}
// Double check that the expected max buffer size and capacity were set
if buf.eventBuffer_ptr.MaxBufferSize != 250 {
t.Errorf("Expected max buffer size of %d, but got %d.", 250, buf.eventBuffer_ptr.MaxBufferSize)
}
if buf.eventBuffer_ptr.List.Len() != 1 {
t.Errorf("Expected buffer to be 1 item. instead: %d", buf.eventBuffer_ptr.List.Len())
}
if buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data != "apple" {
t.Errorf("Expected event data to be %q, but got %q", "apple",
buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data)
}
// Publish two more events
err = manager.Publish("veggies", "potato")
if err != nil {
t.Errorf("Unexpected error publishing event: %q", err)
}
err = manager.Publish("fruits", "orange")
if err != nil {
t.Errorf("Unexpected error publishing event: %q", err)
}
// Allow other goroutine a chance to do a channel read
time.Sleep(50 * time.Millisecond)
if len(manager.eventsIn) != 0 {
t.Errorf("Expected event channel to have 0 events. Instead len: %d",
len(manager.eventsIn))
}
if len(manager.subManager.SubEventBuffer) != 2 {
t.Errorf("Expected sub manager's event map to have 2 item. Instead len: %d",
len(manager.subManager.SubEventBuffer))
}
buf, found = manager.subManager.SubEventBuffer["fruits"]
if !found {
t.Errorf("Failed to find event in sub manager's category-to-eventBuffer map")
}
if buf.eventBuffer_ptr.List.Len() != 2 {
t.Errorf("Expected buffer to be 2 items. instead: %d", buf.eventBuffer_ptr.List.Len())
}
if buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data != "orange" {
t.Errorf("Expected event data to be %q, but got %q", "orange",
buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data)
}
buf, found = manager.subManager.SubEventBuffer["veggies"]
if !found {
t.Errorf("Failed to find event in sub manager's category-to-eventBuffer map")
}
if buf.eventBuffer_ptr.List.Len() != 1 {
t.Errorf("Expected buffer to be 1 item. instead: %d", buf.eventBuffer_ptr.List.Len())
}
if buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data != "potato" {
t.Errorf("Expected event data to be %q, but got %q", "potato",
buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data)
}
// Don't forget to kill subscription manager's running goroutine
manager.Shutdown()
}
func Test_LongpollManager_Publish_MaxBufferSize(t *testing.T) {
manager, err := CreateCustomManager(120, 2, true) // max buffer size 3
if len(manager.subManager.SubEventBuffer) != 0 {
t.Errorf("Expected sub manager's event map to be initially empty. Instead len: %d",
len(manager.subManager.SubEventBuffer))
}
err = manager.Publish("fruits", "apple")
if err != nil {
t.Errorf("Unexpected error publishing event: %q", err)
}
err = manager.Publish("fruits", "banana")
if err != nil {
t.Errorf("Unexpected error publishing event: %q", err)
}
// yield so other goroutine can do channel reads
time.Sleep(50 * time.Millisecond)
if len(manager.eventsIn) != 0 {
t.Errorf("Expected event channel to have 0 events. Instead len: %d",
len(manager.eventsIn))
}
// Confirm events wound up in the sub manager's internal map:
// NOTE: only one map entry because both events the same category
if len(manager.subManager.SubEventBuffer) != 1 {
t.Errorf("Expected sub manager's event map to have 1 item. Instead len: %d",
len(manager.subManager.SubEventBuffer))
}
buf, found := manager.subManager.SubEventBuffer["fruits"]
if !found {
t.Errorf("Failed to find event in sub manager's category-to-eventBuffer map")
}
// Double check that the expected max buffer size and capacity were set
if buf.eventBuffer_ptr.MaxBufferSize != 2 {
t.Errorf("Expected max buffer size of %d, but got %d.", 2, buf.eventBuffer_ptr.MaxBufferSize)
}
if buf.eventBuffer_ptr.List.Len() != 2 {
t.Errorf("Expected buffer to be 2 items. instead: %d", buf.eventBuffer_ptr.List.Len())
}
if buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data != "banana" {
t.Errorf("Expected event data to be %q, but got %q", "banana",
buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data)
}
if buf.eventBuffer_ptr.Back().Value.(*lpEvent).Data != "apple" {
t.Errorf("Expected event data to be %q, but got %q", "apple",
buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data)
}
// Now try and publish another event on the same fruit category,
// confirm that it works, but the oldest fruit is no longer in buffer
err = manager.Publish("fruits", "pear")
if err != nil {
t.Errorf("Unexpected error publishing event: %q", err)
}
// yield so other goroutine can do channel reads
time.Sleep(50 * time.Millisecond)
buf, found = manager.subManager.SubEventBuffer["fruits"]
if !found {
t.Errorf("Failed to find event in sub manager's category-to-eventBuffer map")
}
// Double check that the expected max buffer size and capacity were set
if buf.eventBuffer_ptr.MaxBufferSize != 2 {
t.Errorf("Expected max buffer size of %d, but got %d.", 2, buf.eventBuffer_ptr.MaxBufferSize)
}
if buf.eventBuffer_ptr.List.Len() != 2 {
t.Errorf("Expected buffer to be 2 items. instead: %d", buf.eventBuffer_ptr.List.Len())
}
if buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data != "pear" {
t.Errorf("Expected event data to be %q, but got %q", "banana",
buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data)
}
if buf.eventBuffer_ptr.Back().Value.(*lpEvent).Data != "banana" {
t.Errorf("Expected event data to be %q, but got %q", "apple",
buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data)
}
// Now confirm publishing on a different category still works
err = manager.Publish("veggies", "potato")
if err != nil {
t.Errorf("Unexpected error publishing event: %q", err)
}
// yield so other goroutine can do channel reads
time.Sleep(50 * time.Millisecond)
buf, found = manager.subManager.SubEventBuffer["veggies"]
if !found {
t.Errorf("Failed to find event in sub manager's category-to-eventBuffer map")
}
if buf.eventBuffer_ptr.List.Len() != 1 {
t.Errorf("Expected buffer to be 1 item. instead: %d", buf.eventBuffer_ptr.List.Len())
}
if buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data != "potato" {
t.Errorf("Expected event data to be %q, but got %q", "potato",
buf.eventBuffer_ptr.Front().Value.(*lpEvent).Data)
}
// Don't forget to kill subscription manager's running goroutine
manager.Shutdown()
}
func Test_LongpollManager_Publish_InvalidArgs(t *testing.T) {
manager, err := CreateManager()
// Confirm the create call worked, and our manager has the expected values
if err != nil {
t.Errorf("Failed to create default LongpollManager. Error was: %q", err)
}
// You must provide a category:
err = manager.Publish("", "apple")
if err == nil {
t.Errorf("Expected calls to Publish with blank category would fail.")
}
// category can't be longer than 1024:
// So 1024 len category should work:
tooLong := ""
for i := 0; i < 1024; i++ {
tooLong += "a"
}
err = manager.Publish(tooLong, "apple")
if err != nil {
t.Errorf("Expected calls to Publish with 1024 len category not to fail, but got: %q.", err)
}
// But now that we're at 1025, we're boned.
tooLong += "a"
err = manager.Publish(tooLong, "apple")
if err == nil {
t.Errorf("Expected calls to Publish with blank category would fail.")
}
}
func Test_LongpollManager_Shutdown(t *testing.T) {
manager, err := CreateManager()
if err != nil {
t.Errorf("Failed to create default LongpollManager. Error was: %q", err)
}
manager.Shutdown()
// Confirm the shutdown signal channel was closed (this is now the
// goroutines are notified to quit)
select {
case _, isOpen := <-manager.subManager.Quit:
if isOpen {
t.Errorf("Expected channel to be closed, instead it was still open")
}
default:
t.Errorf("Expected channel close, instead got no activity.")
}
}
func Test_LongpollManager_newclientSubscription(t *testing.T) {
subTime := time.Date(2015, 11, 7, 11, 33, 4, 0, time.UTC)
sub, err := newclientSubscription("colors", subTime)
if err != nil {
t.Errorf("Unexpected error when creating new client subscription: %q", err)
}
if sub.clientCategoryPair.SubscriptionCategory != "colors" {
t.Errorf("Unexpected sub category, expected: %q. got: %q", "colors",
sub.clientCategoryPair.SubscriptionCategory)
}
if sub.LastEventTime != subTime {
t.Errorf("Unexpected sub last event time, expected: %q. got: %q", subTime,
sub.LastEventTime)
}
if cap(sub.Events) != 1 {
t.Errorf("Unexpected event channel capacity. expected: %q. got: %q", 1,
cap(sub.Events))
}
}
func ajaxHandler(handlerFunc func(w http.ResponseWriter, r *http.Request)) http.Handler {
return http.HandlerFunc(handlerFunc)
}
func Test_LongpollManager_WebClient_InvalidRequests(t *testing.T) {
manager, _ := CreateCustomManager(120, 100, true)
subscriptionHandler := ajaxHandler(manager.SubscriptionHandler)
// Empty request, this is going to result in an JSON error object:
req, _ := http.NewRequest("GET", "", nil)
w := httptest.NewRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
// Also note how it says "1-120", so our custom timeout arg of 120 was
// used
if w.Body.String() != "{\"error\": \"Invalid timeout arg. Must be 1-120.\"}" {
t.Errorf("Unexpected response: %q", w.Body.String())
}
// Invalid timeout, not a number
req, _ = http.NewRequest("GET", "?timeout=adf&category=veggies", nil)
w = httptest.NewRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
if w.Body.String() != "{\"error\": \"Invalid timeout arg. Must be 1-120.\"}" {
t.Errorf("Unexpected response: %q", w.Body.String())
}
// Invalid timeout, too small
req, _ = http.NewRequest("GET", "?timeout=0&category=veggies", nil)
w = httptest.NewRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
if w.Body.String() != "{\"error\": \"Invalid timeout arg. Must be 1-120.\"}" {
t.Errorf("Unexpected response: %q", w.Body.String())
}
// Invalid timeout, too big
req, _ = http.NewRequest("GET", "?timeout=121&category=veggies", nil)
w = httptest.NewRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
if w.Body.String() != "{\"error\": \"Invalid timeout arg. Must be 1-120.\"}" {
t.Errorf("Unexpected response: %q", w.Body.String())
}
// Valid timeout, but missing category:
req, _ = http.NewRequest("GET", "?timeout=30", nil)
w = httptest.NewRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
if w.Body.String() != "{\"error\": \"Invalid subscription category, must be 1-1024 characters long.\"}" {
t.Errorf("Unexpected response: %q", w.Body.String())
}
// Valid timeout, but category is too small
req, _ = http.NewRequest("GET", "?timeout=30&category=", nil)
w = httptest.NewRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
if w.Body.String() != "{\"error\": \"Invalid subscription category, must be 1-1024 characters long.\"}" {
t.Errorf("Unexpected response: %q", w.Body.String())
}
// Valid timeout, but category too long
tooLong := ""
for i := 0; i < 1025; i++ {
tooLong += "a"
} // 1025 chars long
req, _ = http.NewRequest("GET", "?timeout=30&category="+tooLong, nil)
w = httptest.NewRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
if w.Body.String() != "{\"error\": \"Invalid subscription category, must be 1-1024 characters long.\"}" {
t.Errorf("Unexpected response: %q", w.Body.String())
}
// Valid timeout, valid category, but invalid since_time
req, _ = http.NewRequest("GET", "?timeout=30&category=foobar&since_time=asdf", nil)
w = httptest.NewRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
if w.Body.String() != "{\"error\": \"Invalid last_event_time arg.\"}" {
t.Errorf("Unexpected response: %q", w.Body.String())
}
// Don't forget to kill our pubsub manager's run goroutine
manager.Shutdown()
}
func Test_LongpollManager_WebClient_NoEventsSoTimeout(t *testing.T) {
manager, _ := CreateCustomManager(120, 100, true)
subscriptionHandler := ajaxHandler(manager.SubscriptionHandler)
// Valid request, but we don't have any events published,
// so this will wait 2 seconds (because timeout param = 2)
// and then come back wtih a timeout response
req, _ := http.NewRequest("GET", "?timeout=2&category=veggies", nil)
w := NewCloseNotifierRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
approxTimeoutTime := timeToEpochMilliseconds(time.Now())
var timeoutResp timeoutResponse
if err := json.Unmarshal(w.Body.Bytes(), &timeoutResp); err != nil {
t.Errorf("Failed to decode json: %q", err)
}
if timeoutResp.TimeoutMessage != "no events before timeout" {
t.Errorf("Unexpected timeout message: %q", timeoutResp.TimeoutMessage)
}
if timeoutResp.Timestamp < (approxTimeoutTime-100) ||
timeoutResp.Timestamp > approxTimeoutTime {
t.Errorf("Unexpected timeout timestamp. Expected: %q, got: %q",
approxTimeoutTime, timeoutResp.Timestamp)
}
// Don't forget to kill our pubsub manager's run goroutine
manager.Shutdown()
}
func Test_LongpollManager_WebClient_Disconnect_RemoveClientSub(t *testing.T) {
manager, _ := CreateCustomManager(120, 100, true)
subscriptionHandler := ajaxHandler(manager.SubscriptionHandler)
if _, found := manager.subManager.ClientSubChannels["veggies"]; found {
t.Errorf("Expected client sub channel not to exist yet ")
}
// This request has timeout of 5 seconds, but we're going to simulate a
// disconnect in 2 seconds which is earlier.
req, _ := http.NewRequest("GET", "?timeout=5&category=veggies", nil)
w := NewCloseNotifierRecorder()
// As of go 1.7, calls to t.Error, t.Fatal, after a test exits causes a panic.
// Before, these were suppressed. So as it turns out, this test's goroutine
// that spawns here was outliving the test. Now let's make the test body
// explicitly wait for it.
// see thread here: https://github.com/golang/go/issues/15976
goroutine_done := make(chan bool)
go func() {
time.Sleep(time.Duration(250) * time.Millisecond)
// confirm subscription entry exists, with one client
if _, found := manager.subManager.ClientSubChannels["veggies"]; !found {
t.Errorf("Expected client sub channel to exist")
}
if val, _ := manager.subManager.ClientSubChannels["veggies"]; len(val) != 1 {
t.Errorf("Expected sub channel to have one client subscribed")
}
time.Sleep(time.Duration(1) * time.Second)
w.CloseNotifier <- true
time.Sleep(time.Duration(1) * time.Second)
// Confirm that the subscription entry no longer exists.
// Before, this test asserted that the entry ('veggie' key in the map)
// existed, but the value listed no clients. But code was changed to auto
// remove subscription keys in this map if there are no clients listening.
// Since these asserts were erroneously firing after the test body exited
// (and this is undefined behavior and pre go 1.7 it's simply ignored),
// this bad assertion was never failing when it should have.
// Once the test body was forced to wait for it's spawned goroutine to exit,
// the old assertion started failing.
// This test is now updated to assert that the key "veggies" no longer
// exists since we're explicitly removing map entries when the value is
// an empty container.
if _, found := manager.subManager.ClientSubChannels["veggies"]; found {
t.Errorf("Expected client sub channel to be auto removed when 0 clients.")
}
goroutine_done <- true
}()
subscriptionHandler.ServeHTTP(w, req)
// causes test body to block until the above spawned goroutine finishes.
// Otherwise this will panic in go 1.7 and later :)
<-goroutine_done
// Don't forget to kill our pubsub manager's run goroutine
manager.Shutdown()
}
func Test_LongpollManager_WebClient_Disconnect_TerminateHttp(t *testing.T) {
manager, _ := CreateCustomManager(120, 100, true)
testChannel := make(chan int, 2)
webValue := 7
goroutineValue := 13
subscriptionHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
manager.SubscriptionHandler(w, r)
testChannel <- webValue
})
if _, found := manager.subManager.ClientSubChannels["veggies"]; found {
t.Errorf("Expected client sub channel not to exist yet ")
}
// This request has timeout of 5 seconds, but we're going to simulate a
// disconnect in 1 second which is earlier.
// If the wrapping subscription handler gets to the end, it will publish
// the number 7 on our test channel. Have a goroutine publish a different
// value at some time after the disconnect, but before the timeout
// and confirm that the disconnect forced the subscription handler
// to return early and thus we get the expected published value.
req, _ := http.NewRequest("GET", "?timeout=5&category=veggies", nil)
w := NewCloseNotifierRecorder()
go func() {
time.Sleep(time.Duration(3) * time.Second)
testChannel <- goroutineValue
}()
go func() {
time.Sleep(time.Duration(250) * time.Millisecond)
// confirm subscription entry exists, with one client
if _, found := manager.subManager.ClientSubChannels["veggies"]; !found {
t.Errorf("Expected client sub channel to exist")
}
if val, _ := manager.subManager.ClientSubChannels["veggies"]; len(val) != 1 {
t.Errorf("Expected sub channel to have one client subscribed")
}
time.Sleep(time.Duration(1) * time.Second)
w.CloseNotifier <- true
time.Sleep(time.Duration(2) * time.Second)
// Confirm that our test channel has the value from our web handler and
// not from our goroutine
select {
case val := <-testChannel:
if val != webValue {
t.Errorf("Expected to get channel send from http handler before the goroutine.")
}
}
}()
subscriptionHandler.ServeHTTP(w, req)
// Don't forget to kill our pubsub manager's run goroutine
manager.Shutdown()
}
func Test_LongpollManager_WebClient_HasEvents(t *testing.T) {
manager, _ := CreateCustomManager(120, 100, true)
subscriptionHandler := ajaxHandler(manager.SubscriptionHandler)
// Valid request, but we don't have any events published,
// so this will wait for a publish or timeout (in this case we'll get
// something)
req, _ := http.NewRequest("GET", "?timeout=30&category=veggies", nil)
w := NewCloseNotifierRecorder()
// Publish two events, only the second is for our subscription category
// Note how these events occur after the client subscribed
// if they occurred before, since we don't provide a since_time url param
// we'd default to now and skip those events.
startTime := time.Now()
go func() {
time.Sleep(1500 * time.Millisecond)
manager.Publish("fruits", "peach")
time.Sleep(1000 * time.Millisecond)
manager.Publish("veggies", "corn")
}()
subscriptionHandler.ServeHTTP(w, req)
// Confirm we got the correct event
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
var eventResponse eventResponse
if err := json.Unmarshal(w.Body.Bytes(), &eventResponse); err != nil {
t.Errorf("Failed to decode json: %q", err)
}
if len(*eventResponse.Events) != 1 {
t.Errorf("Unexpected number of events. Expected: %d, got: %d", 1, len(*eventResponse.Events))
}
if (*eventResponse.Events)[0].Category != "veggies" {
t.Errorf("Unexpected category. Expected: %q, got: %q", "veggies", (*eventResponse.Events)[0].Category)
}
if (*eventResponse.Events)[0].Data != "corn" {
t.Errorf("Unexpected data. Expected: %q, got: %q", "corn", (*eventResponse.Events)[0].Data)
}
// Make a new subscription request.
// Note how since there's no since_time url param, we default to now,
// and thus don't see the previous event from our last http request
req, _ = http.NewRequest("GET", "?timeout=2&category=veggies", nil)
w = NewCloseNotifierRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
approxTimeoutTime := timeToEpochMilliseconds(time.Now())
var timeoutResp timeoutResponse
if err := json.Unmarshal(w.Body.Bytes(), &timeoutResp); err != nil {
t.Errorf("Failed to decode json: %q", err)
}
if timeoutResp.TimeoutMessage != "no events before timeout" {
t.Errorf("Unexpected timeout message: %q", timeoutResp.TimeoutMessage)
}
if timeoutResp.Timestamp < (approxTimeoutTime-100) ||
timeoutResp.Timestamp > approxTimeoutTime {
t.Errorf("Unexpected timeout timestamp. Expected: %q, got: %q",
approxTimeoutTime, timeoutResp.Timestamp)
}
// Now ask for events since the start of our test, which will include
// our previously seen event
req, _ = http.NewRequest("GET", fmt.Sprintf("?timeout=2&category=veggies&since_time=%d",
timeToEpochMilliseconds(startTime)), nil)
w = NewCloseNotifierRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
if err := json.Unmarshal(w.Body.Bytes(), &eventResponse); err != nil {
t.Errorf("Failed to decode json: %q", err)
}
if len(*eventResponse.Events) != 1 {
t.Errorf("Unexpected number of events. Expected: %d, got: %d", 1, len(*eventResponse.Events))
}
if (*eventResponse.Events)[0].Category != "veggies" {
t.Errorf("Unexpected category. Expected: %q, got: %q", "veggies", (*eventResponse.Events)[0].Category)
}
if (*eventResponse.Events)[0].Data != "corn" {
t.Errorf("Unexpected data. Expected: %q, got: %q", "corn", (*eventResponse.Events)[0].Data)
}
firstEventTime := (*eventResponse.Events)[0].Timestamp
manager.Publish("veggies", "carrot")
time.Sleep(50 * time.Millisecond) // allow yield for goroutine channel reads
// Now ask for any events since our first one, and confirm we get the second
// 'veggie' category event
req, _ = http.NewRequest("GET", fmt.Sprintf("?timeout=2&category=veggies&since_time=%d", firstEventTime), nil)
w = NewCloseNotifierRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
if err := json.Unmarshal(w.Body.Bytes(), &eventResponse); err != nil {
t.Errorf("Failed to decode json: %q", err)
}
if len(*eventResponse.Events) != 1 {
t.Errorf("Unexpected number of events. Expected: %d, got: %d", 1, len(*eventResponse.Events))
}
if (*eventResponse.Events)[0].Category != "veggies" {
t.Errorf("Unexpected category. Expected: %q, got: %q", "veggies", (*eventResponse.Events)[0].Category)
}
if (*eventResponse.Events)[0].Data != "carrot" {
t.Errorf("Unexpected data. Expected: %q, got: %q", "carrot", (*eventResponse.Events)[0].Data)
}
// Confirm we get both events when asking for any events since start of test run
req, _ = http.NewRequest("GET", fmt.Sprintf("?timeout=2&category=veggies&since_time=%d",
timeToEpochMilliseconds(startTime)), nil)
w = NewCloseNotifierRecorder()
subscriptionHandler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
if err := json.Unmarshal(w.Body.Bytes(), &eventResponse); err != nil {
t.Errorf("Failed to decode json: %q", err)
}
if len(*eventResponse.Events) != 2 {
t.Errorf("Unexpected number of events. Expected: %d, got: %d", 2, len(*eventResponse.Events))
}
if (*eventResponse.Events)[0].Data != "corn" {
t.Errorf("Unexpected data. Expected: %q, got: %q", "corn", (*eventResponse.Events)[0].Data)
}
if (*eventResponse.Events)[1].Data != "carrot" {
t.Errorf("Unexpected data. Expected: %q, got: %q", "carrot", (*eventResponse.Events)[0].Data)
}
// Don't forget to kill our pubsub manager's run goroutine
manager.Shutdown()
}
func Test_LongpollManager_WebClient_HasBufferedEvents(t *testing.T) {
// Test behavior where clients can see events that happened before
// they started their longpoll by accessing events in the
// subscriptionManager's eventBuffer containers.
// Of course, clients only see this if they request events with a
// 'since_time' argument of a time earlier than the events occurred.
manager, _ := CreateCustomManager(120, 100, true)
subscriptionHandler := ajaxHandler(manager.SubscriptionHandler)
startTime := time.Now()
time.Sleep(500 * time.Millisecond)
manager.Publish("veggies", "broccoli")
time.Sleep(500 * time.Millisecond)
manager.Publish("veggies", "corn")
time.Sleep(500 * time.Millisecond)
// This request clearly takes place after the two events were published.
// But we ask for any events since the start of this test case
req, _ := http.NewRequest("GET", fmt.Sprintf("?timeout=2&category=veggies&since_time=%d",
timeToEpochMilliseconds(startTime)), nil)
w := NewCloseNotifierRecorder()
subscriptionHandler.ServeHTTP(w, req)
// Confirm we got the correct event
if w.Code != http.StatusOK {
t.Errorf("SubscriptionHandler didn't return %v", http.StatusOK)
}
var eventResponse eventResponse
if err := json.Unmarshal(w.Body.Bytes(), &eventResponse); err != nil {
t.Errorf("Failed to decode json: %q", err)
}
if len(*eventResponse.Events) != 2 {
t.Errorf("Unexpected number of events. Expected: %d, got: %d", 2, len(*eventResponse.Events))
}
if (*eventResponse.Events)[0].Category != "veggies" {
t.Errorf("Unexpected category. Expected: %q, got: %q", "veggies", (*eventResponse.Events)[0].Category)
}
if (*eventResponse.Events)[0].Data != "broccoli" {
t.Errorf("Unexpected data. Expected: %q, got: %q", "broccoli", (*eventResponse.Events)[0].Data)
}
if (*eventResponse.Events)[1].Category != "veggies" {
t.Errorf("Unexpected category. Expected: %q, got: %q", "veggies", (*eventResponse.Events)[1].Category)
}
if (*eventResponse.Events)[1].Data != "corn" {
t.Errorf("Unexpected data. Expected: %q, got: %q", "corn", (*eventResponse.Events)[1].Data)
}
// Don't forget to kill our pubsub manager's run goroutine
manager.Shutdown()
}
func Test_LongpollManager_makeTimeoutResponse(t *testing.T) {
now := time.Now()
timeoutResp := makeTimeoutResponse(now)
timeoutTime := timeToEpochMilliseconds(now)
if timeoutResp.TimeoutMessage != "no events before timeout" {
t.Errorf("Unexpected timeout message: %q", timeoutResp.TimeoutMessage)
}
if timeoutResp.Timestamp != timeoutTime {
t.Errorf("Unexpected timeout timestamp. Expected: %q, got: %q",
timeoutTime, timeoutResp.Timestamp)
}
}
func Test_LongpollManager_StartLongpoll_Options(t *testing.T) {
// Error cases due to invalid options:
if _, err := StartLongpoll(Options{
LoggingEnabled: true,
MaxLongpollTimeoutSeconds: 120,
MaxEventBufferSize: -1,
EventTimeToLiveSeconds: 1,
}); err == nil {
t.Errorf("Expected error when passing MaxEventBufferSize that was < 0")
}
if _, err := StartLongpoll(Options{
LoggingEnabled: true,
MaxLongpollTimeoutSeconds: -1,
MaxEventBufferSize: 100,
EventTimeToLiveSeconds: 1,
}); err == nil {
t.Errorf("Expected error when passing MaxLongpollTimeoutSeconds that was < 0")
}
if _, err := StartLongpoll(Options{
LoggingEnabled: true,
MaxLongpollTimeoutSeconds: 120,
MaxEventBufferSize: 100,
EventTimeToLiveSeconds: -1,
}); err == nil {
t.Errorf("Expected error when passing EventTimeToLiveSeconds that was < 0")
}
// Confirm valid options work
// actual TTL
if manager, err := StartLongpoll(Options{
LoggingEnabled: true,
MaxLongpollTimeoutSeconds: 120,
MaxEventBufferSize: 100,
EventTimeToLiveSeconds: 30,
}); err != nil {
t.Errorf("Unxpected error when calling StartLongpoll with valid options")
} else {
manager.Shutdown()
}
// Forever
if manager, err := StartLongpoll(Options{
LoggingEnabled: true,
MaxLongpollTimeoutSeconds: 120,
MaxEventBufferSize: 100,
EventTimeToLiveSeconds: FOREVER,
}); err != nil {
t.Errorf("Unxpected error when calling StartLongpoll with valid options")
} else {
manager.Shutdown()
}
// Confirm zero TTL converts to forever
if manager, err := StartLongpoll(Options{
LoggingEnabled: true,
MaxLongpollTimeoutSeconds: 120,
MaxEventBufferSize: 100,
EventTimeToLiveSeconds: 0,
}); err != nil {
t.Errorf("Unxpected error when calling StartLongpoll with valid options")
} else {
if manager.subManager.EventTimeToLiveSeconds != FOREVER {
t.Errorf("Expected default of FOREVER when EventTimeToLiveSeconds is 0. instead: %d",
manager.subManager.EventTimeToLiveSeconds)
}
manager.Shutdown()
}
// Confirm defaults for options set to zero value
// either explicitly like so:
if manager, err := StartLongpoll(Options{
LoggingEnabled: false,
MaxLongpollTimeoutSeconds: 0,
MaxEventBufferSize: 0,
EventTimeToLiveSeconds: 0,
DeleteEventAfterFirstRetrieval: false,
}); err != nil {
t.Errorf("Unxpected error when calling StartLongpoll with valid options")
} else {
if manager.subManager.EventTimeToLiveSeconds != FOREVER {
t.Errorf("Expected default of FOREVER when EventTimeToLiveSeconds is 0. instead: %d",
manager.subManager.EventTimeToLiveSeconds)
}
if manager.subManager.MaxLongpollTimeoutSeconds != 120 {
t.Errorf("Expected default of 120 when MaxLongpollTimeoutSeconds is 0. instead: %d",
manager.subManager.MaxLongpollTimeoutSeconds)
}
if manager.subManager.MaxEventBufferSize != 250 {
t.Errorf("Expected default of 250 when MaxEventBufferSize is 0. instead: %d",
manager.subManager.MaxEventBufferSize)
}
if manager.subManager.LoggingEnabled != false {
t.Errorf("Expected default of false when LoggingEnabled is left out. instead: %t",
manager.subManager.LoggingEnabled)
}
if manager.subManager.DeleteEventAfterFirstRetrieval != false {
t.Errorf("Expected default of false when DeleteEventAfterFirstRetrieval is left out. instead: %t",
manager.subManager.DeleteEventAfterFirstRetrieval)
}
manager.Shutdown()
}
// or implicitly by never defining them:
if manager, err := StartLongpoll(Options{}); err != nil {
t.Errorf("Unxpected error when calling StartLongpoll with valid options")
} else {
if manager.subManager.EventTimeToLiveSeconds != FOREVER {
t.Errorf("Expected default of FOREVER when EventTimeToLiveSeconds is 0. instead: %d",
manager.subManager.EventTimeToLiveSeconds)
}
if manager.subManager.MaxLongpollTimeoutSeconds != 120 {
t.Errorf("Expected default of 120 when MaxLongpollTimeoutSeconds is 0. instead: %d",
manager.subManager.MaxLongpollTimeoutSeconds)
}
if manager.subManager.MaxEventBufferSize != 250 {
t.Errorf("Expected default of 250 when MaxEventBufferSize is 0. instead: %d",
manager.subManager.MaxEventBufferSize)
}
if manager.subManager.LoggingEnabled != false {
t.Errorf("Expected default of false when LoggingEnabled is left out. instead: %t",
manager.subManager.LoggingEnabled)
}
if manager.subManager.DeleteEventAfterFirstRetrieval != false {
t.Errorf("Expected default of false when DeleteEventAfterFirstRetrieval is left out. instead: %t",
manager.subManager.DeleteEventAfterFirstRetrieval)
}
manager.Shutdown()
}
}
func Test_LongpollManager_EventExpiration(t *testing.T) {
manager, _ := StartLongpoll(Options{
LoggingEnabled: true,
MaxLongpollTimeoutSeconds: 120,
MaxEventBufferSize: 100,
EventTimeToLiveSeconds: 1,
})
sm := manager.subManager
if len(sm.SubEventBuffer) != 0 {
t.Errorf("Unexpected category-to-buffer map size. was: %d, expected %d",
len(sm.SubEventBuffer), 0)
}
if sm.bufferPriorityQueue.Len() != 0 {
t.Errorf("Unexpected heap size. was: %d, expected: %d", sm.bufferPriorityQueue.Len(), 0)
}
manager.Publish("fruit", "apple")
time.Sleep(10 * time.Millisecond)
manager.Publish("veggie", "corn")
time.Sleep(750 * time.Millisecond)
manager.Publish("fruit", "orange")
// Allow sub manager's goroutine time to pull from channel.
// This sleep should cause us to yield and let the other goroutine run
time.Sleep(50 * time.Millisecond)
// Only ~800ms has went by, nothing should be expired out yet, so confirm
// all data is there
if len(sm.SubEventBuffer) != 2 {
t.Errorf("Unexpected category-to-buffer map size. was: %d, expected %d",
len(sm.SubEventBuffer), 2)
}
fruit_buffer, fruit_found := sm.SubEventBuffer["fruit"]
veggie_buffer, veggies_found := sm.SubEventBuffer["veggie"]
if !fruit_found || !veggies_found {
t.Errorf("failed to find fruit and veggie category event buffers")
}
if fruit_buffer.eventBuffer_ptr.List.Len() != 2 {
t.Errorf("Unexpected number of fruit events. was: %d, expected %d",
fruit_buffer.eventBuffer_ptr.List.Len(), 2)
}
if veggie_buffer.eventBuffer_ptr.List.Len() != 1 {
t.Errorf("Unexpected number of veggie events. was: %d, expected %d",
veggie_buffer.eventBuffer_ptr.List.Len(), 1)
}
if sm.bufferPriorityQueue.Len() != 2 {
t.Errorf("Unexpected heap size. was: %d, expected: %d", sm.bufferPriorityQueue.Len(), 2)
}
// Confirm top of heap is the veggie category since veggie is the category
// with the oldest last-event (even tho fruit was started first, it has a
// more recent event published on it--the heap sorts categories by how old
// each categories most recent event is)
if priority, peakErr := sm.bufferPriorityQueue.peakTopPriority(); peakErr != nil {
t.Errorf("Unexpected error checking top priority: %v", peakErr)
} else {
if priority != veggie_buffer.eventBuffer_ptr.List.Front().Value.(*lpEvent).Timestamp {
t.Errorf("Expected priority to be: %d, was: %d", priority,