forked from Shopify/toxiproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toxiproxy_test.go
56 lines (46 loc) · 1.29 KB
/
toxiproxy_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
package toxiproxy_test
import (
"flag"
"net"
"os"
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/zerolog"
"github.com/Shopify/toxiproxy/v2"
"github.com/Shopify/toxiproxy/v2/collectors"
"github.com/Shopify/toxiproxy/v2/testhelper"
)
func NewTestProxy(name, upstream string) *toxiproxy.Proxy {
log := zerolog.Nop()
if flag.Lookup("test.v").DefValue == "true" {
log = zerolog.New(os.Stdout).With().Caller().Timestamp().Logger()
}
srv := toxiproxy.NewServer(
toxiproxy.NewMetricsContainer(prometheus.NewRegistry()),
log,
)
srv.Metrics.ProxyMetrics = collectors.NewProxyMetricCollectors()
proxy := toxiproxy.NewProxy(srv, name, "localhost:0", upstream)
return proxy
}
func WithTCPProxy(
t *testing.T,
f func(proxy net.Conn, response chan []byte, proxyServer *toxiproxy.Proxy),
) {
testhelper.WithTCPServer(t, func(upstream string, response chan []byte) {
proxy := NewTestProxy("test", upstream)
proxy.Start()
conn := AssertProxyUp(t, proxy.Listen, true)
f(conn, response, proxy)
proxy.Stop()
})
}
func AssertProxyUp(t *testing.T, addr string, up bool) net.Conn {
conn, err := net.Dial("tcp", addr)
if err != nil && up {
t.Error("Expected proxy to be up:", err)
} else if err == nil && !up {
t.Error("Expected proxy to be down")
}
return conn
}