-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
65 lines (60 loc) · 1.55 KB
/
main_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
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestRecorder(t *testing.T) {
type checkFunc func(*httptest.ResponseRecorder) error
check := func(fns ...checkFunc) []checkFunc { return fns }
hasStatus := func(want int) checkFunc {
return func(rec *httptest.ResponseRecorder) error {
if rec.Code != want {
return fmt.Errorf("expected status %d, found %d", want, rec.Code)
}
return nil
}
}
containsContents := func(want string) checkFunc {
return func(rec *httptest.ResponseRecorder) error {
if have := rec.Body.String(); !strings.Contains(have, want) {
return fmt.Errorf("expected to find %q, in %q", want, have)
}
return nil
}
}
hasHeader := func(key, want string) checkFunc {
return func(rec *httptest.ResponseRecorder) error {
if have := rec.Result().Header.Get(key); have != want {
return fmt.Errorf("expected header %s: %q, found %q", key, want, have)
}
return nil
}
}
tests := [...]struct {
name string
h func(w http.ResponseWriter, r *http.Request)
checks []checkFunc
}{
{
"200 default",
get,
check(hasStatus(200), containsContents("DOCTYPE"), hasHeader("Content-Type", "text/html; charset=utf-8")),
},
}
r, _ := http.NewRequest("GET", "https://speed.prazefarm.co.uk/", nil)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := http.HandlerFunc(tt.h)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
for _, check := range tt.checks {
if err := check(rec); err != nil {
t.Error(err)
}
}
})
}
}