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.
 
 
 

79 lines
1.7 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_test
  15. import (
  16. "context"
  17. "strconv"
  18. "sync"
  19. "testing"
  20. "cloud.google.com/go/pubsub"
  21. "cloud.google.com/go/pubsub/pstest"
  22. "google.golang.org/api/option"
  23. "google.golang.org/grpc"
  24. )
  25. func TestPSTest(t *testing.T) {
  26. t.Parallel()
  27. ctx := context.Background()
  28. srv := pstest.NewServer()
  29. defer srv.Close()
  30. conn, err := grpc.Dial(srv.Addr, grpc.WithInsecure())
  31. if err != nil {
  32. panic(err)
  33. }
  34. defer conn.Close()
  35. client, err := pubsub.NewClient(ctx, "some-project", option.WithGRPCConn(conn))
  36. if err != nil {
  37. panic(err)
  38. }
  39. defer client.Close()
  40. topic, err := client.CreateTopic(ctx, "test-topic")
  41. if err != nil {
  42. panic(err)
  43. }
  44. sub, err := client.CreateSubscription(ctx, "sub-name", pubsub.SubscriptionConfig{Topic: topic})
  45. if err != nil {
  46. panic(err)
  47. }
  48. go func() {
  49. for i := 0; i < 10; i++ {
  50. srv.Publish("projects/some-project/topics/test-topic", []byte(strconv.Itoa(i)), nil)
  51. }
  52. }()
  53. ctx, cancel := context.WithCancel(ctx)
  54. var mu sync.Mutex
  55. count := 0
  56. err = sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {
  57. mu.Lock()
  58. count++
  59. if count >= 10 {
  60. cancel()
  61. }
  62. mu.Unlock()
  63. m.Ack()
  64. })
  65. if err != nil {
  66. panic(err)
  67. }
  68. }