forked from mitchellh/go-server-timing
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware_test.go
75 lines (65 loc) · 1.54 KB
/
middleware_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
package servertiming
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestMiddleware(t *testing.T) {
cases := []struct {
Name string
Metrics []*Metric
Expected bool
}{
{
Name: "nil metrics",
Metrics: nil,
Expected: false,
},
{
Name: "empty metrics",
Metrics: []*Metric{},
Expected: false,
},
{
Name: "single metric",
Metrics: []*Metric{
{
Name: "sql-1",
Duration: 100 * time.Millisecond,
Desc: "MySQL; lookup Server",
},
},
Expected: true,
},
}
for _, tt := range cases {
t.Run(tt.Name, func(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
rec := httptest.NewRecorder()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set the metrics to the configured case
h := FromContext(r.Context())
if h == nil {
t.Fatal("expected *Header to be present in context")
}
h.Metrics = tt.Metrics
// Write the header to flush the response
w.WriteHeader(204)
})
// Perform the request
Middleware(handler, nil).ServeHTTP(rec, r)
// Test that it is present or not
_, present := map[string][]string(rec.Header())[HeaderKey]
if present != tt.Expected {
t.Fatalf("expected header to be present: %v, but wasn't", tt.Expected)
}
// Test the response
expected := (&Header{Metrics: tt.Metrics}).String()
actual := rec.Header().Get(HeaderKey)
if actual != expected {
t.Fatalf("got wrong value, expected != actual: %q != %q", expected, actual)
}
})
}
}