-
Notifications
You must be signed in to change notification settings - Fork 9
/
rabbit_test.go
962 lines (756 loc) · 24.4 KB
/
rabbit_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
// NOTE: These tests require RabbitMQ to be available on "amqp://localhost"
//
// Make sure that you do `docker-compose up` before running tests
package rabbit
import (
"context"
"log"
"sync"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
// to test with logrus, uncomment the following
// and the log initialiser in generateOptions()
// "github.com/sirupsen/logrus"
amqp "github.com/rabbitmq/amqp091-go"
)
var _ = Describe("Rabbit", func() {
var (
opts *Options
r *Rabbit
ch *amqp.Channel
)
// This runs *after* all of the BeforeEach's AND *before* each It() block
JustBeforeEach(func() {
var err error
opts = generateOptions()
r, err = New(opts)
Expect(err).ToNot(HaveOccurred())
Expect(r).ToNot(BeNil())
ch, err = connect(opts)
Expect(err).ToNot(HaveOccurred())
Expect(ch).ToNot(BeNil())
})
Describe("New", func() {
When("instantiating rabbit", func() {
It("happy: should return a rabbit instance", func() {
opts := generateOptions()
r, err := New(opts)
Expect(err).ToNot(HaveOccurred())
Expect(r).ToNot(BeNil())
})
It("by default, uses Both mode", func() {
Expect(opts.Mode).To(Equal(Both))
Expect(r.Options.Mode).To(Equal(Both))
})
It("should error with missing options", func() {
r, err := New(nil)
Expect(err).ToNot(BeNil())
Expect(err.Error()).To(ContainSubstring("cannot be nil"))
Expect(r).To(BeNil())
})
It("should error with unreachable rabbit server", func() {
opts := generateOptions()
opts.URLs = []string{"amqp://bad-url"}
r, err := New(opts)
Expect(err).ToNot(BeNil())
Expect(err.Error()).To(ContainSubstring("unable to dial server"))
Expect(r).To(BeNil())
})
It("happy: it should succeed after having failed on unreachable rabbit server", func() {
opts := generateOptions()
opts.URLs = []string{"amqp://bad-url", "amqp://localhost"}
r, err := New(opts)
Expect(err).To(BeNil())
Expect(r).ToNot(BeNil())
})
It("instantiates various internals", func() {
opts := generateOptions()
r, err := New(opts)
Expect(err).To(BeNil())
Expect(r).ToNot(BeNil())
Expect(r.ctx).ToNot(BeNil())
Expect(r.cancel).ToNot(BeNil())
Expect(r.Conn).ToNot(BeNil())
Expect(r.ConsumerRWMutex).ToNot(BeNil())
Expect(r.NotifyCloseChan).ToNot(BeNil())
Expect(r.ProducerRWMutex).ToNot(BeNil())
Expect(r.Options).ToNot(BeNil())
})
It("launches NotifyCloseChan watcher", func() {
opts := generateOptions()
r, err := New(opts)
Expect(err).To(BeNil())
Expect(r).ToNot(BeNil())
// Before we write errors to the notify channel, copy previous
// conn and channels so we can compare them after reconnect
oldConn := r.Conn
oldNotifyCloseChan := r.NotifyCloseChan
oldConsumerDeliveryChannel := r.ConsumerDeliveryChannel
// Write an error to the NotifyCloseChan
r.NotifyCloseChan <- &amqp.Error{
Code: 0,
Reason: "Test failure",
Server: false,
Recover: false,
}
// Give our watcher a moment to see the msg and cause a reconnect
time.Sleep(100 * time.Millisecond)
// We should've reconnected and got a new conn
Expect(r.Conn).ToNot(BeNil())
Expect(r.Conn).To(BeAssignableToTypeOf(&amqp.Connection{}))
Expect(oldConn).ToNot(Equal(r.Conn))
// We should also get new channels
Expect(r.NotifyCloseChan).ToNot(BeNil())
Expect(r.ConsumerDeliveryChannel).ToNot(BeNil())
Expect(oldNotifyCloseChan).ToNot(Equal(r.NotifyCloseChan))
Expect(oldConsumerDeliveryChannel).ToNot(Equal(r.ConsumerDeliveryChannel))
})
})
})
Describe("Consume", func() {
var (
errChan = make(chan *ConsumeError, 1)
)
When("attempting to consume messages in producer mode", func() {
It("Consume should not block and immediately return", func() {
opts.Mode = Producer
ra, err := New(opts)
Expect(err).ToNot(HaveOccurred())
Expect(ra).ToNot(BeNil())
var exit bool
go func() {
r.Consume(nil, nil, func(m amqp.Delivery) error {
return nil
})
exit = true
}()
// Give the goroutine a little to start up
time.Sleep(50 * time.Millisecond)
Expect(exit).To(BeTrue())
})
})
When("consuming messages with a context", func() {
It("run function is executed with inbound message", func() {
receivedMessages := make([]amqp.Delivery, 0)
// Launch consumer
go func() {
r.Consume(context.Background(), errChan, func(msg amqp.Delivery) error {
receivedMessages = append(receivedMessages, msg)
return nil
})
}()
messages := generateRandomStrings(10)
// Publish messages
publishErr := publishMessages(ch, opts, messages)
Expect(publishErr).To(BeNil())
// Wait
time.Sleep(100 * time.Millisecond)
// Verify messages we received
stopErr := r.Stop()
Expect(stopErr).ToNot(HaveOccurred())
var data []string
// Verify message attributes
for _, msg := range receivedMessages {
Expect(msg.Exchange).To(Equal(opts.Bindings[0].ExchangeName))
Expect(msg.RoutingKey).To(Equal(opts.Bindings[0].BindingKeys[0]))
Expect(msg.ConsumerTag).To(Equal(opts.ConsumerTag))
data = append(data, string(msg.Body))
}
Expect(messages).To(Equal(data))
})
It("context can be used to cancel consume", func() {
ctx, cancel := context.WithCancel(context.Background())
receivedMessages := make([]amqp.Delivery, 0)
var exit bool
// Launch consumer
go func() {
r.Consume(ctx, errChan, func(msg amqp.Delivery) error {
receivedMessages = append(receivedMessages, msg)
return nil
})
exit = true
}()
messages := generateRandomStrings(20)
// Publish 10 messages -> cancel -> publish remainder of messages ->
// verify runfunc was hit only 10 times
publishErr1 := publishMessages(ch, opts, messages[0:10])
Expect(publishErr1).ToNot(HaveOccurred())
// Wait a moment for consumer to pick up messages
time.Sleep(100 * time.Millisecond)
cancel()
// Wait a moment for consumer to quit
time.Sleep(100 * time.Millisecond)
publishErr2 := publishMessages(ch, opts, messages[10:])
Expect(publishErr2).ToNot(HaveOccurred())
Expect(len(receivedMessages)).To(Equal(10))
Expect(exit).To(BeTrue())
})
})
When("consuming messages with an error channel", func() {
It("any errors returned by run func are passed to error channel", func() {
go func() {
r.Consume(context.Background(), errChan, func(msg amqp.Delivery) error {
return errors.New("stuff broke")
})
}()
messages := generateRandomStrings(1)
publishErr := publishMessages(ch, opts, messages)
Expect(publishErr).ToNot(HaveOccurred())
Eventually(func() string {
consumeErr := <-errChan
return consumeErr.Error.Error()
}).Should(ContainSubstring("stuff broke"))
})
})
When("when a nil error channel is passed in", func() {
It("errors are discarded and Consume() continues to work", func() {
receivedMessages := make([]string, 0)
go func() {
r.Consume(context.Background(), nil, func(msg amqp.Delivery) error {
receivedMessages = append(receivedMessages, string(msg.Body))
return errors.New("stuff broke")
})
}()
// Publish a handful of messages
messages := generateRandomStrings(10)
publishErr := publishMessages(ch, opts, messages)
Expect(publishErr).To(BeNil())
// Wait
time.Sleep(100 * time.Millisecond)
// Verify messages we received
stopErr := r.Stop()
Expect(stopErr).ToNot(HaveOccurred())
// Verify message attributes
Expect(messages).To(Equal(receivedMessages))
})
})
When("a nil context is passed in", func() {
It("Consume() continues to work", func() {
receivedMessages := make([]string, 0)
go func() {
r.Consume(nil, nil, func(msg amqp.Delivery) error {
receivedMessages = append(receivedMessages, string(msg.Body))
return errors.New("stuff broke")
})
}()
// Publish a handful of messages
messages := generateRandomStrings(10)
publishErr := publishMessages(ch, opts, messages)
Expect(publishErr).To(BeNil())
// Wait
time.Sleep(100 * time.Millisecond)
// Verify messages we received
stopErr := r.Stop()
Expect(stopErr).ToNot(HaveOccurred())
// Verify message attributes
Expect(messages).To(Equal(receivedMessages))
})
})
})
Describe("ConsumeOnce", func() {
When("Mode is Producer", func() {
It("will return an error", func() {
opts.Mode = Producer
ra, err := New(opts)
Expect(err).ToNot(HaveOccurred())
Expect(ra).ToNot(BeNil())
err = ra.ConsumeOnce(nil, func(m amqp.Delivery) error { return nil })
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("library is configured in Producer mode"))
})
})
When("passed context is nil", func() {
It("will continue to work", func() {
var receivedMessage string
var consumeErr error
var exit bool
go func() {
consumeErr = r.ConsumeOnce(nil, func(msg amqp.Delivery) error {
receivedMessage = string(msg.Body)
return nil
})
exit = true
}()
// Wait a moment for consumer to start
time.Sleep(100 * time.Millisecond)
// Generate a handful of messages
messages := generateRandomStrings(10)
publishErr := publishMessages(ch, opts, messages)
Expect(publishErr).ToNot(HaveOccurred())
// Wait a moment for consumer to get the message
time.Sleep(100 * time.Millisecond)
Expect(consumeErr).ToNot(HaveOccurred())
// Received message should be the same as the first message
Expect(receivedMessage).To(Equal(messages[0]))
// Goroutine should've exited
Expect(exit).To(BeTrue())
})
})
When("context is passed", func() {
It("will listen for cancellation", func() {
var consumeErr error
var exit bool
var receivedMessage string
ctx, cancel := context.WithCancel(context.Background())
go func() {
consumeErr = r.ConsumeOnce(ctx, func(msg amqp.Delivery) error {
receivedMessage = string(msg.Body)
return nil
})
exit = true
}()
// Wait a moment for consumer to connect
time.Sleep(100 * time.Millisecond)
// Consumer should not have received a message or exited
Expect(receivedMessage).To(BeEmpty())
Expect(exit).To(BeFalse())
cancel()
// Wait for cancel to kick in
time.Sleep(100 * time.Millisecond)
// Goroutine should've exited
Expect(exit).To(BeTrue())
Expect(consumeErr).ToNot(HaveOccurred())
})
})
When("run func gets an error", func() {
It("will return the error to the user", func() {
var consumeErr error
var exit bool
go func() {
consumeErr = r.ConsumeOnce(nil, func(msg amqp.Delivery) error {
return errors.New("something broke")
})
exit = true
}()
// Wait a moment for consumer to connect
time.Sleep(100 * time.Millisecond)
// Generate and send a message
messages := generateRandomStrings(1)
publishErr := publishMessages(ch, opts, messages)
Expect(publishErr).ToNot(HaveOccurred())
// Wait a moment for consumer to receive the message
time.Sleep(100 * time.Millisecond)
// Goroutine should've exited
Expect(exit).To(BeTrue())
// Consumer should've returned correct error
Expect(consumeErr).To(HaveOccurred())
Expect(consumeErr.Error()).To(ContainSubstring("something broke"))
})
})
})
Describe("Publish", func() {
Context("happy path", func() {
It("correctly publishes message", func() {
var receivedMessage *amqp.Delivery
go func() {
var err error
receivedMessage, err = receiveMessage(ch, opts)
Expect(err).ToNot(HaveOccurred())
}()
time.Sleep(25 * time.Millisecond)
testMessage := []byte(uuid.NewV4().String())
publishErr := r.Publish(nil, opts.Bindings[0].BindingKeys[0], testMessage)
Expect(publishErr).ToNot(HaveOccurred())
// Give our consumer some time to receive the message
time.Sleep(100 * time.Millisecond)
Expect(receivedMessage.Body).To(Equal(testMessage))
Expect(receivedMessage.AppId).To(Equal(opts.AppID))
})
When("Mode is Consumer", func() {
It("should return an error", func() {
opts.Mode = Consumer
ra, err := New(opts)
Expect(err).ToNot(HaveOccurred())
Expect(ra).ToNot(BeNil())
err = ra.Publish(nil, "messages", []byte("test"))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("library is configured in Consumer mode"))
})
})
})
Context("context timeout", func() {
It("returns an error on context timeout", func() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
testMessage := []byte(uuid.NewV4().String())
publishErr := r.Publish(ctx, opts.Bindings[0].BindingKeys[0], testMessage)
Expect(publishErr).To(HaveOccurred())
})
})
When("producer server channel is nil", func() {
It("will generate a new server channel", func() {
r.ProducerServerChannel = nil
var receivedMessage *amqp.Delivery
go func() {
var err error
receivedMessage, err = receiveMessage(ch, opts)
Expect(err).ToNot(HaveOccurred())
}()
time.Sleep(25 * time.Millisecond)
testMessage := []byte(uuid.NewV4().String())
publishErr := r.Publish(nil, opts.Bindings[0].BindingKeys[0], testMessage)
Expect(publishErr).ToNot(HaveOccurred())
// Give our consumer some time to receive the message
time.Sleep(100 * time.Millisecond)
Expect(receivedMessage.Body).To(Equal(testMessage))
})
})
})
Describe("Stop", func() {
When("consuming messages via Consume()", func() {
It("Stop() should release Consume() and return", func() {
var receivedMessage string
var exit bool
go func() {
r.Consume(nil, nil, func(msg amqp.Delivery) error {
receivedMessage = string(msg.Body)
return nil
})
exit = true
}()
// Wait a moment for consumer to start
time.Sleep(100 * time.Millisecond)
// Stop the consumer
stopErr := r.Stop()
time.Sleep(100 * time.Millisecond)
// Verify that stop did not error and the goroutine exited
Expect(stopErr).ToNot(HaveOccurred())
Expect(receivedMessage).To(BeEmpty()) // jic
Expect(exit).To(BeTrue())
})
})
})
Describe("Close", func() {
When("called after instantiating new rabbit", func() {
It("does not error", func() {
err := r.Close()
Expect(err).ToNot(HaveOccurred())
})
})
When("called before Consume", func() {
It("should cause Consume to immediately return", func() {
err := r.Close()
Expect(err).ToNot(HaveOccurred())
// This shouldn't block because internal ctx func should have been called
r.Consume(nil, nil, func(m amqp.Delivery) error {
return nil
})
Expect(true).To(BeTrue())
})
})
When("called before ConsumeOnce", func() {
It("ConsumeOnce should timeout", func() {
err := r.Close()
Expect(err).ToNot(HaveOccurred())
// This shouldn't block because internal ctx func should have been called
err = r.ConsumeOnce(nil, func(m amqp.Delivery) error {
return nil
})
Expect(err).To(HaveOccurred())
Expect(err).To(Equal(ErrShutdown))
})
})
When("called before Publish", func() {
It("Publish should error", func() {
err := r.Close()
Expect(err).ToNot(HaveOccurred())
err = r.Publish(nil, "messages", []byte("testing"))
Expect(err).To(HaveOccurred())
Expect(err).To(Equal(ErrShutdown))
})
})
})
Describe("validateOptions", func() {
Context("validation combinations", func() {
BeforeEach(func() {
opts = generateOptions()
})
It("errors with nil options", func() {
err := ValidateOptions(nil)
Expect(err).To(HaveOccurred())
})
It("should error on invalid mode", func() {
opts.Mode = 15
err := ValidateOptions(opts)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("invalid mode"))
})
It("errors when no valid URL is set", func() {
opts.URLs = []string{"", "", ""}
err := ValidateOptions(opts)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("At least one non-empty URL must be provided"))
})
It("errors when no URL is set", func() {
opts.URLs = []string{}
err := ValidateOptions(opts)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("At least one non-empty URL must be provided"))
})
It("errors when no exchange is specified", func() {
opts.URLs = []string{
"amqp://whatever",
}
// empty/nil bindings
opts.Bindings = []Binding{}
err := ValidateOptions(opts)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("At least one Exchange must be specified"))
})
It("errors when multiple exchanges are specified in Producer/Both mode", func() {
opts.Bindings = []Binding{
{
ExchangeName: "exchange1",
ExchangeDeclare: false,
ExchangeType: "",
},
{
ExchangeName: "exchange2",
ExchangeDeclare: false,
ExchangeType: "",
},
}
opts.URLs = []string{
"amqp://whatever",
}
opts.Mode = Producer
err := ValidateOptions(opts)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Exactly one Exchange must be specified when publishing messages"))
opts.Mode = Both
err = ValidateOptions(opts)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Exactly one Exchange must be specified when publishing messages"))
})
It("only checks ExchangeType if ExchangeDeclare is true", func() {
opts.Bindings = []Binding{
{
ExchangeName: "exchange1",
ExchangeDeclare: false,
ExchangeType: "",
BindingKeys: []string{
"routingeKey1",
"routingeKey2",
},
},
}
opts.URLs = []string{
"amqp://whatever",
}
opts.Mode = Consumer
err := ValidateOptions(opts)
Expect(err).ToNot(HaveOccurred())
opts.Bindings[0].ExchangeDeclare = true
opts.Bindings[0].ExchangeType = ""
err = ValidateOptions(opts)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("ExchangeType cannot be empty"))
})
It("errors if ExchangeName is unset", func() {
opts.Bindings = []Binding{
{
ExchangeName: "",
},
}
opts.URLs = []string{
"amqp://whatever",
}
err := ValidateOptions(opts)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("ExchangeName cannot be empty"))
})
It("errors if BindingKeys is unset", func() {
opts.Bindings = []Binding{
{
ExchangeName: "exchange1",
BindingKeys: []string{},
},
}
opts.URLs = []string{
"amqp://whatever",
}
err := ValidateOptions(opts)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("At least one BindingKeys must be specified"))
})
It("sets RetryConnect to default if unset", func() {
opts.RetryReconnectSec = 0
err := ValidateOptions(opts)
Expect(err).ToNot(HaveOccurred())
Expect(opts.RetryReconnectSec).To(Equal(DefaultRetryReconnectSec))
})
It("sets AppID and ConsumerTag to default if unset", func() {
opts.AppID = ""
opts.ConsumerTag = ""
err := ValidateOptions(opts)
Expect(err).ToNot(HaveOccurred())
Expect(opts.ConsumerTag).To(ContainSubstring("c-rabbit-"))
Expect(opts.AppID).To(ContainSubstring("p-rabbit-"))
})
})
})
Describe("Reconnect testing", func() {
When("runWatcher receives reconnect signal", func() {
It("performs a reconnect", func() {
// TODO: Implement
})
})
When("runWatcher receives a notify close signal", func() {
It("performs a reconnect", func() {
// TODO: Implement
})
})
When("consumer receives amqp.Delivery with nil acknowledger", func() {
It("will send reconnect signal to ReconnectChan + send err to errCh", func() {
// Create our own rabbit instance with mock delivery channel
ctx, cancel := context.WithCancel(context.Background())
ac, err := amqp.Dial(opts.URLs[0])
Expect(err).ToNot(HaveOccurred())
notifyCloseCh := make(chan *amqp.Error)
reconnectCh := make(chan struct{}, 1)
deliveryCh := make(chan amqp.Delivery, 1)
errCh := make(chan *ConsumeError, 1)
r := &Rabbit{
Conn: ac,
ConsumerRWMutex: &sync.RWMutex{},
ConsumerWG: &sync.WaitGroup{},
NotifyCloseChan: notifyCloseCh,
ReconnectChan: reconnectCh,
ConsumerDeliveryChannel: deliveryCh,
ReconnectInProgressMtx: &sync.RWMutex{},
ProducerRWMutex: &sync.RWMutex{},
Options: opts,
log: &NoOpLogger{},
ctx: ctx,
cancel: cancel,
}
receivedMessage := false
// Listen for exactly one message
go func() {
r.Consume(ctx, errCh, func(msg amqp.Delivery) error {
receivedMessage = true
return nil
})
}()
// Write message to delivery channel
deliveryCh <- amqp.Delivery{
Acknowledger: nil,
MessageId: "reconnect-test-id-123",
Timestamp: time.Now(),
ConsumerTag: "reconnect-test",
Exchange: "fake-exchange",
RoutingKey: "fake-routing-key",
Body: []byte("foo"),
}
go func() {
defer GinkgoRecover()
consumeErr := <-errCh
Expect(consumeErr).ToNot(BeNil())
Expect(consumeErr.Error.Error()).To(ContainSubstring("nil acknowledger detected - sending reconnect signal"))
}()
// Give consume error goroutine enough time to start up
time.Sleep(time.Second)
Eventually(reconnectCh).Should(Receive())
Eventually(notifyCloseCh).ShouldNot(Receive())
// Consume func should NOT be executed (library should treat as error)
Eventually(receivedMessage).Should(BeFalse())
})
})
})
})
func generateOptions() *Options {
exchangeName := "rabbit-" + uuid.NewV4().String()
return &Options{
URLs: []string{"amqp://localhost"},
QueueName: "rabbit-" + uuid.NewV4().String(),
Bindings: []Binding{
{
ExchangeName: exchangeName,
ExchangeType: "topic",
ExchangeDeclare: true,
ExchangeDurable: false,
ExchangeAutoDelete: true,
BindingKeys: []string{exchangeName},
},
},
QosPrefetchCount: 0,
QosPrefetchSize: 0,
RetryReconnectSec: 10,
QueueDeclare: true,
QueueDurable: false,
QueueExclusive: false,
QueueAutoDelete: true,
AppID: "rabbit-test-producer",
ConsumerTag: "rabbit-test-consumer",
//Log: logrus.WithField("pkg", "rabbit"),
}
}
func generateRandomStrings(num int) []string {
generated := make([]string, 0)
for i := 0; i != num; i++ {
generated = append(generated, uuid.NewV4().String())
}
return generated
}
func connect(opts *Options) (*amqp.Channel, error) {
var err error
var ac *amqp.Connection
for _, url := range opts.URLs {
ac, err = amqp.Dial(url)
if err != nil {
ac = nil
} else {
break
}
}
if err != nil {
return nil, errors.Wrap(err, "unable to dial rabbit server")
}
ch, err := ac.Channel()
if err != nil {
return nil, errors.Wrap(err, "unable to instantiate channel")
}
return ch, nil
}
func publishMessages(ch *amqp.Channel, opts *Options, messages []string) error {
for _, v := range messages {
if err := ch.Publish(opts.Bindings[0].ExchangeName, opts.Bindings[0].BindingKeys[0], false, false, amqp.Publishing{
DeliveryMode: amqp.Persistent,
Body: []byte(v),
}); err != nil {
return err
}
}
return nil
}
func receiveMessage(ch *amqp.Channel, opts *Options) (*amqp.Delivery, error) {
tmpQueueName := "rabbit-receiveMessages-" + uuid.NewV4().String()
if _, err := ch.QueueDeclare(
tmpQueueName,
false,
true,
false,
false,
nil,
); err != nil {
return nil, errors.Wrap(err, "unable to declare queue")
}
if err := ch.QueueBind(tmpQueueName, opts.Bindings[0].BindingKeys[0], opts.Bindings[0].ExchangeName, false, nil); err != nil {
return nil, errors.Wrap(err, "unable to bind queue")
}
deliveryChan, err := ch.Consume(tmpQueueName, "", true, false, false, false, nil)
if err != nil {
return nil, errors.Wrap(err, "unable to create delivery channel")
}
select {
case m := <-deliveryChan:
log.Println("Test: received message in receiveMessage()")
return &m, nil
case <-time.After(5 * time.Second):
log.Println("Test: timed out waiting for message in receiveMessage()")
return nil, errors.New("timed out")
}
}