/
pubsub_test.go
64 lines (57 loc) · 1.47 KB
/
pubsub_test.go
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
package pubsub
import (
"cloud.google.com/go/pubsub"
"context"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"testing"
)
func TestPubsub(t *testing.T) {
ctx := context.Background()
container, err := setupPubsub(ctx)
if err != nil {
t.Fatal(err)
}
// Clean up the container after the test is complete
t.Cleanup(func() {
if err := container.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
})
conn, err := grpc.Dial(container.URI, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
options := []option.ClientOption{option.WithGRPCConn(conn)}
client, err := pubsub.NewClient(ctx, "my-project-id", options...)
if err != nil {
t.Fatal(err)
}
defer client.Close()
topic, err := client.CreateTopic(ctx, "greetings")
if err != nil {
t.Fatal(err)
}
subscription, err := client.CreateSubscription(ctx, "subscription",
pubsub.SubscriptionConfig{Topic: topic})
if err != nil {
t.Fatal(err)
}
result := topic.Publish(ctx, &pubsub.Message{Data: []byte("Hello World")})
_, err = result.Get(ctx)
if err != nil {
t.Fatal(err)
}
// perform assertions
var data []byte
cctx, cancel := context.WithCancel(ctx)
err = subscription.Receive(cctx, func(ctx context.Context, m *pubsub.Message) {
data = m.Data
m.Ack()
defer cancel()
})
if string(data) != "Hello World" {
t.Fatalf("Expected value %s. Got %s.", "Hello World", data)
}
}