-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathexample_test.go
270 lines (244 loc) · 7 KB
/
example_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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
// Tests to verify that example code behaves as expected.
// Run in this directory with `go test example_test.go`
//
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"math/rand"
"net"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"testing"
"time"
)
func fatalIf(t *testing.T, err error) {
if err != nil {
t.Fatalf("%s", err)
}
}
// A demo broker process
type broker struct {
cmd *exec.Cmd
addr string
runerr chan error
err error
}
// Try to connect to the broker to verify it is ready, give up after a timeout
func (b *broker) check() error {
dialer := net.Dialer{Deadline: time.Now().Add(time.Second * 10)}
for {
c, err := dialer.Dial("tcp", b.addr)
if err == nil { // Success
c.Close()
return nil
}
select {
case runerr := <-b.runerr: // Broker exited.
return runerr
default:
}
if neterr, ok := err.(net.Error); ok && neterr.Timeout() { // Running but timed out
b.stop()
return fmt.Errorf("timed out waiting for broker")
}
time.Sleep(time.Second / 10)
}
}
// Start the demo broker, wait till it is listening on *addr. No-op if already started.
func (b *broker) start(t *testing.T) error {
if b.cmd == nil { // Not already started
b.addr = fmt.Sprintf("127.0.0.1:%d", rand.Intn(10000)+10000)
b.cmd = exampleCommand(t, *brokerName, "-addr", b.addr)
b.runerr = make(chan error)
b.cmd.Stderr, b.cmd.Stdout = os.Stderr, os.Stdout
b.err = b.cmd.Start()
if b.err == nil {
go func() { b.runerr <- b.cmd.Wait() }()
} else {
b.runerr <- b.err
}
b.err = b.check()
}
return b.err
}
func (b *broker) stop() {
if b != nil && b.cmd != nil {
b.cmd.Process.Kill()
<-b.runerr
}
}
func checkEqual(want interface{}, got interface{}) error {
if reflect.DeepEqual(want, got) {
return nil
}
return fmt.Errorf("%#v != %#v", want, got)
}
// exampleCommand returns an exec.Cmd to run an example.
func exampleCommand(t *testing.T, prog string, arg ...string) (cmd *exec.Cmd) {
args := []string{}
if *debug {
args = append(args, "-debug=true")
}
args = append(args, arg...)
prog, err := filepath.Abs(path.Join(*dir, prog))
fatalIf(t, err)
if _, err := os.Stat(prog); err == nil {
cmd = exec.Command(prog, args...)
} else if _, err := os.Stat(prog + ".go"); err == nil {
args = append([]string{"run", prog + ".go"}, args...)
cmd = exec.Command("go", args...)
} else {
t.Fatalf("Cannot find binary or source for %s", prog)
}
cmd.Stderr = os.Stderr
return cmd
}
// Run an example Go program, return the combined output as a string.
func runExample(t *testing.T, prog string, arg ...string) (string, error) {
cmd := exampleCommand(t, prog, arg...)
out, err := cmd.Output()
return string(out), err
}
func prefix(prefix string, err error) error {
if err != nil {
return fmt.Errorf("%s: %s", prefix, err)
}
return nil
}
func runExampleWant(t *testing.T, want string, prog string, args ...string) error {
out, err := runExample(t, prog, args...)
if err != nil {
return fmt.Errorf("%s failed: %s: %s", prog, err, out)
}
return prefix(prog, checkEqual(want, out))
}
func exampleArgs(args ...string) []string {
for i := 0; i < *connections; i++ {
args = append(args, fmt.Sprintf("amqp://%s/%s%d", testBroker.addr, "q", i))
}
return args
}
// Send then receive
func TestExampleSendReceive(t *testing.T) {
if testing.Short() {
t.Skip("Skip demo tests in short mode")
}
testBroker.start(t)
err := runExampleWant(t,
fmt.Sprintf("Received all %d acknowledgements\n", expected),
"send",
exampleArgs("-count", fmt.Sprintf("%d", *count))...)
if err != nil {
t.Fatal(err)
}
err = runExampleWant(t,
fmt.Sprintf("Listening on %v connections\nReceived %v messages\n", *connections, *count**connections),
"receive",
exampleArgs("-count", fmt.Sprintf("%d", *count**connections))...)
if err != nil {
t.Fatal(err)
}
}
var ready error
func init() { ready = fmt.Errorf("Ready") }
// Run receive in a goroutine.
// Send ready on errchan when it is listening.
// Send final error when it is done.
// Returns the Cmd, caller must Wait()
func goReceiveWant(t *testing.T, errchan chan<- error, want string, arg ...string) *exec.Cmd {
cmd := exampleCommand(t, "receive", arg...)
go func() {
pipe, err := cmd.StdoutPipe()
if err != nil {
errchan <- err
return
}
out := bufio.NewReader(pipe)
cmd.Start()
line, err := out.ReadString('\n')
if err != nil && err != io.EOF {
errchan <- err
return
}
listening := "Listening on 3 connections\n"
if line != listening {
errchan <- checkEqual(listening, line)
return
}
errchan <- ready
buf := bytes.Buffer{}
io.Copy(&buf, out) // Collect the rest of the output
cmd.Wait()
errchan <- checkEqual(want, buf.String())
close(errchan)
}()
return cmd
}
// Start receiver first, wait till it is running, then send.
func TestExampleReceiveSend(t *testing.T) {
if testing.Short() {
t.Skip("Skip demo tests in short mode")
}
testBroker.start(t)
// Start receiver, wait for "listening" message on stdout
recvCmd := exampleCommand(t, "receive", exampleArgs(fmt.Sprintf("-count=%d", expected))...)
pipe, err := recvCmd.StdoutPipe()
if err != nil {
t.Fatal(err)
}
recvCmd.Start()
out := bufio.NewReader(pipe)
line, err := out.ReadString('\n')
if err := checkEqual("Listening on 3 connections\n", line); err != nil {
t.Fatal(err)
}
if err := runExampleWant(t,
fmt.Sprintf("Received all %d acknowledgements\n", expected),
"send",
exampleArgs("-count", fmt.Sprintf("%d", *count))...); err != nil {
t.Fatal(err)
}
buf := bytes.Buffer{}
io.Copy(&buf, out)
if err := checkEqual(fmt.Sprintf("Received %d messages\n", expected), buf.String()); err != nil {
t.Fatal(err)
}
}
var testBroker *broker
var debug = flag.Bool("debug", false, "Debugging output from examples")
var brokerName = flag.String("broker", "broker", "Name of broker executable to run")
var count = flag.Int("count", 3, "Count of messages to send in tests")
var connections = flag.Int("connections", 3, "Number of connections to make in tests")
var dir = flag.String("dir", "electron", "Directory containing example sources or binaries")
var expected int
func TestMain(m *testing.M) {
expected = (*count) * (*connections)
rand.Seed(time.Now().UTC().UnixNano())
testBroker = &broker{} // Broker is started on-demand by tests.
status := m.Run()
testBroker.stop()
os.Exit(status)
}