/
relay_stub_test.go
53 lines (44 loc) · 1.09 KB
/
relay_stub_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
package tchannel_test
import (
"math/rand"
"sync"
"testing"
. "github.com/uber/tchannel-go"
"github.com/stretchr/testify/assert"
)
type SimpleRelayHosts struct {
sync.RWMutex
r *rand.Rand
peers map[string][]string
}
func NewSimpleRelayHosts(peers map[string][]string) *SimpleRelayHosts {
// Use a known seed for repeatable tests.
return &SimpleRelayHosts{
r: NewRand(1),
peers: peers,
}
}
func (rh *SimpleRelayHosts) Get(service string) string {
rh.RLock()
defer rh.RUnlock()
available, ok := rh.peers[service]
if !ok || len(available) == 0 {
return ""
}
i := rh.r.Intn(len(available))
return available[i]
}
func (rh *SimpleRelayHosts) Add(service, hostPort string) {
rh.Lock()
rh.peers[service] = append(rh.peers[service], hostPort)
rh.Unlock()
}
func TestSimpleRelayHosts(t *testing.T) {
hosts := map[string][]string{
"foo": {"1.1.1.1:1234", "1.1.1.1:1235"},
"foo-canary": {},
}
rh := NewSimpleRelayHosts(hosts)
assert.Equal(t, "", rh.Get("foo-canary"), "Expected no canary hosts.")
assert.Equal(t, "1.1.1.1:1235", rh.Get("foo"), "Unexpected peer chosen.")
}