-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgilmour_test.go
675 lines (548 loc) · 14.5 KB
/
gilmour_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
package gilmour
import (
"fmt"
"log"
"math/rand"
"os"
"strings"
"sync"
"testing"
"time"
r "gopkg.in/gilmour-libs/gilmour-e-go.v5/backends/redis"
"gopkg.in/gilmour-libs/gilmour-e-go.v5/proto"
"gopkg.in/gilmour-libs/gilmour-e-go.v5/ui"
)
const (
PingTopic = "ping"
PingResponse = "pong"
SleepTopic = "sleepy-ping"
)
var engine *Gilmour
var redis = r.MakeRedis("127.0.0.1:6379", "")
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randSeq(n int) string {
rand.Seed(time.Now().UTC().UnixNano())
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func isReplySubscribed(topic string) (bool, error) {
return isTopicSubscribed(topic, false)
}
func isSlotSubscribed(topic string) (bool, error) {
return isTopicSubscribed(topic, true)
}
func isTopicSubscribed(topic string, is_slot bool) (bool, error) {
if is_slot {
topic = engine.slotDestination(topic)
} else {
topic = engine.requestDestination(topic)
}
return redis.IsTopicSubscribed(topic)
}
func TestHealthSubscribe(t *testing.T) {
engine.SetHealthCheckEnabled()
topic := proto.HealthTopic(engine.getIdent())
if has, _ := isReplySubscribed(topic); !has {
t.Error(topic, "should have been subscribed")
}
}
func TestSubscribePing(t *testing.T) {
timeout := 3
handler_opts := NewHandlerOpts().SetTimeout(timeout)
sub, err := engine.ReplyTo(PingTopic, func(req *Request, resp *Message) {
var x string
req.Data(&x)
ui.Message("Topic %v Received %v", PingTopic, x)
ui.Message("Topic %v Sending %v", PingTopic, PingResponse)
resp.SetData(PingResponse)
}, handler_opts)
if err != nil {
t.Error("Error Subscribing", PingTopic, err.Error())
return
}
actualTimeout := sub.GetOpts().GetTimeout()
if actualTimeout != timeout {
t.Error("Handler should have timeout of", timeout, "seconds. Found", actualTimeout)
}
if has, _ := isReplySubscribed(PingTopic); !has {
t.Error("Topic", PingTopic, "should have been subscribed")
}
}
func TestSubscribePingResponse(t *testing.T) {
req := engine.NewRequest(PingTopic)
resp, err := req.Execute(NewMessage().SetData("ping?"))
if err != nil {
t.Error("Error in response", err.Error())
return
}
x := resp.Next()
var recv string
x.GetData(&recv)
if recv != PingResponse {
t.Error("Expecting", PingResponse, "Found", recv)
}
}
func TestSubscribePingSync(t *testing.T) {
req := engine.NewRequest(PingTopic)
response, err := req.Execute(NewMessage().SetData("ping?"))
if err != nil {
t.Error("Error in sync response", err.Error())
return
}
msg := response.Next()
var recv string
msg.GetData(&recv)
if recv != PingResponse {
t.Error("Expecting", PingResponse, "Found", recv)
}
}
func TestWildcardSlot(t *testing.T) {
opts := NewHandlerOpts().SetGroup("wildcard_group")
topic := fmt.Sprintf("%v*", PingTopic)
_, err := engine.Slot(topic, func(*Request) {}, opts)
if err != nil {
t.Error("Error Subscribing", PingTopic, err.Error())
}
}
func TestWildcardReply(t *testing.T) {
topic := fmt.Sprintf("%v*", PingTopic)
_, err := engine.ReplyTo(topic, func(req *Request, resp *Message) {}, nil)
if err == nil {
t.Error("ReplyTo cannot have wildcard topics.")
}
}
func TestPublisherSleep(t *testing.T) {
_, err := engine.ReplyTo(
SleepTopic,
func(req *Request, resp *Message) {
var delay int
req.Data(&delay)
time.Sleep(time.Duration(delay) * time.Second)
resp.SetData(PingResponse)
}, nil,
)
if err != nil {
t.Error("Error Subscribing", SleepTopic, err.Error())
return
}
if has, _ := isReplySubscribed(SleepTopic); !has {
t.Error("Topic", SleepTopic, "should have been subscribed")
}
}
func TestHealthGetAll(t *testing.T) {
idents, err := redis.ActiveIdents()
if err != nil {
t.Error(err)
}
val, ok := idents[engine.getIdent()]
if !ok || val != "true" {
t.Error("Ident is missing in the Health ident")
}
}
func TestUnsubscribe(t *testing.T) {
topic := randSeq(10)
sub, err := engine.Slot(topic, func(req *Request) {}, nil)
if err != nil {
t.Error("Error Subscribing", topic, err.Error())
return
}
if has, _ := isSlotSubscribed(topic); !has {
t.Error(topic, "should have been subscribed")
}
engine.UnsubscribeSlot(topic, sub)
if has, _ := isSlotSubscribed(topic); has {
t.Error("Topic", topic, "should have been unsubscribed")
}
}
func TestRelayFromSubscriber(t *testing.T) {
}
func TestTwiceSlot(t *testing.T) {
topic := randSeq(10)
opts := NewHandlerOpts()
subs := []*Subscription{}
defer func() {
for _, s := range subs {
engine.UnsubscribeSlot(topic, s)
}
}()
for i := 0; i < 2; i++ {
sub, err := engine.Slot(topic, func(_ *Request) {}, opts)
if sub != nil {
subs = append(subs, sub)
} else if err != nil {
t.Error("Cannot subscribe. Error", err.Error())
}
}
}
func TestTwiceSlotFail(t *testing.T) {
topic := randSeq(10)
count := 2
opts := NewHandlerOpts().SetGroup("unique")
subs := []*Subscription{}
defer func() {
for _, s := range subs {
engine.UnsubscribeSlot(topic, s)
}
}()
for i := 0; i < count; i++ {
sub, err := engine.Slot(topic, func(_ *Request) {}, opts)
if sub != nil {
subs = append(subs, sub)
} else if i == 1 {
if err == nil {
t.Error("Should now allow second Subscription citing duplication.")
}
} else if err != nil {
t.Error("Cannot subscribe. Error", err.Error())
}
}
}
func TestTwiceReplyToFail(t *testing.T) {
topic := randSeq(10)
count := 2
opts := NewHandlerOpts() //Note, we did not pass a group.
subs := []*Subscription{}
defer func() {
for _, s := range subs {
engine.UnsubscribeReply(topic, s)
}
}()
for i := 0; i < count; i++ {
sub, err := engine.ReplyTo(topic, func(_ *Request, _ *Message) {}, opts)
if sub != nil {
subs = append(subs, sub)
} else if i == 1 {
if err == nil {
t.Error("Should now allow second Subscription citing duplication.")
}
} else if err != nil {
t.Error("Cannot subscribe. Error", err.Error())
}
}
}
type slotStruct struct {
Args []string `json:"args"`
}
type failedSlotStruct struct {
args []string `json:"args"`
}
func TestSignalSlotStruct(t *testing.T) {
topic := randSeq(10)
out_chan := make(chan *slotStruct, 1)
opts := NewHandlerOpts()
sub, err := engine.Slot(topic, func(req *Request) {
var x slotStruct
req.Data(&x)
out_chan <- &x
}, opts)
defer engine.UnsubscribeSlot(topic, sub)
if err != nil {
t.Error(err.Error())
return
}
data := slotStruct{[]string{"a", "b", "c"}}
//Publish a message to random topic
engine.Signal(topic, NewMessage().SetData(data))
// Select Case, once and that should work.
select {
case result := <-out_chan:
if len(result.Args) != 3 {
t.Error("Should have received 3 strings in data")
}
case <-time.After(time.Second * 2):
t.Error("*Message should be twice, timed out instead")
}
}
// Should fail because of unexported field in struct
func TestSignalSlotStructFailed(t *testing.T) {
topic := randSeq(10)
out_chan := make(chan *failedSlotStruct, 1)
opts := NewHandlerOpts()
sub, err := engine.Slot(topic, func(req *Request) {
var x failedSlotStruct
req.Data(&x)
out_chan <- &x
}, opts)
defer engine.UnsubscribeSlot(topic, sub)
if err != nil {
t.Error(err.Error())
return
}
data := failedSlotStruct{[]string{"a", "b", "c"}}
//Publish a message to random topic
engine.Signal(topic, NewMessage().SetData(data))
// Select Case, once and that should work.
select {
case result := <-out_chan:
if len(result.args) != 0 {
t.Error("Should not have received any string in data")
}
case <-time.After(time.Second * 2):
t.Error("*Message should be twice, timed out instead")
}
engine.UnsubscribeSlot(topic, sub)
}
func TestSendOnceReceiveTwice(t *testing.T) {
topic := randSeq(10)
count := 2
out := []string{}
subs := []*Subscription{}
// cleanup. Unsubscribe from all subscribed channels.
defer func() {
for _, sub := range subs {
engine.UnsubscribeSlot(topic, sub)
}
// Confirm that the topic was Indeed unsubscribed.
if has, _ := isSlotSubscribed(topic); has {
t.Error("Topic", topic, "should have been unsubscribed")
}
}()
out_chan := make(chan string, count)
// Subscribe x no. of times
for i := 0; i < count; i++ {
data := fmt.Sprintf("hello %v", i)
opts := NewHandlerOpts().SetGroup(randSeq(10))
sub, err := engine.Slot(topic, func(_ *Request) {
out_chan <- data
}, opts)
if err != nil {
t.Error("Error Subscribing", err.Error())
return
}
subs = append(subs, sub)
}
//Publish a message to random topic
engine.Signal(topic, NewMessage().SetData("ping?"))
// Select Case, once and that should work.
for i := 0; i < count; i++ {
select {
case result := <-out_chan:
out = append(out, result)
case <-time.After(time.Second * 2):
t.Error("*Message should be twice, timed out instead")
}
}
// Results should be received twice.
if len(out) != count {
t.Error("*Message should be returned ", count, "items. Found", out)
}
}
func TestHealthResponse(t *testing.T) {
out_chan := make(chan string, 1)
data := NewMessage().SetData("is-healthy?")
req := engine.NewRequest(proto.HealthTopic(engine.getIdent()))
resp, err := req.Execute(data)
if err != nil {
t.Error(err)
}
msg := resp.Next()
x := []string{}
msg.GetData(&x)
if len(x) > 0 {
out_chan <- "healthy"
} else {
out_chan <- "false"
}
select {
case result := <-out_chan:
if result != "healthy" {
t.Error("*Message should be healthy. Found", result)
}
case <-time.After(time.Second * 5):
t.Error("*Message should be", PingResponse, "timed out instead")
}
}
func TestReceiveOnWildcard(t *testing.T) {
topic := fmt.Sprintf("%v*", PingTopic)
out_chan := make(chan string, 1)
//Subscribe to the wildcard topic.
sub, _ := engine.Slot(
topic,
func(_ *Request) {
out_chan <- PingResponse
},
nil,
)
//Publish a message to random topic
engine.Signal("pingworld", NewMessage().SetData("ping?"))
// Select Case, once and that should work.
select {
case <-out_chan:
// True Case.
case <-time.After(time.Second * 2):
t.Error("*Message should be received, timed out instead")
}
// cleanup. Unsubscribe from all subscribed channels.
engine.UnsubscribeSlot(topic, sub)
// Confirm that the topic was Indeed unsubscribed.
if has, _ := isSlotSubscribed(topic); has {
t.Error("Topic", topic, "should have been unsubscribed")
}
}
func TestSendAndReceive(t *testing.T) {
out_chan := make(chan string, 1)
data := NewMessage().SetData("ping?")
req := engine.NewRequest(PingTopic)
resp, err := req.Execute(data)
if err != nil {
t.Error(err)
}
msg := resp.Next()
var x string
msg.GetData(&x)
out_chan <- x
select {
case result := <-out_chan:
if result != PingResponse {
t.Error("*Message should be", PingResponse, "Found", result)
}
case <-time.After(time.Second * 5):
t.Error("*Message should be", PingResponse, "timed out instead")
}
}
func TestPublisherTimeout(t *testing.T) {
out_chan := make(chan string, 1)
sleepFor := 5
data := NewMessage().SetData(sleepFor)
opts := NewRequestOpts().SetTimeout(2)
req := engine.NewRequestWithOpts(SleepTopic, opts)
resp, err := req.Execute(data)
if err != nil {
t.Error(err)
}
msg := resp.Next()
var x string
msg.GetData(&x)
out_chan <- x
select {
case result := <-out_chan:
if result != "Execution timed out" {
t.Error("*Message should be 'Execution timed out' Found", result)
}
case <-time.After(time.Second * time.Duration(sleepFor)):
t.Error("*Message should be", "Execution timed out", "timed out instead")
}
}
func TestSansListenerSlot(t *testing.T) {
_, err := engine.Signal("humpty-dumpty", nil)
if err == nil {
t.Error("Slots return 404")
} else if !strings.Contains(err.Error(), "not received") {
t.Error("Slots without recivers should throw error.")
}
}
func TestSansListenerRequest(t *testing.T) {
req := engine.NewRequest("humpty-dumpty")
_, err := req.Execute(nil)
if err == nil || !strings.Contains(err.Error(), "listeners") {
t.Error(err.Error())
}
}
func TestSubscriberTimeout(t *testing.T) {
out_chan := make(chan string, 1)
topic := "sleep_delayed"
sub, err := engine.ReplyTo(
topic,
func(req *Request, resp *Message) {
time.Sleep(time.Second * 4)
resp.SetData(PingResponse)
},
NewHandlerOpts().SetTimeout(2),
)
if err != nil {
t.Error("Error Subscribing", PingTopic, err.Error())
return
}
data := NewMessage().SetData("send")
req := engine.NewRequest(topic)
resp, err := req.Execute(data)
if err != nil {
t.Error(err)
}
msg := resp.Next()
var x string
msg.GetData(&x)
out_chan <- x
select {
case result := <-out_chan:
if result != "Execution timed out" {
t.Error("*Message should be Execution timed out. Found", result)
}
case <-time.After(time.Second * 5):
t.Error("*Message should be", PingResponse, "timed out instead")
}
engine.UnsubscribeReply(topic, sub)
}
func TestHandlerException(t *testing.T) {
out_chan := make(chan int, 1)
topic := randSeq(10)
sub, err := engine.ReplyTo(topic, func(req *Request, resp *Message) {
// Just to induce errors, access a null pointers's method.
var x *HandlerOpts
log.Println(x.GetGroup())
}, nil)
if err != nil {
t.Error("Error Subscribing", PingTopic, err.Error())
return
}
data := NewMessage().SetData("send")
req := engine.NewRequest(topic)
resp, err := req.Execute(data)
if err != nil {
t.Error(err)
}
msg := resp.Next()
out_chan <- msg.GetCode()
select {
case result := <-out_chan:
if result != 500 {
t.Error("*Message should raise exception")
}
case <-time.After(time.Second * 5):
t.Error("*Message should have raised Exception, timed out instead")
}
engine.UnsubscribeReply(topic, sub)
}
func TestSansListener(t *testing.T) {
data := NewMessage().SetData("ping?")
if _, err := engine.Signal("ping-sans-listener", data); err != nil {
t.Error(err)
}
}
func TestConfirmSansListener(t *testing.T) {
data := NewMessage().SetData("ping?")
req := engine.NewRequest("ping-confirm-sans-listener")
if _, err := req.Execute(data); err != nil {
if !strings.Contains(err.Error(), "active listeners") {
t.Error(err.Error())
}
}
}
func waitBeforeExiting(interval int) {
var wg sync.WaitGroup
wg.Add(1)
time.AfterFunc(time.Duration(interval)*time.Second, func() {
wg.Done()
})
wg.Wait()
}
var initializers []func(*Gilmour)
func attachSetup(f func(*Gilmour)) {
initializers = append(initializers, f)
}
func TestMain(m *testing.M) {
ui.SetLevel(ui.Levels.Message)
engine = Get(redis)
for _, f := range initializers {
f(engine)
}
engine.Start()
status := m.Run()
waitBeforeExiting(2) //Wait 5 seconds before exiting.
engine.Stop()
waitBeforeExiting(2) //Wait 2 more seconds before exiting.
os.Exit(status)
}