File: timeout_test.go

package info (click to toggle)
golang-google-cloud 0.56.0-6
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 22,456 kB
  • sloc: sh: 191; ansic: 75; awk: 64; makefile: 51; asm: 46; python: 21
file content (94 lines) | stat: -rw-r--r-- 2,324 bytes parent folder | download | duplicates (5)
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
// Copyright 2018 Google LLC
//
// 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
//
//      http://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 pubsub

import (
	"context"
	"log"
	"sync/atomic"
	"testing"
	"time"

	"cloud.google.com/go/pubsub/pstest"
	"google.golang.org/api/option"
	"google.golang.org/grpc"
)

// Using the fake PubSub server in the pstest package, verify that streaming
// pull resumes if the server stream times out.
func TestStreamTimeout(t *testing.T) {
	t.Parallel()
	log.SetFlags(log.Lmicroseconds)
	ctx := context.Background()
	srv := pstest.NewServer()
	defer srv.Close()

	srv.SetStreamTimeout(2 * time.Second)
	conn, err := grpc.Dial(srv.Addr, grpc.WithInsecure())
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()

	opts := withGRPCHeadersAssertion(t, option.WithGRPCConn(conn))
	client, err := NewClient(ctx, "P", opts...)
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close()

	topic, err := client.CreateTopic(ctx, "T")
	if err != nil {
		t.Fatal(err)
	}
	sub, err := client.CreateSubscription(ctx, "sub", SubscriptionConfig{Topic: topic, AckDeadline: 10 * time.Second})
	if err != nil {
		t.Fatal(err)
	}
	const nPublish = 8
	rctx, cancel := context.WithTimeout(ctx, 30*time.Second)
	defer cancel()
	errc := make(chan error)
	var nSeen int64
	go func() {
		errc <- sub.Receive(rctx, func(ctx context.Context, m *Message) {
			m.Ack()
			n := atomic.AddInt64(&nSeen, 1)
			if n >= nPublish {
				cancel()
			}
		})
	}()

	for i := 0; i < nPublish; i++ {
		pr := topic.Publish(ctx, &Message{Data: []byte("msg")})
		_, err := pr.Get(ctx)
		if err != nil {
			t.Fatal(err)
		}
		time.Sleep(250 * time.Millisecond)
	}

	if err := <-errc; err != nil {
		t.Fatal(err)
	}
	if err := sub.Delete(ctx); err != nil {
		t.Fatal(err)
	}
	n := atomic.LoadInt64(&nSeen)
	if n < nPublish {
		t.Errorf("got %d messages, want %d", n, nPublish)
	}
}