-
Notifications
You must be signed in to change notification settings - Fork 59
/
consul_test.go
115 lines (104 loc) · 2.62 KB
/
consul_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
package consul
import (
"context"
"testing"
"time"
"github.com/hashicorp/consul/api"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/resolver"
)
func TestPopulateEndpoints(t *testing.T) {
tests := []struct {
name string
input []string
wantCall []resolver.Address
}{
{"one",
[]string{"127.0.0.1:50051"},
[]resolver.Address{
{Addr: "127.0.0.1:50051"},
},
},
{"sorted",
[]string{"227.0.0.1:50051", "127.0.0.1:50051"},
[]resolver.Address{
{Addr: "127.0.0.1:50051"},
{Addr: "227.0.0.1:50051"},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var (
in = make(chan []string, len(tt.input))
)
fcc := &ClientConnMock{
UpdateStateFunc: func(state resolver.State) error {
require.Equal(t, tt.wantCall, state.Addresses)
return nil
},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go populateEndpoints(ctx, fcc, in)
in <- tt.input
time.Sleep(time.Millisecond)
require.Equal(t, 1, len(fcc.UpdateStateCalls()))
})
}
}
func TestWatchConsulService(t *testing.T) {
tests := []struct {
name string
tgt target
services []*api.ServiceEntry
errorFromService error
want []string
}{
{"simple", target{Service: "svc", Wait: time.Second},
[]*api.ServiceEntry{
{
Service: &api.AgentService{Address: "127.0.0.1", Port: 1024},
},
},
nil,
[]string{"127.0.0.1:1024"},
},
// TODO: Add more tests-cases
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var (
got []string
out = make(chan []string)
)
go func() {
for {
select {
case <-ctx.Done():
return
case got = <-out:
}
}
}()
fconsul := &servicerMock{
ServiceFunc: func(s1, s2 string, b bool, queryOptions *api.QueryOptions) ([]*api.ServiceEntry, *api.QueryMeta, error) {
require.Equal(t, tt.tgt.Service, s1)
require.Equal(t, tt.tgt.Tag, s2)
require.Equal(t, tt.tgt.Healthy, b)
require.Equal(t, tt.tgt.Near, queryOptions.Near)
require.Equal(t, tt.tgt.Wait, queryOptions.WaitTime)
require.Equal(t, tt.tgt.Dc, queryOptions.Datacenter)
require.Equal(t, tt.tgt.AllowStale, queryOptions.AllowStale)
require.Equal(t, tt.tgt.RequireConsistent, queryOptions.RequireConsistent)
return tt.services, &api.QueryMeta{LastIndex: 1}, tt.errorFromService
},
}
go watchConsulService(ctx, fconsul, tt.tgt, out)
time.Sleep(5 * time.Millisecond)
require.Equal(t, tt.want, got)
})
}
}