Debian Codegraph @

samples/gocdk-pubsub/main_test.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
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 // https://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
15 package main
16
17 import (
18 "flag"
19 "os"
20 "testing"
21
22 "github.com/google/go-cmdtest"
23 "github.com/streadway/amqp"
24 "gocloud.dev/internal/testing/setup"
25 )
26
27 // Requires rabbit to be running. Run pubsub/rabbitpubsub/localrabbit.sh.
28
29 var update = flag.Bool("update", false, "replace test file contents with output")
30
31 func Test(t *testing.T) {
32 if !setup.HasDockerTestEnvironment() {
33 t.Skip("do not have docker test environment")
34 }
35 ts, err := cmdtest.Read(".")
36 if err != nil {
37 t.Fatal(err)
38 }
39 os.Setenv("RABBIT_SERVER_URL", rabbitURL)
40 if err := initRabbit(); err != nil {
41 t.Fatal(err)
42 }
43 ts.Commands["gocdk-pubsub"] = cmdtest.InProcessProgram("gocdk-pubsub", run)
44 ts.Run(t, *update)
45 }
46
47 const (
48 rabbitURL = "amqp://guest:guest@localhost:5672/"
49
50 // These names must match the URLs in the pubsub.ct file.
51 topicName = "sample-topic"
52 subscriptionName = "sample-subscription"
53 )
54
55 // Set up a topic and subscription.
56 func initRabbit() error {
57 conn, err := amqp.Dial(rabbitURL)
58 if err != nil {
59 return err
60 }
61 defer conn.Close()
62 ch, err := conn.Channel()
63 if err != nil {
64 return err
65 }
66 defer ch.Close()
67 if err := ch.Confirm(false); err != nil {
68 return err
69 }
70 err = ch.ExchangeDeclare(topicName,
71 "fanout", // kind
72 false, // durable
73 false, // delete when unused
74 false, // internal
75 false, // wait for server response
76 nil) // args
77 if err != nil {
78 return err
79 }
80 q, err := ch.QueueDeclare(subscriptionName,
81 false, // durable
82 false, // delete when unused
83 false, // exclusive
84 false, // wait for server response
85 nil) // args
86 if err != nil {
87 return err
88 }
89 return ch.QueueBind(q.Name, q.Name, topicName, false, nil)
90 }