/
consul_test_server.go
73 lines (64 loc) · 1.72 KB
/
consul_test_server.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
package consul
import (
"fmt"
"net"
"testing"
"time"
timeutil "github.com/allegro/marathon-consul/time"
"github.com/hashicorp/consul/testutil"
"github.com/stretchr/testify/assert"
)
func CreateTestServer(t *testing.T) *testutil.TestServer {
ports, err := getPorts(6)
assert.NoError(t, err)
return testutil.NewTestServerConfig(t, func(c *testutil.TestServerConfig) {
c.Datacenter = fmt.Sprint("dc-", time.Now().UnixNano())
c.Ports = &testutil.TestPortConfig{
DNS: ports[0],
HTTP: ports[1],
RPC: ports[2],
SerfLan: ports[3],
SerfWan: ports[4],
Server: ports[5],
}
})
}
// Ask the kernel for free open ports that are ready to use
func getPorts(number int) ([]int, error) {
ports := make([]int, number)
listener := make([]*net.TCPListener, number)
defer func() {
for _, l := range listener {
l.Close()
}
}()
for i := 0; i < number; i++ {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return nil, err
}
listener[i], err = net.ListenTCP("tcp", addr)
if err != nil {
return nil, err
}
ports[i] = listener[i].Addr().(*net.TCPAddr).Port
}
return ports, nil
}
func ClientAtServer(server *testutil.TestServer) *Consul {
return consulClientAtAddress(server.Config.Bind, server.Config.Ports.HTTP)
}
func FailingClient() *Consul {
return consulClientAtAddress("127.5.5.5", 5555)
}
func consulClientAtAddress(host string, port int) *Consul {
config := Config{
Timeout: timeutil.Interval{Duration: 10 * time.Millisecond},
Port: fmt.Sprintf("%d", port),
ConsulNameSeparator: ".",
}
consul := New(config)
// initialize the agents cache with a single client pointing at provided location
consul.AddAgent(host)
return consul
}