-
Notifications
You must be signed in to change notification settings - Fork 383
/
test_pubsub.go
1354 lines (1071 loc) · 36.3 KB
/
test_pubsub.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 tests
import (
"context"
"fmt"
"log"
"math/rand"
"os"
"os/exec"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
internalSubscriber "github.com/ThreeDotsLabs/watermill/internal/subscriber"
"github.com/ThreeDotsLabs/watermill"
"github.com/ThreeDotsLabs/watermill/internal"
"github.com/ThreeDotsLabs/watermill/message"
"github.com/ThreeDotsLabs/watermill/message/subscriber"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var defaultTimeout = time.Second * 15
// TestPubSub is a universal test suite. Every Pub/Sub implementation should pass it
// before it's considered production ready.
//
// Execution of the tests may be a bit different for every Pub/Sub. You can configure it by changing provided Features.
func TestPubSub(
t *testing.T,
features Features,
pubSubConstructor PubSubConstructor,
consumerGroupPubSubConstructor ConsumerGroupPubSubConstructor,
) {
testFuncs := []struct {
Func func(t *testing.T, tCtx TestContext, pubSubConstructor PubSubConstructor)
NotParallel bool
}{
{Func: TestPublishSubscribe},
{Func: TestConcurrentSubscribe},
{Func: TestConcurrentSubscribeMultipleTopics},
{Func: TestResendOnError},
{Func: TestNoAck},
{Func: TestContinueAfterSubscribeClose},
{Func: TestConcurrentClose},
{Func: TestContinueAfterErrors},
{Func: TestPublishSubscribeInOrder},
{Func: TestPublisherClose},
{Func: TestTopic},
{Func: TestMessageCtx},
{Func: TestSubscribeCtx},
{Func: TestNewSubscriberReceivesOldMessages},
{
Func: TestReconnect,
NotParallel: true,
},
}
for i := range testFuncs {
testFunc := testFuncs[i]
runTest(
t,
getTestName(testFunc.Func),
func(t *testing.T, testCtx TestContext) {
testFunc.Func(t, testCtx, pubSubConstructor)
},
features,
!testFunc.NotParallel,
)
}
runTest(
t,
getTestName(TestConsumerGroups),
func(t *testing.T, testCtx TestContext) {
TestConsumerGroups(
t,
testCtx,
consumerGroupPubSubConstructor,
)
},
features,
true,
)
}
// Features are used to configure Pub/Subs implementations behaviour.
// Different features set decides also which, and how tests should be run.
type Features struct {
// ConsumerGroups should be true, if consumer groups are supported.
ConsumerGroups bool
// ExactlyOnceDelivery should be true, if exactly-once delivery is supported.
ExactlyOnceDelivery bool
// GuaranteedOrder should be true, if order of messages is guaranteed.
GuaranteedOrder bool
// Some Pub/Subs guarantee the order only when one subscriber is subscribed at a time.
GuaranteedOrderWithSingleSubscriber bool
// Persistent should be true, if messages are persistent between multiple instancees of a Pub/Sub
// (in practice, only GoChannel doesn't support that).
Persistent bool
// RestartServiceCommand is a command to test reconnects. It should restart the message broker.
// Example: []string{"docker", "restart", "rabbitmq"}
RestartServiceCommand []string
// RequireSingleInstance must be true,if a PubSub requires a single instance to work properly
// (for example: GoChannel implementation).
RequireSingleInstance bool
// NewSubscriberReceivesOldMessages should be set to true if messages are persisted even
// if they are already consumed (for example, like in Kafka).
NewSubscriberReceivesOldMessages bool
}
// RunOnlyFastTests returns true if -short flag was provided -race was not provided.
// Useful for excluding some slow tests.
func RunOnlyFastTests() bool {
return testing.Short() && !internal.RaceEnabled
}
// PubSubConstructor is a function that creates a Publisher and a Subscriber.
type PubSubConstructor func(t *testing.T) (message.Publisher, message.Subscriber)
// ConsumerGroupPubSubConstructor is a function that creates a Publisher and a Subscriber that use given consumer group.
type ConsumerGroupPubSubConstructor func(t *testing.T, consumerGroup string) (message.Publisher, message.Subscriber)
// SimpleMessage is deprecated: not used anywhere internally
type SimpleMessage struct {
Num int `json:"num"`
}
func getTestName(testFunc interface{}) string {
fullName := runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name()
nameSliced := strings.Split(fullName, ".")
return nameSliced[len(nameSliced)-1]
}
// TestID is a unique ID of a test.
type TestID string
// NewTestID returns a new unique TestID.
func NewTestID() TestID {
return TestID(watermill.NewUUID())
}
// TestContext is a collection of values that belong to a single test.
type TestContext struct {
// Unique ID of the test
TestID TestID
// PubSub features
Features Features
}
func runTest(
t *testing.T,
name string,
fn func(t *testing.T, testCtx TestContext),
features Features,
parallel bool,
) {
t.Run(name, func(t *testing.T) {
if parallel {
t.Parallel()
}
testID := NewTestID()
t.Run(string(testID), func(t *testing.T) {
tCtx := TestContext{
TestID: testID,
Features: features,
}
fn(t, tCtx)
})
})
}
const defaultStressTestTestsCount = 10
// TestPubSubStressTest runs stress tests on a chosen Pub/Sub.
func TestPubSubStressTest(
t *testing.T,
features Features,
pubSubConstructor PubSubConstructor,
consumerGroupPubSubConstructor ConsumerGroupPubSubConstructor,
) {
stressTestsCount, _ := strconv.ParseInt(os.Getenv("STRESS_TEST_COUNT"), 10, 64)
if stressTestsCount == 0 {
stressTestsCount = defaultStressTestTestsCount
}
for i := 0; i < int(stressTestsCount); i++ {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
t.Parallel()
TestPubSub(t, features, pubSubConstructor, consumerGroupPubSubConstructor)
})
}
}
// TestPublishSubscribe runs basic publish and subscribe tests on a chosen Pub/Sub.
func TestPublishSubscribe(
t *testing.T,
tCtx TestContext,
pubSubConstructor PubSubConstructor,
) {
pub, sub := pubSubConstructor(t)
topicName := testTopicName(tCtx.TestID)
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
var messagesToPublish []*message.Message
messagesPayloads := map[string][]byte{}
messagesTestMetadata := map[string]string{}
for i := 0; i < 100; i++ {
id := watermill.NewUUID()
testMetadata := watermill.NewUUID()
payload := []byte(fmt.Sprintf("%d", i))
msg := message.NewMessage(id, payload)
msg.Metadata.Set("test", testMetadata)
messagesTestMetadata[id] = testMetadata
messagesToPublish = append(messagesToPublish, msg)
messagesPayloads[id] = payload
}
err := publishWithRetry(pub, topicName, messagesToPublish...)
require.NoError(t, err, "cannot publish message")
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
receivedMessages, all := bulkRead(tCtx, messages, len(messagesToPublish), defaultTimeout*3)
assert.True(t, all)
AssertAllMessagesReceived(t, messagesToPublish, receivedMessages)
AssertMessagesPayloads(t, messagesPayloads, receivedMessages)
AssertMessagesMetadata(t, "test", messagesTestMetadata, receivedMessages)
closePubSub(t, pub, sub)
assertMessagesChannelClosed(t, messages)
}
// TestConcurrentSubscribe tests subscribing to messages by multiple concurrent subscribers.
func TestConcurrentSubscribe(
t *testing.T,
tCtx TestContext,
pubSubConstructor PubSubConstructor,
) {
pub, initSub := pubSubConstructor(t)
defer closePubSub(t, pub, initSub)
topicName := testTopicName(tCtx.TestID)
messagesCount := 5000
subscribersCount := 50
if testing.Short() {
messagesCount = 100
subscribersCount = 10
}
if subscribeInitializer, ok := initSub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
publishedMessages := AddSimpleMessagesParallel(t, messagesCount, pub, topicName, 50)
var sub message.Subscriber
if tCtx.Features.RequireSingleInstance {
sub = initSub
} else {
sub = createMultipliedSubscriber(t, pubSubConstructor, subscribersCount)
}
defer closePubSub(t, pub, sub)
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
receivedMessages, all := bulkRead(tCtx, messages, len(publishedMessages), defaultTimeout*3)
assert.True(t, all)
AssertAllMessagesReceived(t, publishedMessages, receivedMessages)
}
// TestConcurrentSubscribeMultipleTopics tests subscribing to messages by concurrent subscribers on multiple topics.
func TestConcurrentSubscribeMultipleTopics(
t *testing.T,
tCtx TestContext,
pubSubConstructor PubSubConstructor,
) {
pub, sub := pubSubConstructor(t)
defer closePubSub(t, pub, sub)
messagesCount := 100
topicsCount := 20
if testing.Short() {
messagesCount = 50
topicsCount = 10
}
var messagesToPublish []*message.Message
for i := 0; i < messagesCount; i++ {
id := watermill.NewUUID()
msg := message.NewMessage(id, nil)
messagesToPublish = append(messagesToPublish, msg)
}
subsWg := sync.WaitGroup{}
subsWg.Add(topicsCount)
receivedMessagesCh := make(chan message.Messages, topicsCount)
for i := 0; i < topicsCount; i++ {
topicName := testTopicName(tCtx.TestID) + fmt.Sprintf("-%d", i)
go func() {
defer subsWg.Done()
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
err := subscribeInitializer.SubscribeInitialize(topicName)
if err != nil {
t.Error(err)
}
}
err := publishWithRetry(pub, topicName, messagesToPublish...)
if err != nil {
t.Error(err)
}
messages, err := sub.Subscribe(context.Background(), topicName)
if err != nil {
t.Error(err)
}
topicMessages, _ := bulkRead(tCtx, messages, len(messagesToPublish), defaultTimeout*5)
receivedMessagesCh <- topicMessages
}()
}
subsWg.Wait()
close(receivedMessagesCh)
topicsReceivedMessages := 0
for msgs := range receivedMessagesCh {
AssertAllMessagesReceived(t, messagesToPublish, msgs)
topicsReceivedMessages++
}
assert.Equal(t, topicsCount, topicsReceivedMessages)
}
// TestPublishSubscribeInOrder tests if published messages are received in a proper order.
// This test is skipped for Pub/Subs that don't support GuaranteedOrder feature.
func TestPublishSubscribeInOrder(
t *testing.T,
tCtx TestContext,
pubSubConstructor PubSubConstructor,
) {
if !tCtx.Features.GuaranteedOrder {
t.Skipf("order is not guaranteed")
}
messagesCount := 1000
if testing.Short() {
messagesCount = 100
}
pub, initSub := pubSubConstructor(t)
defer closePubSub(t, pub, initSub)
topicName := testTopicName(tCtx.TestID)
if subscribeInitializer, ok := initSub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
var messagesToPublish []*message.Message
expectedMessages := map[string][]string{}
for i := 0; i < messagesCount; i++ {
id := watermill.NewUUID()
msgType := fmt.Sprintf("%d", i%16)
msg := message.NewMessage(id, []byte(msgType))
messagesToPublish = append(messagesToPublish, msg)
if _, ok := expectedMessages[msgType]; !ok {
expectedMessages[msgType] = []string{}
}
expectedMessages[msgType] = append(expectedMessages[msgType], msg.UUID)
}
err := publishWithRetry(pub, topicName, messagesToPublish...)
require.NoError(t, err)
var sub message.Subscriber
if tCtx.Features.RequireSingleInstance {
sub = initSub
} else {
subscribersCount := 10
if tCtx.Features.GuaranteedOrderWithSingleSubscriber {
subscribersCount = 1
}
sub = createMultipliedSubscriber(t, pubSubConstructor, subscribersCount)
defer require.NoError(t, sub.Close())
}
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
receivedMessages, all := bulkRead(tCtx, messages, len(messagesToPublish), defaultTimeout)
require.True(t, all, "not all messages received (%d of %d)", len(receivedMessages), len(messagesToPublish))
receivedMessagesByType := map[string][]string{}
for _, msg := range receivedMessages {
if _, ok := receivedMessagesByType[string(msg.Payload)]; !ok {
receivedMessagesByType[string(msg.Payload)] = []string{}
}
receivedMessagesByType[string(msg.Payload)] = append(receivedMessagesByType[string(msg.Payload)], msg.UUID)
}
require.Equal(t, len(receivedMessagesByType), len(expectedMessages))
require.Equal(t, len(receivedMessages), len(messagesToPublish))
for key, ids := range expectedMessages {
assert.Equal(t, ids, receivedMessagesByType[key])
}
}
// TestResendOnError tests if messages are re-delivered after the subscriber fails to process them.
func TestResendOnError(
t *testing.T,
tCtx TestContext,
pubSubConstructor PubSubConstructor,
) {
pub, sub := pubSubConstructor(t)
defer closePubSub(t, pub, sub)
topicName := testTopicName(tCtx.TestID)
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
messagesToSend := 100
nacksCount := 2
var publishedMessages message.Messages
allMessagesSent := make(chan struct{})
publishedMessages = PublishSimpleMessages(t, messagesToSend, pub, topicName)
close(allMessagesSent)
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
NackLoop:
for i := 0; i < nacksCount; i++ {
select {
case msg, closed := <-messages:
if !closed {
t.Fatal("messages channel closed before all received")
}
log.Println("sending err for ", msg.UUID)
msg.Nack()
case <-time.After(defaultTimeout):
break NackLoop
}
}
receivedMessages, _ := bulkRead(tCtx, messages, messagesToSend, defaultTimeout)
<-allMessagesSent
AssertAllMessagesReceived(t, publishedMessages, receivedMessages)
}
// TestNoAck tests if no new messages are received by the subscriber until the previous message is acknowledged.
// This test is skipped for Pub/Subs that don't support GuaranteedOrder feature.
func TestNoAck(
t *testing.T,
tCtx TestContext,
pubSubConstructor PubSubConstructor,
) {
if !tCtx.Features.GuaranteedOrder {
t.Skip("guaranteed order is required for this test")
}
pub, sub := pubSubConstructor(t)
defer closePubSub(t, pub, sub)
topicName := testTopicName(tCtx.TestID)
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
for i := 0; i < 2; i++ {
id := watermill.NewUUID()
log.Printf("sending %s", id)
msg := message.NewMessage(id, nil)
err := publishWithRetry(pub, topicName, msg)
require.NoError(t, err)
}
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
receivedMessage := make(chan struct{})
unlockAck := make(chan struct{}, 1)
go func() {
msg := <-messages
receivedMessage <- struct{}{}
<-unlockAck
msg.Ack()
}()
select {
case <-receivedMessage:
// ok
case <-time.After(defaultTimeout):
t.Fatal("timeouted")
}
select {
case msg := <-messages:
t.Fatalf("messages channel should be blocked since Ack() was not sent, received %s", msg.UUID)
case <-time.After(time.Millisecond * 100):
// ok
}
unlockAck <- struct{}{}
select {
case msg := <-messages:
msg.Ack()
case <-time.After(time.Second * 5):
t.Fatal("messages channel should be unblocked after Ack()")
}
if tCtx.Features.ExactlyOnceDelivery {
select {
case <-messages:
t.Fatal("msg should be not sent again")
case <-time.After(time.Millisecond * 50):
// ok
}
}
}
// TestContinueAfterSubscribeClose checks, that we don't lose messages after closing subscriber.
func TestContinueAfterSubscribeClose(
t *testing.T,
tCtx TestContext,
createPubSub PubSubConstructor,
) {
if !tCtx.Features.Persistent {
t.Skip("Non-Persistent is not supported yet")
}
if tCtx.Features.ExactlyOnceDelivery {
t.Skip("ExactlyOnceDelivery test is not supported yet")
}
totalMessagesCount := 5000
batches := 5
if testing.Short() {
totalMessagesCount = 50
batches = 2
}
batchSize := int(totalMessagesCount / batches)
readAttempts := batches * 4
pub, sub := createPubSub(t)
defer closePubSub(t, pub, sub)
topicName := testTopicName(tCtx.TestID)
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
publishedMessages := AddSimpleMessagesParallel(t, totalMessagesCount, pub, topicName, 50)
receivedMessages := map[string]*message.Message{}
for i := 0; i < readAttempts; i++ {
pub, sub := createPubSub(t)
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
messagesToRead := batchSize
messagesLeft := totalMessagesCount - len(receivedMessages)
if messagesToRead > messagesLeft {
messagesToRead = messagesLeft
}
receivedMessagesBatch, _ := bulkRead(tCtx, messages, messagesToRead, defaultTimeout)
closePubSub(t, pub, sub)
for _, msg := range receivedMessagesBatch {
receivedMessages[msg.UUID] = msg
}
closePubSub(t, pub, sub)
if len(receivedMessages) >= totalMessagesCount {
break
}
}
// to make this test more robust - let's consume all missing messages
// (we care here if we didn't lost any message, not if we received duplicated)
missingMessagesCount := totalMessagesCount - len(receivedMessages)
if missingMessagesCount > 0 && !tCtx.Features.ExactlyOnceDelivery {
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
defer closePubSub(t, pub, sub)
timeout := time.After(defaultTimeout)
MessagesLoop:
for len(receivedMessages) < totalMessagesCount {
select {
case msg, ok := <-messages:
if !ok {
break MessagesLoop
}
receivedMessages[msg.UUID] = msg
msg.Ack()
case <-timeout:
break MessagesLoop
}
}
}
// we need to deduplicate messages, because bulkRead will deduplicate only per one batch
uniqueReceivedMessages := message.Messages{}
for _, msg := range receivedMessages {
uniqueReceivedMessages = append(uniqueReceivedMessages, msg)
}
AssertAllMessagesReceived(t, publishedMessages, uniqueReceivedMessages)
}
// TestConcurrentClose tests if the Pub/Sub works correctly when subscribers are being closed concurrently.
func TestConcurrentClose(
t *testing.T,
tCtx TestContext,
createPubSub PubSubConstructor,
) {
if tCtx.Features.ExactlyOnceDelivery {
t.Skip("ExactlyOnceDelivery test is not supported yet")
}
topicName := testTopicName(tCtx.TestID)
createPub, createSub := createPubSub(t)
if subscribeInitializer, ok := createSub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
closePubSub(t, createPub, createSub)
totalMessagesCount := 50
closeWg := sync.WaitGroup{}
closeWg.Add(10)
for i := 0; i < 10; i++ {
go func() {
defer closeWg.Done()
pub, sub := createPubSub(t)
defer closePubSub(t, pub, sub)
_, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
}()
}
closeWg.Wait()
pub, sub := createPubSub(t)
expectedMessages := PublishSimpleMessages(t, totalMessagesCount, pub, topicName)
closePubSub(t, pub, sub)
pub, sub = createPubSub(t)
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
receivedMessages, all := bulkRead(tCtx, messages, len(expectedMessages), defaultTimeout*3)
assert.True(t, all)
AssertAllMessagesReceived(t, expectedMessages, receivedMessages)
closePubSub(t, pub, sub)
}
// TestContinueAfterErrors tests if messages are processed again after an initial failure.
func TestContinueAfterErrors(
t *testing.T,
tCtx TestContext,
createPubSub PubSubConstructor,
) {
pub, sub := createPubSub(t)
defer closePubSub(t, pub, sub)
topicName := testTopicName(tCtx.TestID)
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
totalMessagesCount := 50
subscribersToNack := 3
nacksPerSubscriber := 100
if testing.Short() {
subscribersToNack = 1
nacksPerSubscriber = 5
}
messagesToPublish := PublishSimpleMessages(t, totalMessagesCount, pub, topicName)
for i := 0; i < subscribersToNack; i++ {
var errorsPub message.Publisher
var errorsSub message.Subscriber
if !tCtx.Features.Persistent {
errorsPub = pub
errorsSub = sub
} else {
errorsPub, errorsSub = createPubSub(t)
}
messages, err := errorsSub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
for j := 0; j < nacksPerSubscriber; j++ {
select {
case msg := <-messages:
msg.Nack()
case <-time.After(defaultTimeout):
t.Fatal("no messages left, probably seek after error doesn't work")
}
}
if tCtx.Features.Persistent {
closePubSub(t, errorsPub, errorsSub)
}
}
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
// only nacks was sent, so all messages should be consumed
receivedMessages, _ := bulkRead(tCtx, messages, totalMessagesCount, defaultTimeout*6)
AssertAllMessagesReceived(t, messagesToPublish, receivedMessages)
}
// TestConsumerGroups tests if the consumer groups feature behaves correctly.
// This test is skipped for Pub/Sub that don't support ConsumerGroups feature.
func TestConsumerGroups(
t *testing.T,
tCtx TestContext,
pubSubConstructor ConsumerGroupPubSubConstructor,
) {
if !tCtx.Features.ConsumerGroups {
t.Skip("consumer groups are not supported")
}
publisherPub, publisherSub := pubSubConstructor(t, "test_"+watermill.NewUUID())
defer closePubSub(t, publisherPub, publisherSub)
topicName := testTopicName(tCtx.TestID)
if subscribeInitializer, ok := publisherSub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
totalMessagesCount := 50
group1 := generateConsumerGroup(t, pubSubConstructor, topicName)
group2 := generateConsumerGroup(t, pubSubConstructor, topicName)
messagesToPublish := PublishSimpleMessages(t, totalMessagesCount, publisherPub, topicName)
assertConsumerGroupReceivedMessages(t, tCtx, pubSubConstructor, group1, topicName, messagesToPublish)
assertConsumerGroupReceivedMessages(t, tCtx, pubSubConstructor, group2, topicName, messagesToPublish)
}
// TestPublisherClose sends big amount of messages and them run close to ensure that messages are not lost during adding.
func TestPublisherClose(
t *testing.T,
tCtx TestContext,
pubSubConstructor PubSubConstructor,
) {
pub, sub := pubSubConstructor(t)
defer closePubSub(t, pub, sub)
topicName := testTopicName(tCtx.TestID)
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
messagesCount := 10000
if testing.Short() {
messagesCount = 100
}
producedMessages := AddSimpleMessagesParallel(t, messagesCount, pub, topicName, 20)
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
receivedMessages, _ := bulkRead(tCtx, messages, messagesCount, defaultTimeout*3)
AssertAllMessagesReceived(t, producedMessages, receivedMessages)
}
// TestTopic tests if different topics work correctly in a Pub/Sub.
func TestTopic(
t *testing.T,
tCtx TestContext,
pubSubConstructor PubSubConstructor,
) {
pub, sub := pubSubConstructor(t)
defer closePubSub(t, pub, sub)
topic1 := testTopicName(tCtx.TestID) + "-1"
topic2 := testTopicName(tCtx.TestID) + "-2"
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topic1))
}
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topic2))
}
topic1Msg := message.NewMessage(watermill.NewUUID(), nil)
topic2Msg := message.NewMessage(watermill.NewUUID(), nil)
require.NoError(t, publishWithRetry(pub, topic1, topic1Msg))
require.NoError(t, publishWithRetry(pub, topic2, topic2Msg))
messagesTopic1, err := sub.Subscribe(context.Background(), topic1)
require.NoError(t, err)
messagesTopic2, err := sub.Subscribe(context.Background(), topic2)
require.NoError(t, err)
messagesConsumedTopic1, received := bulkRead(tCtx, messagesTopic1, 1, defaultTimeout)
require.True(t, received, "no messages received in topic %s", topic1)
messagesConsumedTopic2, received := bulkRead(tCtx, messagesTopic2, 1, defaultTimeout)
require.True(t, received, "no messages received in topic %s", topic2)
assert.Equal(t, messagesConsumedTopic1.IDs()[0], topic1Msg.UUID)
assert.Equal(t, messagesConsumedTopic2.IDs()[0], topic2Msg.UUID)
}
// TestMessageCtx tests if the Message's Context works correctly.
func TestMessageCtx(
t *testing.T,
tCtx TestContext,
pubSubConstructor PubSubConstructor,
) {
if tCtx.Features.ExactlyOnceDelivery {
// with ExactlyOnce delivery (at least as implemented by NATS jetstream)
// the second message will never be received because the broker deduplicates
// by message ID.
t.Skip("ExactlyOnceDelivery test is not supported yet")
}
pub, sub := pubSubConstructor(t)
defer closePubSub(t, pub, sub)
topicName := testTopicName(tCtx.TestID)
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
msg := message.NewMessage(watermill.NewUUID(), nil)
// ensuring that context is not propagated via pub/sub
ctx, ctxCancel := context.WithCancel(context.Background())
ctxCancel()
msg.SetContext(ctx)
require.NoError(t, publishWithRetry(pub, topicName, msg))
// this might actually be an error in some pubsubs (http), because we close the subscriber without ACK.
_ = pub.Publish(topicName, msg)
messages, err := sub.Subscribe(context.Background(), topicName)
require.NoError(t, err)
select {
case msg := <-messages:
ctx := msg.Context()
select {
case <-ctx.Done():
t.Fatal("context should not be canceled")
default:
// ok
}
require.True(t, msg.Ack())
select {
case <-ctx.Done():
// ok
case <-time.After(defaultTimeout):
t.Fatal("context should be canceled after Ack")
}
case <-time.After(defaultTimeout):
t.Fatal("no message received")
}
select {
case msg := <-messages:
ctx := msg.Context()
select {
case <-ctx.Done():
t.Fatal("context should not be canceled")
default:
// ok
}
go closePubSub(t, pub, sub)
select {
case <-ctx.Done():
// ok
case <-time.After(defaultTimeout):
t.Fatal("context should be canceled after pubSub.Close()")
}
case <-time.After(defaultTimeout):
t.Fatal("no message received")
}
}
type contextKey string
// TestSubscribeCtx tests if the Subscriber's Context works correctly.
func TestSubscribeCtx(
t *testing.T,
tCtx TestContext,
pubSubConstructor PubSubConstructor,
) {
pub, sub := pubSubConstructor(t)
defer closePubSub(t, pub, sub)
const messagesCount = 20
ctxWithCancel, cancel := context.WithCancel(context.Background())
ctxWithCancel = context.WithValue(ctxWithCancel, contextKey("foo"), "bar")
topicName := testTopicName(tCtx.TestID)
if subscribeInitializer, ok := sub.(message.SubscribeInitializer); ok {
require.NoError(t, subscribeInitializer.SubscribeInitialize(topicName))
}
publishedMessages := PublishSimpleMessages(t, messagesCount, pub, topicName)
msgsToCancel, err := sub.Subscribe(ctxWithCancel, topicName)
require.NoError(t, err)
cancel()
timeout := time.After(defaultTimeout)
ClosedLoop:
for {
select {
case msg, open := <-msgsToCancel:
if !open {
break ClosedLoop