You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

94 lines
2.2 KiB

  1. // Copyright 2018 Google LLC
  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. // http://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. import (
  16. "context"
  17. "log"
  18. "sync/atomic"
  19. "testing"
  20. "time"
  21. "cloud.google.com/go/pubsub/pstest"
  22. "google.golang.org/api/option"
  23. "google.golang.org/grpc"
  24. )
  25. // Using the fake PubSub server in the pstest package, verify that streaming
  26. // pull resumes if the server stream times out.
  27. func TestStreamTimeout(t *testing.T) {
  28. t.Parallel()
  29. log.SetFlags(log.Lmicroseconds)
  30. ctx := context.Background()
  31. srv := pstest.NewServer()
  32. defer srv.Close()
  33. srv.SetStreamTimeout(2 * time.Second)
  34. conn, err := grpc.Dial(srv.Addr, grpc.WithInsecure())
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. defer conn.Close()
  39. client, err := NewClient(ctx, "P", option.WithGRPCConn(conn))
  40. if err != nil {
  41. t.Fatal(err)
  42. }
  43. defer client.Close()
  44. topic, err := client.CreateTopic(ctx, "T")
  45. if err != nil {
  46. t.Fatal(err)
  47. }
  48. sub, err := client.CreateSubscription(ctx, "sub", SubscriptionConfig{Topic: topic, AckDeadline: 10 * time.Second})
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. const nPublish = 8
  53. rctx, cancel := context.WithTimeout(ctx, 30*time.Second)
  54. defer cancel()
  55. errc := make(chan error)
  56. var nSeen int64
  57. go func() {
  58. errc <- sub.Receive(rctx, func(ctx context.Context, m *Message) {
  59. m.Ack()
  60. n := atomic.AddInt64(&nSeen, 1)
  61. if n >= nPublish {
  62. cancel()
  63. }
  64. })
  65. }()
  66. for i := 0; i < nPublish; i++ {
  67. pr := topic.Publish(ctx, &Message{Data: []byte("msg")})
  68. _, err := pr.Get(ctx)
  69. if err != nil {
  70. t.Fatal(err)
  71. }
  72. time.Sleep(250 * time.Millisecond)
  73. }
  74. if err := <-errc; err != nil {
  75. t.Fatal(err)
  76. }
  77. if err := sub.Delete(ctx); err != nil {
  78. t.Fatal(err)
  79. }
  80. n := atomic.LoadInt64(&nSeen)
  81. if n < nPublish {
  82. t.Errorf("got %d messages, want %d", n, nPublish)
  83. }
  84. }