Debian Codegraph @

pubsub/pubsub_test.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 package pubsub
15
16 import (
17 "context"
18 "errors"
19 "fmt"
20 "net/url"
21 "strings"
22 "sync"
23 "sync/atomic"
24 "testing"
25 "time"
26
27 "github.com/google/go-cmp/cmp"
28 "gocloud.dev/gcerrors"
29 "gocloud.dev/internal/gcerr"
30 "gocloud.dev/internal/testing/oteltest"
31 "gocloud.dev/pubsub/batcher"
32 "gocloud.dev/pubsub/driver"
33 )
34
35 type driverTopic struct {
36 driver.Topic
37 subs []*driverSub
38 }
39
40 func (t *driverTopic) SendBatch(ctx context.Context, ms []*driver.Message) error {
41 for _, s := range t.subs {
42 select {
43 case <-s.sem:
44 s.q = append(s.q, ms...)
45 s.sem <- struct{}{}
46 case <-ctx.Done():
47 return ctx.Err()
48 }
49 }
50 return nil
51 }
52
53 func (*driverTopic) IsRetryable(error) bool { return false }
54 func (*driverTopic) ErrorCode(error) gcerrors.ErrorCode { return gcerrors.Unknown }
55 func (*driverTopic) Close() error { return nil }
56
57 type driverSub struct {
58 driver.Subscription
59 sem chan struct{}
60 // Normally this queue would live on a separate server in the cloud.
61 q []*driver.Message
62 }
63
64 func NewDriverSub() *driverSub {
65 ds := &driverSub{
66 sem: make(chan struct{}, 1),
67 }
68 ds.sem <- struct{}{}
69 return ds
70 }
71
72 func (s *driverSub) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
73 for {
74 select {
75 case <-s.sem:
76 ms := s.grabQueue(maxMessages)
77 if len(ms) != 0 {
78 return ms, nil
79 }
80 case <-ctx.Done():
81 return nil, ctx.Err()
82 }
83 }
84 }
85
86 func (s *driverSub) grabQueue(maxMessages int) []*driver.Message {
87 defer func() { s.sem <- struct{}{} }()
88 if len(s.q) > 0 {
89 if len(s.q) <= maxMessages {
90 ms := s.q
91 s.q = nil
92 return ms
93 }
94 ms := s.q[:maxMessages]
95 s.q = s.q[maxMessages:]
96 return ms
97 }
98 return nil
99 }
100
101 func (s *driverSub) SendAcks(ctx context.Context, ackIDs []driver.AckID) error {
102 return nil
103 }
104
105 func (*driverSub) IsRetryable(error) bool { return false }
106 func (*driverSub) ErrorCode(error) gcerrors.ErrorCode { return gcerrors.Internal }
107 func (*driverSub) CanNack() bool { return false }
108 func (*driverSub) Close() error { return nil }
109
110 func TestSendReceive(t *testing.T) {
111 ctx := context.Background()
112 ds := NewDriverSub()
113 dt := &driverTopic{
114 subs: []*driverSub{ds},
115 }
116 topic := NewTopic(dt, nil)
117 defer topic.Shutdown(ctx)
118 m := &Message{LoggableID: "foo", Body: []byte("user signed up")}
119 if err := topic.Send(ctx, m); err == nil {
120 t.Fatalf("expected a Send with a non-empty LoggableID to fail")
121 }
122 m.LoggableID = ""
123 if err := topic.Send(ctx, m); err != nil {
124 t.Fatal(err)
125 }
126
127 sub := NewSubscription(ds, nil, nil)
128 defer sub.Shutdown(ctx)
129 m2, err := sub.Receive(ctx)
130 if err != nil {
131 t.Fatal(err)
132 }
133 if string(m2.Body) != string(m.Body) {
134 t.Fatalf("received message has body %q, want %q", m2.Body, m.Body)
135 }
136 m2.Ack()
137 }
138
139 func TestConcurrentReceivesGetAllTheMessages(t *testing.T) {
140 howManyToSend := int(1e3)
141 ctx, cancel := context.WithCancel(context.Background())
142 dt := &driverTopic{}
143
144 // wg is used to wait until all messages are received.
145 var wg sync.WaitGroup
146 wg.Add(howManyToSend)
147
148 // Make a subscription.
149 ds := NewDriverSub()
150 dt.subs = append(dt.subs, ds)
151 s := NewSubscription(ds, nil, nil)
152 defer s.Shutdown(ctx)
153
154 // Start 10 goroutines to receive from it.
155 var mu sync.Mutex
156 receivedMsgs := make(map[string]bool)
157 for range 10 {
158 go func() {
159 for {
160 m, err := s.Receive(ctx)
161 if err != nil {
162 // Permanent error; ctx cancelled or subscription closed is
163 // expected once we've received all the messages.
164 mu.Lock()
165 n := len(receivedMsgs)
166 mu.Unlock()
167 if n != howManyToSend {
168 t.Errorf("Worker's Receive failed before all messages were received (%d)", n)
169 }
170 return
171 }
172 m.Ack()
173 mu.Lock()
174 receivedMsgs[string(m.Body)] = true
175 mu.Unlock()
176 wg.Done()
177 }
178 }()
179 }
180
181 // Send messages. Each message has a unique body used as a key to receivedMsgs.
182 topic := NewTopic(dt, nil)
183 defer topic.Shutdown(ctx)
184 for i := range howManyToSend {
185 key := fmt.Sprintf("message #%d", i)
186 m := &Message{Body: []byte(key)}
187 if err := topic.Send(ctx, m); err != nil {
188 t.Fatal(err)
189 }
190 }
191
192 // Wait for the goroutines to receive all of the messages, then cancel the
193 // ctx so they all exit.
194 wg.Wait()
195 defer cancel()
196
197 // Check that all the messages were received.
198 for i := range howManyToSend {
199 key := fmt.Sprintf("message #%d", i)
200 if !receivedMsgs[key] {
201 t.Errorf("message %q was not received", key)
202 }
203 }
204 }
205
206 func TestCancelSend(t *testing.T) {
207 ctx, cancel := context.WithCancel(context.Background())
208 ds := NewDriverSub()
209 dt := &driverTopic{
210 subs: []*driverSub{ds},
211 }
212 topic := NewTopic(dt, nil)
213 defer topic.Shutdown(ctx)
214 m := &Message{}
215
216 // Intentionally break the driver subscription by acquiring its semaphore.
217 // Now topic.Send will have to wait for cancellation.
218 <-ds.sem
219
220 cancel()
221 if err := topic.Send(ctx, m); err == nil {
222 t.Error("got nil, want cancellation error")
223 }
224 }
225
226 func TestCancelReceive(t *testing.T) {
227 ctx, cancel := context.WithCancel(context.Background())
228 ds := NewDriverSub()
229 s := NewSubscription(ds, nil, nil)
230 defer s.Shutdown(ctx)
231 cancel()
232 // Without cancellation, this Receive would hang.
233 if _, err := s.Receive(ctx); err == nil {
234 t.Error("got nil, want cancellation error")
235 }
236 }
237
238 type blockingDriverSub struct {
239 driver.Subscription
240 inReceiveBatch chan struct{}
241 }
242
243 func (b blockingDriverSub) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
244 b.inReceiveBatch <- struct{}{}
245 <-ctx.Done()
246 return nil, ctx.Err()
247 }
248 func (blockingDriverSub) CanNack() bool { return false }
249 func (blockingDriverSub) IsRetryable(error) bool { return false }
250 func (blockingDriverSub) Close() error { return nil }
251
252 func TestCancelTwoReceives(t *testing.T) {
253 // We want to create the following situation:
254 // 1. Goroutine 1 calls Receive, obtains the lock (Subscription.mu),
255 // then releases the lock and calls driver.ReceiveBatch, which hangs.
256 // 2. Goroutine 2 calls Receive.
257 // 3. The context passed to the Goroutine 2 call is canceled.
258 // We expect Goroutine 2's Receive to exit immediately. That won't
259 // happen if Receive holds the lock during the call to ReceiveBatch.
260 inReceiveBatch := make(chan struct{})
261 s := NewSubscription(blockingDriverSub{inReceiveBatch: inReceiveBatch}, nil, nil)
262 defer s.Shutdown(context.Background())
263 go func() {
264 _, err := s.Receive(context.Background())
265 // This should happen at the very end of the test, during Shutdown.
266 if err != context.Canceled {
267 t.Errorf("got %v, want context.Canceled", err)
268 }
269 }()
270 <-inReceiveBatch
271 // Give the Receive call time to block on the mutex before timing out.
272 ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
273 defer cancel()
274 errc := make(chan error)
275 go func() {
276 _, err := s.Receive(ctx)
277 errc <- err
278 }()
279 err := <-errc
280 if err != context.DeadlineExceeded {
281 t.Errorf("got %v, want context.DeadlineExceeded", err)
282 }
283 }
284
285 type secondReceiveBlockedDriverSub struct {
286 driver.Subscription
287 receiveCounter atomic.Uint64
288 }
289
290 func (s *secondReceiveBlockedDriverSub) ReceiveBatch(ctx context.Context, _ int) ([]*driver.Message, error) {
291 // The first request will return a message right away.
292 // The second one will block ~forever.
293 if n := s.receiveCounter.Add(1); n > 1 {
294 <-ctx.Done()
295 }
296 msg := &driver.Message{Body: fmt.Appendf(nil, "message #%d", s.receiveCounter.Load())}
297 return []*driver.Message{msg}, nil
298 }
299 func (*secondReceiveBlockedDriverSub) CanNack() bool { return false }
300 func (*secondReceiveBlockedDriverSub) SendAcks(_ context.Context, _ []driver.AckID) error { return nil }
301 func (*secondReceiveBlockedDriverSub) IsRetryable(error) bool { return false }
302 func (*secondReceiveBlockedDriverSub) Close() error { return nil }
303
304 // TestIndependentBatchReturn verifies that when multiple batch requests are sent,
305 // as long as one of them succeeds it should not block Subscription.Receive.
306 func TestIndependentBatchReturn(t *testing.T) {
307 s := NewSubscription(
308 &secondReceiveBlockedDriverSub{},
309 &batcher.Options{MaxBatchSize: 1, MaxHandlers: 2}, // force 2 batches by allowing 2 handlers and 1 msg per batch
310 nil,
311 )
312 ctx := context.Background()
313 defer s.Shutdown(ctx)
314
315 // Set the batch size to force 2 batches to be called.
316 s.runningBatchSize = 2
317 ctxTimeout, cancel := context.WithTimeout(ctx, 10*time.Second)
318 defer cancel()
319 m, err := s.Receive(ctxTimeout)
320 if err != nil {
321 t.Fatal("Receive should not fail", err)
322 return
323 }
324 m.Ack()
325 }
326
327 func TestRetryTopic(t *testing.T) {
328 // Test that Send is retried if the driver returns a retryable error.
329 ctx := context.Background()
330 ft := &failTopic{}
331 topic := NewTopic(ft, nil)
332 defer topic.Shutdown(ctx)
333 err := topic.Send(ctx, &Message{})
334 if err != nil {
335 t.Errorf("Send: got %v, want nil", err)
336 }
337 if got, want := ft.calls, nRetryCalls+1; got != want {
338 t.Errorf("calls: got %d, want %d", got, want)
339 }
340 }
341
342 var errRetry = errors.New("retry")
343
344 func isRetryable(err error) bool {
345 return err == errRetry
346 }
347
348 const nRetryCalls = 2
349
350 // failTopic helps test retries for SendBatch.
351 //
352 // SendBatch will fail nRetryCall times before succeeding.
353 type failTopic struct {
354 driver.Topic
355 calls int
356 }
357
358 func (t *failTopic) SendBatch(ctx context.Context, ms []*driver.Message) error {
359 t.calls++
360 if t.calls <= nRetryCalls {
361 return errRetry
362 }
363 return nil
364 }
365
366 func (*failTopic) IsRetryable(err error) bool { return isRetryable(err) }
367 func (*failTopic) ErrorCode(error) gcerrors.ErrorCode { return gcerrors.Unknown }
368 func (*failTopic) Close() error { return nil }
369
370 func TestRetryReceive(t *testing.T) {
371 ctx := context.Background()
372 fs := &failSub{fail: true}
373 sub := NewSubscription(fs, nil, nil)
374 defer sub.Shutdown(ctx)
375 m, err := sub.Receive(ctx)
376 if err != nil {
377 t.Fatalf("Receive: got %v, want nil", err)
378 }
379 m.Ack()
380 if got, want := fs.calls, nRetryCalls+1; got != want {
381 t.Errorf("calls: got %d, want %d", got, want)
382 }
383 }
384
385 // TestBatchSizeDecay verifies that the batch size decays when no messages are available.
386 // (see https://github.com/google/go-cloud/issues/2849).
387 func TestBatchSizeDecays(t *testing.T) {
388 ctx := context.Background()
389 fs := &failSub{}
390 // Allow multiple handlers and cap max batch size to ensure we get concurrency.
391 sub := NewSubscription(fs, &batcher.Options{MaxHandlers: 10, MaxBatchSize: 2}, nil)
392 defer sub.Shutdown(ctx)
393
394 // Records the last batch size.
395 var mu sync.Mutex
396 lastMaxMessages := 0
397 sub.preReceiveBatchHook = func(maxMessages int) {
398 mu.Lock()
399 defer mu.Unlock()
400 lastMaxMessages = maxMessages
401 }
402
403 // Do some receives to allow the number of batches to increase past 1.
404 for range 100 {
405 m, err := sub.Receive(ctx)
406 if err != nil {
407 t.Fatalf("Receive: got %v, want nil", err)
408 }
409 m.Ack()
410 }
411
412 // Tell the failSub to start returning no messages.
413 fs.mu.Lock()
414 fs.empty = true
415 fs.mu.Unlock()
416
417 mu.Lock()
418 highWaterMarkBatchSize := lastMaxMessages
419 if lastMaxMessages <= 1 {
420 t.Fatal("max messages wasn't greater than 1")
421 }
422 mu.Unlock()
423
424 // Make a bunch of calls to Receive to drain any outstanding
425 // messages, and wait some extra time during which we should
426 // continue polling, and the batch size should decay.
427 for {
428 ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
429 defer cancel()
430 m, err := sub.Receive(ctx)
431 if err != nil {
432 // Expected: no more messages, and timed out.
433 break
434 }
435 // Drained a message.
436 m.Ack()
437 }
438
439 // Verify that the batch size decayed.
440 mu.Lock()
441 if lastMaxMessages >= highWaterMarkBatchSize {
442 t.Fatalf("wanted batch size to decay; high water mark was %d, now %d", highWaterMarkBatchSize, lastMaxMessages)
443 }
444 mu.Unlock()
445 }
446
447 // TestRetryReceiveBatches verifies that batching and retries work without races
448 // (see https://github.com/google/go-cloud/issues/2676).
449 func TestRetryReceiveInBatchesDoesntRace(t *testing.T) {
450 ctx := context.Background()
451 fs := &failSub{}
452 // Allow multiple handlers and cap max batch size to ensure we get concurrency.
453 sub := NewSubscription(fs, &batcher.Options{MaxHandlers: 10, MaxBatchSize: 2}, nil)
454 defer sub.Shutdown(ctx)
455
456 // Do some receives to allow the number of batches to increase past 1.
457 for range 100 {
458 m, err := sub.Receive(ctx)
459 if err != nil {
460 t.Fatalf("Receive: got %v, want nil", err)
461 }
462 m.Ack()
463 }
464 // Tell the failSub to start failing.
465 fs.mu.Lock()
466 fs.fail = true
467 fs.mu.Unlock()
468
469 // This call to Receive should result in nRetryCalls+1 calls to ReceiveBatch for
470 // each batch. In the issue noted above, this would cause a race.
471 for range 100 {
472 m, err := sub.Receive(ctx)
473 if err != nil {
474 t.Fatalf("Receive: got %v, want nil", err)
475 }
476 m.Ack()
477 }
478 // Don't try to verify the exact number of calls, as it is unpredictable
479 // based on the timing of the batching.
480 }
481
482 // failSub helps test retries for ReceiveBatch.
483 //
484 // Once start=true, ReceiveBatch will fail nRetryCalls times before succeeding.
485 type failSub struct {
486 driver.Subscription
487 fail bool
488 empty bool
489 calls int
490 mu sync.Mutex
491 }
492
493 func (t *failSub) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
494 t.mu.Lock()
495 defer t.mu.Unlock()
496 if t.fail {
497 t.calls++
498 if t.calls <= nRetryCalls {
499 return nil, errRetry
500 }
501 }
502 if t.empty {
503 t.calls++
504 return nil, nil
505 }
506 return []*driver.Message{{Body: []byte("")}}, nil
507 }
508
509 func (*failSub) SendAcks(ctx context.Context, ackIDs []driver.AckID) error { return nil }
510 func (*failSub) IsRetryable(err error) bool { return isRetryable(err) }
511 func (*failSub) CanNack() bool { return false }
512 func (*failSub) Close() error { return nil }
513
514 // TODO(jba): add a test for retry of SendAcks.
515
516 var errDriver = errors.New("driver error")
517
518 type erroringTopic struct {
519 driver.Topic
520 }
521
522 func (erroringTopic) SendBatch(context.Context, []*driver.Message) error { return errDriver }
523 func (erroringTopic) IsRetryable(err error) bool { return isRetryable(err) }
524 func (erroringTopic) ErrorCode(error) gcerrors.ErrorCode { return gcerrors.AlreadyExists }
525 func (erroringTopic) Close() error { return errDriver }
526
527 type erroringSubscription struct {
528 driver.Subscription
529 }
530
531 func (erroringSubscription) ReceiveBatch(context.Context, int) ([]*driver.Message, error) {
532 return nil, errDriver
533 }
534
535 func (erroringSubscription) SendAcks(context.Context, []driver.AckID) error { return errDriver }
536 func (erroringSubscription) IsRetryable(err error) bool { return isRetryable(err) }
537 func (erroringSubscription) ErrorCode(error) gcerrors.ErrorCode { return gcerrors.AlreadyExists }
538 func (erroringSubscription) CanNack() bool { return false }
539 func (erroringSubscription) Close() error { return errDriver }
540
541 // TestErrorsAreWrapped tests that all errors returned from the driver are
542 // wrapped exactly once by the portable type.
543 func TestErrorsAreWrapped(t *testing.T) {
544 ctx := context.Background()
545
546 verify := func(err error) {
547 t.Helper()
548 if err == nil {
549 t.Errorf("got nil error, wanted non-nil")
550 return
551 }
552 if e, ok := err.(*gcerr.Error); !ok {
553 t.Errorf("not wrapped: %v", err)
554 } else if got := e.Unwrap(); got != errDriver {
555 t.Errorf("got %v for wrapped error, not errDriver", got)
556 }
557 if s := err.Error(); !strings.HasPrefix(s, "pubsub ") {
558 t.Errorf("Error() for wrapped error doesn't start with 'pubsub': prefix: %s", s)
559 }
560 }
561
562 topic := NewTopic(erroringTopic{}, nil)
563 verify(topic.Send(ctx, &Message{}))
564 err := topic.Shutdown(ctx)
565 verify(err)
566
567 sub := NewSubscription(erroringSubscription{}, nil, nil)
568 _, err = sub.Receive(ctx)
569 verify(err)
570 err = sub.Shutdown(ctx)
571 verify(err)
572 }
573
574 // TestOpenTelemetry tests that OpenTelemetry tracing is working correctly.
575 func TestOpenTelemetry(t *testing.T) {
576 ctx := context.Background()
577
578 te := oteltest.NewTestExporter(t, OpenTelemetryViews)
579 defer func() {
580 err := te.Shutdown(ctx)
581 if err != nil {
582 t.Logf("Error shutting down test exporter: %v", err)
583 }
584 }()
585
586 ds := NewDriverSub()
587 dt := &driverTopic{
588 subs: []*driverSub{ds},
589 }
590 topic := NewTopic(dt, nil)
591 defer topic.Shutdown(ctx)
592 sub := NewSubscription(ds, nil, nil)
593 defer sub.Shutdown(ctx)
594 if err := topic.Send(ctx, &Message{Body: []byte("x")}); err != nil {
595 t.Fatal(err)
596 }
597 if err := topic.Shutdown(ctx); err != nil {
598 t.Fatal(err)
599 }
600 msg, err := sub.Receive(ctx)
601 if err != nil {
602 t.Fatal(err)
603 }
604 msg.Ack()
605 err = sub.Shutdown(ctx)
606 if err != nil {
607 t.Fatal(err)
608 }
609 _, _ = sub.Receive(ctx)
610
611 spans := te.GetSpans()
612 metrics := te.GetMetrics(ctx)
613
614 diff := oteltest.Diff(spans.Snapshots(), metrics, pkgName, "gocloud.dev/pubsub", []oteltest.Call{
615 {Method: "driver.Topic.SendBatch", Code: gcerrors.OK},
616 {Method: "Topic.Send", Code: gcerrors.OK},
617 {Method: "Topic.Shutdown", Code: gcerrors.OK},
618 {Method: "driver.Subscription.ReceiveBatch", Code: gcerrors.OK},
619 {Method: "Subscription.Receive", Code: gcerrors.OK},
620 {Method: "driver.Subscription.SendAcks", Code: gcerrors.OK},
621 {Method: "Subscription.Shutdown", Code: gcerrors.OK},
622 {Method: "Subscription.Receive", Code: gcerrors.FailedPrecondition},
623 })
624 if diff != "" {
625 t.Error(diff)
626 }
627 }
628
629 func TestURLMux(t *testing.T) {
630 ctx := context.Background()
631
632 mux := new(URLMux)
633 fake := &fakeOpener{}
634 mux.RegisterTopic("foo", fake)
635 mux.RegisterTopic("err", fake)
636 mux.RegisterSubscription("foo", fake)
637 mux.RegisterSubscription("err", fake)
638
639 if diff := cmp.Diff(mux.TopicSchemes(), []string{"err", "foo"}); diff != "" {
640 t.Errorf("Schemes: %s", diff)
641 }
642 if !mux.ValidTopicScheme("foo") || !mux.ValidTopicScheme("err") {
643 t.Errorf("ValidTopicScheme didn't return true for valid scheme")
644 }
645 if mux.ValidTopicScheme("foo2") || mux.ValidTopicScheme("http") {
646 t.Errorf("ValidTopicScheme didn't return false for invalid scheme")
647 }
648
649 if diff := cmp.Diff(mux.SubscriptionSchemes(), []string{"err", "foo"}); diff != "" {
650 t.Errorf("Schemes: %s", diff)
651 }
652 if !mux.ValidSubscriptionScheme("foo") || !mux.ValidSubscriptionScheme("err") {
653 t.Errorf("ValidSubscriptionScheme didn't return true for valid scheme")
654 }
655 if mux.ValidSubscriptionScheme("foo2") || mux.ValidSubscriptionScheme("http") {
656 t.Errorf("ValidSubscriptionScheme didn't return false for invalid scheme")
657 }
658
659 for _, tc := range []struct {
660 name string
661 url string
662 wantErr bool
663 }{
664 {
665 name: "empty URL",
666 wantErr: true,
667 },
668 {
669 name: "invalid URL",
670 url: ":foo",
671 wantErr: true,
672 },
673 {
674 name: "invalid URL no scheme",
675 url: "foo",
676 wantErr: true,
677 },
678 {
679 name: "unregistered scheme",
680 url: "bar://myps",
681 wantErr: true,
682 },
683 {
684 name: "func returns error",
685 url: "err://myps",
686 wantErr: true,
687 },
688 {
689 name: "no query options",
690 url: "foo://myps",
691 },
692 {
693 name: "empty query options",
694 url: "foo://myps?",
695 },
696 {
697 name: "query options",
698 url: "foo://myps?aAa=bBb&cCc=dDd",
699 },
700 {
701 name: "multiple query options",
702 url: "foo://myps?x=a&x=b&x=c",
703 },
704 {
705 name: "fancy ps name",
706 url: "foo:///foo/bar/baz",
707 },
708 {
709 name: "using api schema prefix",
710 url: "pubsub+foo://foo",
711 },
712 } {
713 t.Run("topic: "+tc.name, func(t *testing.T) {
714 _, gotErr := mux.OpenTopic(ctx, tc.url)
715 if (gotErr != nil) != tc.wantErr {
716 t.Fatalf("got err %v, want error %v", gotErr, tc.wantErr)
717 }
718 if gotErr != nil {
719 return
720 }
721 if got := fake.u.String(); got != tc.url {
722 t.Errorf("got %q want %q", got, tc.url)
723 }
724 // Repeat with OpenTopicURL.
725 parsed, err := url.Parse(tc.url)
726 if err != nil {
727 t.Fatal(err)
728 }
729 _, gotErr = mux.OpenTopicURL(ctx, parsed)
730 if gotErr != nil {
731 t.Fatalf("got err %v, want nil", gotErr)
732 }
733 if got := fake.u.String(); got != tc.url {
734 t.Errorf("got %q want %q", got, tc.url)
735 }
736 })
737 t.Run("subscription: "+tc.name, func(t *testing.T) {
738 _, gotErr := mux.OpenSubscription(ctx, tc.url)
739 if (gotErr != nil) != tc.wantErr {
740 t.Fatalf("got err %v, want error %v", gotErr, tc.wantErr)
741 }
742 if gotErr != nil {
743 return
744 }
745 if got := fake.u.String(); got != tc.url {
746 t.Errorf("got %q want %q", got, tc.url)
747 }
748 // Repeat with OpenSubscriptionURL.
749 parsed, err := url.Parse(tc.url)
750 if err != nil {
751 t.Fatal(err)
752 }
753 _, gotErr = mux.OpenSubscriptionURL(ctx, parsed)
754 if gotErr != nil {
755 t.Fatalf("got err %v, want nil", gotErr)
756 }
757 if got := fake.u.String(); got != tc.url {
758 t.Errorf("got %q want %q", got, tc.url)
759 }
760 })
761 }
762 }
763
764 type fakeOpener struct {
765 u *url.URL // last url passed to OpenTopicURL/OpenSubscriptionURL
766 }
767
768 func (o *fakeOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*Topic, error) {
769 if u.Scheme == "err" {
770 return nil, errors.New("fail")
771 }
772 o.u = u
773 return nil, nil
774 }
775
776 func (o *fakeOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*Subscription, error) {
777 if u.Scheme == "err" {
778 return nil, errors.New("fail")
779 }
780 o.u = u
781 return nil, nil
782 }