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.
 
 
 

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