forked from cloudfoundry/gorouter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nats_client.go
77 lines (63 loc) · 1.31 KB
/
nats_client.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
package test_util
import (
. "github.com/onsi/gomega"
"errors"
"fmt"
"net"
"os/exec"
"strconv"
"time"
)
type Nats struct {
port uint16
cmd *exec.Cmd
address string
}
func NewNats(port uint16) *Nats {
return &Nats{
port: port,
address: fmt.Sprintf("127.0.0.1:%d", port),
}
}
func NewNatsOnRandomPort() *Nats {
return NewNats(NextAvailPort())
}
func (n *Nats) Port() uint16 {
return n.port
}
func (n *Nats) Start() {
cmd := exec.Command("gnatsd", "-p", strconv.Itoa(int(n.port)), "--user", "nats", "--pass", "nats")
err := cmd.Start()
Expect(err).ToNot(HaveOccurred())
n.cmd = cmd
err = n.waitUntilNatsUp()
Expect(err).ToNot(HaveOccurred())
}
func (n *Nats) Stop() {
n.cmd.Process.Kill()
n.cmd.Wait()
err := n.waitUntilNatsDown()
Expect(err).ToNot(HaveOccurred())
}
func (n *Nats) waitUntilNatsUp() error {
maxWait := 10
for i := 0; i < maxWait; i++ {
time.Sleep(500 * time.Millisecond)
_, err := net.Dial("tcp", n.address)
if err == nil {
return nil
}
}
return errors.New("Waited too long for NATS to start")
}
func (n *Nats) waitUntilNatsDown() error {
maxWait := 10
for i := 0; i < maxWait; i++ {
time.Sleep(500 * time.Millisecond)
_, err := net.Dial("tcp", n.address)
if err != nil {
return nil
}
}
return errors.New("Waited too long for NATS to stop")
}