/
drivertest.go
983 lines (889 loc) · 27.4 KB
/
drivertest.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
// Copyright 2018 The Go Cloud Development Kit Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package drivertest provides a conformance test for implementations of
// driver.
package drivertest // import "github.com/eliben/gocdkx/pubsub/drivertest"
import (
"bytes"
"context"
"errors"
"sort"
"strconv"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/eliben/gocdkx/gcerrors"
"github.com/eliben/gocdkx/internal/batcher"
"github.com/eliben/gocdkx/internal/escape"
"github.com/eliben/gocdkx/internal/retry"
"github.com/eliben/gocdkx/pubsub"
"github.com/eliben/gocdkx/pubsub/driver"
"golang.org/x/sync/errgroup"
)
// Harness descibes the functionality test harnesses must provide to run
// conformance tests.
type Harness interface {
// CreateTopic creates a new topic in the provider and returns a driver.Topic
// for testing. The topic may have to be removed manually if the test is
// abruptly terminated or the network connection fails.
CreateTopic(ctx context.Context, testName string) (dt driver.Topic, cleanup func(), err error)
// MakeNonexistentTopic makes a driver.Topic referencing a topic that
// does not exist.
MakeNonexistentTopic(ctx context.Context) (driver.Topic, error)
// CreateSubscription creates a new subscription in the provider, subscribed
// to the given topic, and returns a driver.Subscription for testing. The
// subscription may have to be cleaned up manually if the test is abruptly
// terminated or the network connection fails.
CreateSubscription(ctx context.Context, t driver.Topic, testName string) (ds driver.Subscription, cleanup func(), err error)
// MakeNonexistentSubscription makes a driver.Subscription referencing a
// subscription that does not exist.
MakeNonexistentSubscription(ctx context.Context) (driver.Subscription, error)
// Close closes resources used by the harness, but does not call Close
// on the Topics and Subscriptions generated by the Harness.
Close()
// MaxBatchSizes returns the maximum size of SendBatch/Send(Na|A)cks, or 0
// if there's no max.
MaxBatchSizes() (int, int)
}
// HarnessMaker describes functions that construct a harness for running tests.
// It is called exactly once per test; Harness.Close() will be called when the test is complete.
type HarnessMaker func(ctx context.Context, t *testing.T) (Harness, error)
// AsTest represents a test of As functionality.
// The conformance test:
// 1. Calls TopicCheck.
// 2. Calls SubscriptionCheck.
// 3. Sends a message, setting Message.BeforeSend to BeforeSend.
// 4. Receives the message and calls MessageCheck.
// 5. Calls TopicErrorCheck.
// 6. Calls SubscriptionErrorCheck.
type AsTest interface {
// Name should return a descriptive name for the test.
Name() string
// TopicCheck will be called to allow verifcation of Topic.As.
TopicCheck(t *pubsub.Topic) error
// SubscriptionCheck will be called to allow verification of Subscription.As.
SubscriptionCheck(s *pubsub.Subscription) error
// TopicErrorCheck will be called to allow verification of Topic.ErrorAs.
// The error will be the one returned from SendBatch when called with
// a non-existent topic.
TopicErrorCheck(t *pubsub.Topic, err error) error
// SubscriptionErrorCheck will be called to allow verification of
// Subscription.ErrorAs.
// The error will be the one returned from ReceiveBatch when called with
// a non-existent subscription.
SubscriptionErrorCheck(s *pubsub.Subscription, err error) error
// MessageCheck will be called to allow verification of Message.As.
MessageCheck(m *pubsub.Message) error
// BeforeSend will be used as Message.BeforeSend as part of sending a test
// message.
BeforeSend(as func(interface{}) bool) error
}
// Many tests set the maximum batch size to 1 to make record/replay stable.
var batchSizeOne = &batcher.Options{MaxBatchSize: 1, MaxHandlers: 1}
type verifyAsFailsOnNil struct{}
func (verifyAsFailsOnNil) Name() string {
return "verify As returns false when passed nil"
}
func (verifyAsFailsOnNil) TopicCheck(t *pubsub.Topic) error {
if t.As(nil) {
return errors.New("want Topic.As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) SubscriptionCheck(s *pubsub.Subscription) error {
if s.As(nil) {
return errors.New("want Subscription.As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) TopicErrorCheck(t *pubsub.Topic, err error) (ret error) {
defer func() {
if recover() == nil {
ret = errors.New("want Topic.ErrorAs to panic when passed nil")
}
}()
t.ErrorAs(err, nil)
return nil
}
func (verifyAsFailsOnNil) SubscriptionErrorCheck(s *pubsub.Subscription, err error) (ret error) {
defer func() {
if recover() == nil {
ret = errors.New("want Subscription.ErrorAs to panic when passed nil")
}
}()
s.ErrorAs(err, nil)
return nil
}
func (verifyAsFailsOnNil) MessageCheck(m *pubsub.Message) error {
if m.As(nil) {
return errors.New("want Message.As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) BeforeSend(as func(interface{}) bool) error {
if as(nil) {
return errors.New("want Message.BeforeSend's As function to return false when passed nil")
}
return nil
}
// RunConformanceTests runs conformance tests for provider implementations of pubsub.
func RunConformanceTests(t *testing.T, newHarness HarnessMaker, asTests []AsTest) {
tests := map[string]func(t *testing.T, newHarness HarnessMaker){
"TestSendReceive": testSendReceive,
"TestSendReceiveTwo": testSendReceiveTwo,
"TestNack": testNack,
"TestBatching": testBatching,
"TestDoubleAck": testDoubleAck,
"TestErrorOnSendToClosedTopic": testErrorOnSendToClosedTopic,
"TestErrorOnReceiveFromClosedSubscription": testErrorOnReceiveFromClosedSubscription,
"TestCancelSendReceive": testCancelSendReceive,
"TestNonExistentTopicSucceedsOnOpenButFailsOnSend": testNonExistentTopicSucceedsOnOpenButFailsOnSend,
"TestNonExistentSubscriptionSucceedsOnOpenButFailsOnReceive": testNonExistentSubscriptionSucceedsOnOpenButFailsOnReceive,
"TestMetadata": testMetadata,
"TestNonUTF8MessageBody": testNonUTF8MessageBody,
}
for name, test := range tests {
t.Run(name, func(t *testing.T) { test(t, newHarness) })
}
asTests = append(asTests, verifyAsFailsOnNil{})
t.Run("TestAs", func(t *testing.T) {
for _, st := range asTests {
if st.Name() == "" {
t.Fatalf("AsTest.Name is required")
}
t.Run(st.Name(), func(t *testing.T) { testAs(t, newHarness, st) })
}
})
}
// RunBenchmarks runs benchmarks for provider implementations of pubsub.
func RunBenchmarks(b *testing.B, topic *pubsub.Topic, sub *pubsub.Subscription) {
b.Run("BenchmarkReceive", func(b *testing.B) {
benchmark(b, topic, sub, false)
})
b.Run("BenchmarkSend", func(b *testing.B) {
benchmark(b, topic, sub, true)
})
}
func testNonExistentTopicSucceedsOnOpenButFailsOnSend(t *testing.T, newHarness HarnessMaker) {
// Set up.
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
dt, err := h.MakeNonexistentTopic(ctx)
if err != nil {
// Failure shouldn't happen for non-existent topics until messages are sent
// to them.
t.Fatalf("creating a local topic that doesn't exist on the server: %v", err)
}
topic := pubsub.NewTopic(dt, nil)
defer func() {
if err := topic.Shutdown(ctx); err != nil {
t.Error(err)
}
}()
m := &pubsub.Message{}
err = topic.Send(ctx, m)
if err == nil || gcerrors.Code(err) != gcerrors.NotFound {
t.Errorf("got error %v for send to non-existent topic, want code=NotFound", err)
}
}
func testNonExistentSubscriptionSucceedsOnOpenButFailsOnReceive(t *testing.T, newHarness HarnessMaker) {
// Set up.
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
ds, err := h.MakeNonexistentSubscription(ctx)
if err != nil {
t.Fatalf("failed to make non-existent subscription: %v", err)
}
sub := pubsub.NewSubscription(ds, batchSizeOne, batchSizeOne)
defer func() {
if err := sub.Shutdown(ctx); err != nil {
t.Error(err)
}
}()
// The test will hang here if the message isn't available, so use a shorter timeout.
ctx2, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
_, err = sub.Receive(ctx2)
if err == nil || ctx2.Err() != nil || gcerrors.Code(err) != gcerrors.NotFound {
t.Errorf("got error %v for receive from non-existent subscription, want code=NotFound", err)
}
}
func testSendReceive(t *testing.T, newHarness HarnessMaker) {
// Set up.
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
topic, sub, cleanup, err := makePair(ctx, t, h)
if err != nil {
t.Fatal(err)
}
defer cleanup()
want := publishN(ctx, t, topic, 3)
got := receiveN(ctx, t, sub, len(want))
// Check that the received messages match the sent ones.
if diff := diffMessageSets(got, want); diff != "" {
t.Error(diff)
}
}
// Receive from two subscriptions to the same topic.
// Verify both get all the messages.
func testSendReceiveTwo(t *testing.T, newHarness HarnessMaker) {
// Set up.
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
dt, cleanup, err := h.CreateTopic(ctx, t.Name())
if err != nil {
t.Fatal(err)
}
defer cleanup()
topic := pubsub.NewTopic(dt, batchSizeOne)
defer func() {
if err := topic.Shutdown(ctx); err != nil {
t.Error(err)
}
}()
var ss []*pubsub.Subscription
for i := 0; i < 2; i++ {
ds, cleanup, err := h.CreateSubscription(ctx, dt, t.Name())
if err != nil {
t.Fatal(err)
}
defer cleanup()
s := pubsub.NewSubscription(ds, batchSizeOne, batchSizeOne)
defer func() {
if err := s.Shutdown(ctx); err != nil {
t.Error(err)
}
}()
ss = append(ss, s)
}
want := publishN(ctx, t, topic, 3)
for i, s := range ss {
got := receiveN(ctx, t, s, len(want))
if diff := diffMessageSets(got, want); diff != "" {
t.Errorf("sub #%d: %s", i, diff)
}
}
}
func testNack(t *testing.T, newHarness HarnessMaker) {
const nMessages = 2
// Set up.
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
dt, topicCleanup, err := h.CreateTopic(ctx, t.Name())
if err != nil {
t.Fatal(err)
}
defer topicCleanup()
ds, subCleanup, err := h.CreateSubscription(ctx, dt, t.Name())
if err != nil {
t.Fatal(err)
}
defer subCleanup()
if !ds.CanNack() {
t.Skip("Nack not supported")
}
topic := pubsub.NewTopic(dt, batchSizeOne)
defer func() {
if err := topic.Shutdown(ctx); err != nil {
t.Error(err)
}
}()
sub := pubsub.NewSubscription(ds, batchSizeOne, batchSizeOne)
defer func() {
if err := sub.Shutdown(ctx); err != nil {
t.Error(err)
}
}()
want := publishN(ctx, t, topic, nMessages)
// Get the messages, but nack them.
// Make sure to nack after receiving all of them; otherwise, we could
// receive one of the messages twice instead of receiving all nMessages.
var got []*pubsub.Message
for i := 0; i < nMessages; i++ {
m, err := sub.Receive(ctx)
if err != nil {
t.Fatal(err)
}
got = append(got, m)
}
for _, m := range got {
m.Nack()
}
// Check that the received messages match the sent ones.
if diff := diffMessageSets(got, want); diff != "" {
t.Error(diff)
}
// The test will hang here if the messages aren't redelivered, so use a shorter timeout.
ctx2, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
got = nil
for i := 0; i < nMessages; i++ {
m, err := sub.Receive(ctx2)
if err != nil {
t.Fatal(err)
}
got = append(got, m)
m.Ack()
}
if diff := diffMessageSets(got, want); diff != "" {
t.Error(diff)
}
}
func testBatching(t *testing.T, newHarness HarnessMaker) {
const nMessages = 12 // must be divisible by 2
const batchSize = nMessages / 2
// Set up.
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
maxSendBatch, maxAckBatch := h.MaxBatchSizes()
dt, topicCleanup, err := h.CreateTopic(ctx, t.Name())
if err != nil {
t.Fatal(err)
}
defer topicCleanup()
ds, subCleanup, err := h.CreateSubscription(ctx, dt, t.Name())
if err != nil {
t.Fatal(err)
}
defer subCleanup()
sendBatchOpts := &batcher.Options{MinBatchSize: batchSize, MaxBatchSize: batchSize}
// If the driver doesn't support batchSize batches, fall back to size 1.
if maxSendBatch != 0 && batchSize > maxSendBatch {
sendBatchOpts = batchSizeOne
}
topic := pubsub.NewTopic(dt, sendBatchOpts)
defer func() {
if err := topic.Shutdown(ctx); err != nil {
t.Error(err)
}
}()
ackBatchOpts := &batcher.Options{MinBatchSize: batchSize, MaxBatchSize: batchSize}
// If the driver doesn't support batchSize batches, fall back to size 1.
if maxAckBatch != 0 && batchSize > maxAckBatch {
ackBatchOpts = batchSizeOne
}
sub := pubsub.NewSubscription(ds, batchSizeOne, ackBatchOpts)
defer func() {
if err := sub.Shutdown(ctx); err != nil {
t.Error(err)
}
}()
// Publish nMessages. We have to do them asynchronously because topic.Send
// blocks until the message is sent, and these messages won't be sent until
// all batchSize are queued.
// Note: this test uses the same Body for each message, because the order
// that they appear in the SendBatch is not stable.
gr, grctx := errgroup.WithContext(ctx)
var want []*pubsub.Message
for i := 0; i < nMessages; i++ {
m := &pubsub.Message{Body: []byte("hello world")}
want = append(want, m)
gr.Go(func() error { return topic.Send(grctx, m) })
}
if err := gr.Wait(); err != nil {
t.Fatal(err)
}
// Get the messages.
var got []*pubsub.Message
for i := 0; i < nMessages; i++ {
m, err := sub.Receive(ctx)
if err != nil {
t.Fatal(err)
}
got = append(got, m)
m.Ack()
}
if diff := diffMessageSets(got, want); diff != "" {
t.Error(diff)
}
}
func testDoubleAck(t *testing.T, newHarness HarnessMaker) {
// Set up.
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
dt, topicCleanup, err := h.CreateTopic(ctx, t.Name())
if err != nil {
t.Fatal(err)
}
defer topicCleanup()
ds, subCleanup, err := h.CreateSubscription(ctx, dt, t.Name())
if err != nil {
t.Fatal(err)
}
defer subCleanup()
if ds.AckFunc() != nil {
t.Skip("Ack not supported")
}
// Publish 3 messages.
for i := 0; i < 3; i++ {
err := dt.SendBatch(ctx, []*driver.Message{{Body: []byte(strconv.Itoa(i))}})
if err != nil {
t.Fatal(err)
}
}
// Retrieve the messages.
var dms []*driver.Message
for len(dms) != 3 {
curdms, err := ds.ReceiveBatch(ctx, 3)
if err != nil {
t.Fatal(err)
}
dms = append(dms, curdms...)
}
// Ack the first two messages.
err = ds.SendAcks(ctx, []driver.AckID{dms[0].AckID, dms[1].AckID})
if err != nil {
t.Fatal(err)
}
// Ack them again; this should succeed even though we've acked them before.
// If providers return an error for this, drivers should drop them.
err = ds.SendAcks(ctx, []driver.AckID{dms[0].AckID, dms[1].AckID})
if err != nil {
t.Fatal(err)
}
if !ds.CanNack() {
return
}
// Nack all 3 messages. This should also succeed, and the nack of the third
// message should take effect, so we should be able to fetch it again.
// Note that the other messages *may* also be re-sent, because we're nacking
// them here (even though we acked them earlier); it depends on provider
// semantics and time-sensitivity.
err = ds.SendNacks(ctx, []driver.AckID{dms[0].AckID, dms[1].AckID, dms[2].AckID})
if err != nil {
t.Fatal(err)
}
// The test will hang here if the message isn't redelivered, so use a shorter timeout.
ctx2, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// We're looking to re-receive dms[2].
Loop:
for {
curdms, err := ds.ReceiveBatch(ctx2, 1)
if err != nil {
t.Fatal(err)
}
for _, curdm := range curdms {
if bytes.Equal(curdm.Body, dms[2].Body) {
// Found it!
break Loop
}
}
}
}
// Publish n different messages to the topic. Return the messages.
func publishN(ctx context.Context, t *testing.T, topic *pubsub.Topic, n int) []*pubsub.Message {
var ms []*pubsub.Message
for i := 0; i < n; i++ {
m := &pubsub.Message{
Body: []byte(strconv.Itoa(i)),
Metadata: map[string]string{"a": strconv.Itoa(i)},
}
if err := topic.Send(ctx, m); err != nil {
t.Fatal(err)
}
ms = append(ms, m)
}
return ms
}
// Receive and ack n messages from sub.
func receiveN(ctx context.Context, t *testing.T, sub *pubsub.Subscription, n int) []*pubsub.Message {
// The test will hang here if the message(s) aren't available, so use a shorter timeout.
ctx2, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
var ms []*pubsub.Message
for i := 0; i < n; i++ {
m, err := sub.Receive(ctx2)
if err != nil {
t.Fatal(err)
}
ms = append(ms, m)
m.Ack()
}
return ms
}
// Find the differences between two sets of messages.
func diffMessageSets(got, want []*pubsub.Message) string {
less := func(x, y *pubsub.Message) bool { return bytes.Compare(x.Body, y.Body) < 0 }
return cmp.Diff(got, want, cmpopts.SortSlices(less), cmpopts.IgnoreUnexported(pubsub.Message{}))
}
func testErrorOnSendToClosedTopic(t *testing.T, newHarness HarnessMaker) {
// Set up.
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
dt, cleanup, err := h.CreateTopic(ctx, t.Name())
if err != nil {
t.Fatal(err)
}
defer cleanup()
topic := pubsub.NewTopic(dt, batchSizeOne)
if err := topic.Shutdown(ctx); err != nil {
t.Error(err)
}
// Check that sending to the closed topic fails.
m := &pubsub.Message{}
if err := topic.Send(ctx, m); err == nil {
t.Error("topic.Send returned nil, want error")
}
if err := topic.Shutdown(ctx); err == nil {
t.Error("wanted error on double Shutdown")
}
}
func testErrorOnReceiveFromClosedSubscription(t *testing.T, newHarness HarnessMaker) {
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
dt, cleanup, err := h.CreateTopic(ctx, t.Name())
if err != nil {
t.Fatal(err)
}
defer cleanup()
ds, cleanup, err := h.CreateSubscription(ctx, dt, t.Name())
if err != nil {
t.Fatal(err)
}
sub := pubsub.NewSubscription(ds, batchSizeOne, batchSizeOne)
if err := sub.Shutdown(ctx); err != nil {
t.Error(err)
}
if _, err = sub.Receive(ctx); err == nil {
t.Error("sub.Receive returned nil, want error")
}
if err := sub.Shutdown(ctx); err == nil {
t.Error("wanted error on double Shutdown")
}
}
func testCancelSendReceive(t *testing.T, newHarness HarnessMaker) {
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
topic, sub, cleanup, err := makePair(ctx, t, h)
if err != nil {
t.Fatal(err)
}
defer cleanup()
ctx, cancel := context.WithCancel(ctx)
cancel()
m := &pubsub.Message{}
if err := topic.Send(ctx, m); !isCanceled(err) {
t.Errorf("topic.Send returned %v (%T), want context.Canceled", err, err)
}
if _, err := sub.Receive(ctx); !isCanceled(err) {
t.Errorf("sub.Receive returned %v (%T), want context.Canceled", err, err)
}
// It would be nice to add a test that cancels an in-flight blocking Receive.
// However, because pubsub.Subscription.Receive repeatedly calls
// driver.ReceiveBatch if it returns 0 messages, it's difficult to write
// such a test without it being flaky for drivers with record/replay
// (the number of times driver.ReceiveBatch is called is timing-dependent).
}
func testMetadata(t *testing.T, newHarness HarnessMaker) {
// Set up.
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
weirdMetadata := map[string]string{}
for _, k := range escape.WeirdStrings {
weirdMetadata[k] = k
}
topic, sub, cleanup, err := makePair(ctx, t, h)
if err != nil {
t.Fatal(err)
}
defer cleanup()
m := &pubsub.Message{
Body: []byte("hello world"),
Metadata: weirdMetadata,
}
if err := topic.Send(ctx, m); err != nil {
t.Fatal(err)
}
m, err = sub.Receive(ctx)
if err != nil {
t.Fatal(err)
}
m.Ack()
if diff := cmp.Diff(m.Metadata, weirdMetadata); diff != "" {
t.Fatalf("got\n%v\nwant\n%v\ndiff\n%s", m.Metadata, weirdMetadata, diff)
}
// Verify that non-UTF8 strings in metadata key or value fail.
m = &pubsub.Message{
Body: []byte("hello world"),
Metadata: map[string]string{escape.NonUTF8String: "bar"},
}
if err := topic.Send(ctx, m); err == nil {
t.Error("got nil error, expected error for using non-UTF8 string as metadata key")
}
m.Metadata = map[string]string{"foo": escape.NonUTF8String}
if err := topic.Send(ctx, m); err == nil {
t.Error("got nil error, expected error for using non-UTF8 string as metadata value")
}
}
func testNonUTF8MessageBody(t *testing.T, newHarness HarnessMaker) {
// Set up.
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
topic, sub, cleanup, err := makePair(ctx, t, h)
if err != nil {
t.Fatal(err)
}
defer cleanup()
// Sort the WeirdStrings map for record/replay consistency.
var weirdStrings [][]string // [0] = key, [1] = value
for k, v := range escape.WeirdStrings {
weirdStrings = append(weirdStrings, []string{k, v})
}
sort.Slice(weirdStrings, func(i, j int) bool { return weirdStrings[i][0] < weirdStrings[j][0] })
// Construct a message body with the weird strings and some non-UTF-8 bytes.
var body []byte
for _, v := range weirdStrings {
body = append(body, []byte(v[1])...)
}
body = append(body, []byte(escape.NonUTF8String)...)
m := &pubsub.Message{Body: body}
if err := topic.Send(ctx, m); err != nil {
t.Fatal(err)
}
m, err = sub.Receive(ctx)
if err != nil {
t.Fatal(err)
}
m.Ack()
if diff := cmp.Diff(m.Body, body); diff != "" {
t.Fatalf("got\n%v\nwant\n%v\ndiff\n%s", m.Body, body, diff)
}
}
func isCanceled(err error) bool {
if err == context.Canceled {
return true
}
if cerr, ok := err.(*retry.ContextError); ok {
return cerr.CtxErr == context.Canceled
}
return gcerrors.Code(err) == gcerrors.Canceled
}
func makePair(ctx context.Context, t *testing.T, h Harness) (*pubsub.Topic, *pubsub.Subscription, func(), error) {
dt, topicCleanup, err := h.CreateTopic(ctx, t.Name())
if err != nil {
return nil, nil, nil, err
}
ds, subCleanup, err := h.CreateSubscription(ctx, dt, t.Name())
if err != nil {
topicCleanup()
return nil, nil, nil, err
}
topic := pubsub.NewTopic(dt, batchSizeOne)
sub := pubsub.NewSubscription(ds, batchSizeOne, batchSizeOne)
cleanup := func() {
topicCleanup()
subCleanup()
if err := topic.Shutdown(ctx); err != nil {
t.Error(err)
}
if err := sub.Shutdown(ctx); err != nil {
t.Error(err)
}
}
return topic, sub, cleanup, nil
}
// testAs tests the various As functions, using AsTest.
func testAs(t *testing.T, newHarness HarnessMaker, st AsTest) {
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
topic, sub, cleanup, err := makePair(ctx, t, h)
if err != nil {
t.Fatal(err)
}
defer cleanup()
if err := st.TopicCheck(topic); err != nil {
t.Error(err)
}
if err := st.SubscriptionCheck(sub); err != nil {
t.Error(err)
}
msg := &pubsub.Message{
Body: []byte("x"),
BeforeSend: st.BeforeSend,
}
if err := topic.Send(ctx, msg); err != nil {
t.Fatal(err)
}
m, err := sub.Receive(ctx)
if err != nil {
t.Fatal(err)
}
if err := st.MessageCheck(m); err != nil {
t.Error(err)
}
m.Ack()
// Make a nonexistent topic and try to to send on it, to get an error we can
// use to call TopicErrorCheck.
dt, err := h.MakeNonexistentTopic(ctx)
if err != nil {
t.Fatal(err)
}
nonexistentTopic := pubsub.NewTopic(dt, batchSizeOne)
defer func() {
if err := nonexistentTopic.Shutdown(ctx); err != nil {
t.Error(err)
}
}()
topicErr := nonexistentTopic.Send(ctx, &pubsub.Message{})
if topicErr == nil || gcerrors.Code(topicErr) != gcerrors.NotFound {
t.Errorf("got error %v sending to nonexistent topic, want Code=NotFound", topicErr)
} else if err := st.TopicErrorCheck(topic, topicErr); err != nil {
t.Error(err)
}
// Make a nonexistent subscription and try to receive from it, to get an error
// we can use to call SubscriptionErrorCheck.
ds, err := h.MakeNonexistentSubscription(ctx)
if err != nil {
t.Fatal(err)
}
nonExistentSub := pubsub.NewSubscription(ds, batchSizeOne, batchSizeOne)
defer func() {
if err := nonExistentSub.Shutdown(ctx); err != nil {
t.Error(err)
}
}()
// The test will hang here if Receive doesn't fail quickly, so set a shorter timeout.
ctx2, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
_, subErr := nonExistentSub.Receive(ctx2)
if subErr == nil || ctx2.Err() != nil || gcerrors.Code(subErr) != gcerrors.NotFound {
t.Errorf("got error %v receiving from nonexistent subscription, want Code=NotFound", subErr)
} else if err := st.SubscriptionErrorCheck(nonExistentSub, subErr); err != nil {
t.Error(err)
}
}
// Publishes a large number of messages to topic concurrently, and then times
// how long it takes to send (if timeSend is true) or receive (if timeSend
// is false) them all.
func benchmark(b *testing.B, topic *pubsub.Topic, sub *pubsub.Subscription, timeSend bool) {
attrs := map[string]string{"label": "value"}
body := []byte("hello, world")
const (
nMessages = 10000
concurrencySend = 100
concurrencyReceive = 100
)
if nMessages%concurrencySend != 0 || nMessages%concurrencyReceive != 0 {
b.Fatal("nMessages must be divisible by # of sending/receiving goroutines")
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if !timeSend {
b.StopTimer()
}
if err := publishNConcurrently(topic, nMessages, concurrencySend, attrs, body); err != nil {
b.Fatalf("publishing: %v", err)
}
b.Logf("published %d messages", nMessages)
if timeSend {
b.StopTimer()
} else {
b.StartTimer()
}
if err := receiveNConcurrently(sub, nMessages, concurrencyReceive); err != nil {
b.Fatalf("receiving: %v", err)
}
b.SetBytes(nMessages * 1e6)
b.Log("MB/s is actually number of messages received per second")
if timeSend {
b.StartTimer()
}
}
}
func publishNConcurrently(topic *pubsub.Topic, nMessages, nGoroutines int, attrs map[string]string, body []byte) error {
return runConcurrently(nMessages, nGoroutines, func(ctx context.Context) error {
return topic.Send(ctx, &pubsub.Message{Metadata: attrs, Body: body})
})
}
func receiveNConcurrently(sub *pubsub.Subscription, nMessages, nGoroutines int) error {
return runConcurrently(nMessages, nGoroutines, func(ctx context.Context) error {
m, err := sub.Receive(ctx)
if err != nil {
return err
}
m.Ack()
return nil
})
}
// Call function f n times concurrently, using g goroutines. g must divide n.
// Wait until all calls complete. If any fail, cancel the remaining ones.
func runConcurrently(n, g int, f func(context.Context) error) error {
gr, ctx := errgroup.WithContext(context.Background())
ng := n / g
for i := 0; i < g; i++ {
gr.Go(func() error {
for j := 0; j < ng; j++ {
if err := f(ctx); err != nil {
return err
}
}
return nil
})
}
return gr.Wait()
}