-
Notifications
You must be signed in to change notification settings - Fork 41
/
capture_metrics_test.go
103 lines (98 loc) · 2.47 KB
/
capture_metrics_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
package httpsnoop
import (
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
)
func TestCaptureMetrics(t *testing.T) {
// Some of the edge cases tested below cause the net/http pkg to log some
// messages that add a lot of noise to the `go test -v` output, so we discard
// the log here.
log.SetOutput(io.Discard)
defer log.SetOutput(os.Stderr)
tests := []struct {
Handler http.Handler
WantDuration time.Duration
WantWritten int64
WantCode int
WantErr string
}{
{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}),
WantCode: http.StatusOK,
},
{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("foo"))
w.Write([]byte("bar"))
time.Sleep(25 * time.Millisecond)
}),
WantCode: http.StatusBadRequest,
WantWritten: 6,
WantDuration: 25 * time.Millisecond,
},
{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("foo"))
w.WriteHeader(http.StatusNotFound)
}),
WantCode: http.StatusOK,
},
{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rrf := w.(io.ReaderFrom)
rrf.ReadFrom(strings.NewReader("reader from is ok"))
}),
WantWritten: 17,
WantCode: http.StatusOK,
},
{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic("oh no")
}),
WantErr: "EOF",
},
}
for i, test := range tests {
func() {
ch := make(chan Metrics, 1)
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ch <- CaptureMetrics(test.Handler, w, r)
})
s := httptest.NewServer(h)
defer s.Close()
res, err := http.Get(s.URL)
if !errContains(err, test.WantErr) {
t.Errorf("test %d: got=%s want=%s", i, err, test.WantErr)
}
if err != nil {
return
}
defer res.Body.Close()
m := <-ch
if m.Code != test.WantCode {
t.Errorf("test %d: got=%d want=%d", i, m.Code, test.WantCode)
} else if m.Duration < test.WantDuration {
t.Errorf("test %d: got=%s want=%s", i, m.Duration, test.WantDuration)
} else if m.Written < test.WantWritten {
t.Errorf("test %d: got=%d want=%d", i, m.Written, test.WantWritten)
}
}()
}
}
func errContains(err error, s string) bool {
var errS string
if err == nil {
errS = ""
} else {
errS = err.Error()
}
return strings.Contains(errS, s)
}