-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnode_test.go
122 lines (105 loc) · 2.31 KB
/
node_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
package dht
import (
"strconv"
"testing"
"time"
"github.com/hashicorp/consul/api"
"github.com/stvp/tempconsul"
)
func apiClient() (client *api.Client) {
client, _ = api.NewClient(api.DefaultConfig())
return client
}
func startConsul() (server *tempconsul.Server, err error) {
server = &tempconsul.Server{}
return server, server.Start()
}
func servicesCount(name string) (count int, err error) {
services, _, err := apiClient().Catalog().Service(name, "", nil)
return len(services), err
}
func TestJoinLeave(t *testing.T) {
// No Consul agent
_, err := Join("test", "a")
if err == nil {
t.Errorf("expected error got nil")
}
// Start Consul agent
server, err := startConsul()
if err != nil {
t.Fatal(err)
}
defer server.Term()
// Valid join
node, err := Join("test", "a")
if err != nil {
t.Fatal(err)
}
count, err := servicesCount("test")
if err != nil {
t.Fatal(err)
}
if count != 1 {
t.Errorf("expected 1 service registered, got %d", count)
}
// Leave
err = node.Leave()
if err != nil {
t.Error(err)
}
count, err = servicesCount("test")
if err != nil {
t.Fatal(err)
}
if count != 0 {
t.Errorf("expected 0 service registered, got %d", count)
}
}
func TestMember(t *testing.T) {
server, err := startConsul()
if err != nil {
t.Fatal(err)
}
defer server.Term()
n := 3
nodes := make([]*Node, n)
for i := 0; i < n; i++ {
nodes[i], err = Join("test", strconv.Itoa(i))
if err != nil {
t.Fatal(err)
}
}
// Ensure nodes have the latest state. First we have to wait for consul
// to run all checks so that all services are "passing".
time.Sleep(checkInterval * 2)
for _, node := range nodes {
node.waitIndex = 0
node.update()
}
tests := []struct {
key string
member []bool
}{
{"", []bool{true, false, false}},
{"a", []bool{true, false, false}},
{"b", []bool{false, false, true}},
{"d9edf13e917c4f0f66be0e80cc30060e", []bool{false, true, false}},
{"a2a9538886f1df96be9e5b52b14b404a", []bool{false, false, true}},
}
for _, test := range tests {
for i, node := range nodes {
expect := test.member[i]
got := node.Member(test.key)
if got != expect {
t.Errorf("nodes[%d].Member(%#v): expected %v, got %v", i, test.key, expect, got)
}
}
}
// Clean up
for _, node := range nodes {
err = node.Leave()
if err != nil {
t.Error(err)
}
}
}