-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollector_test.go
77 lines (64 loc) · 1.77 KB
/
collector_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
package main
import (
"errors"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
traceroute "github.com/jefsg/traceroute-exporter/traceroute"
log "github.com/sirupsen/logrus"
)
// test traceMiddleware
func TestEmptyTargetParam(t *testing.T) {
resp := traceHandlerTestHelper("GET", "/trace?target=")
assertEqual(t, resp.StatusCode, 400)
}
func TestNoTargetParam(t *testing.T) {
resp := traceHandlerTestHelper("GET", "/trace")
assertEqual(t, resp.StatusCode, 400)
}
func TestWithValidTarget(t *testing.T) {
resp := traceHandlerTestHelper("GET", "/trace?target=google.com")
assertEqual(t, resp.StatusCode, 200)
}
func TestWithFailedTrace(t *testing.T) {
resp := traceHandlerTestHelper("GET", "/trace?target=fail.com")
assertEqual(t, resp.StatusCode, 500)
}
// Helper functions
func traceHandlerTestHelper(method string, path string) *http.Response {
req := httptest.NewRequest(method, "http://example.com"+path, nil)
w := httptest.NewRecorder()
traceHandler(w, req, fakeHTTPHandler(), fakeTracer)
return w.Result()
}
func fakeHTTPHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("success")) //nolint
})
}
// fake tracer sends success response, unless host string contains the
// substring "fail"
func fakeTracer(host string) ([]traceroute.Hop, error) {
if strings.Contains(host, "fail") {
return []traceroute.Hop{}, errors.New("contrived tracer error for testing")
}
return []traceroute.Hop{
traceroute.Hop{
Number: "1",
Name: "hostname",
Address: "address",
Latency: 10.01,
},
}, nil
}
func assertEqual(t *testing.T, a interface{}, b interface{}) {
if a != b {
t.Fatalf("%s != %s", a, b)
}
}
func init() {
// disable log output while testing
log.SetOutput(ioutil.Discard)
}