-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_suite_test.go
More file actions
103 lines (82 loc) · 2.11 KB
/
Copy pathtest_suite_test.go
File metadata and controls
103 lines (82 loc) · 2.11 KB
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 basicauth
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"net/http/httptest"
"testing"
)
// a simple test suite written specifically for the basicauth middleware.
type testie struct {
t *testing.T
resp *http.Response
}
func (te *testie) fatal(err error) {
msg := fmt.Sprintf("[%s] %v", te.resp.Request.URL.String(), err)
if id := te.resp.Request.Header.Get("X-Request-Id"); id != "" {
msg = fmt.Sprintf("[%s] %s", id, msg)
}
te.t.Fatal(msg)
}
func (te *testie) fatalf(format string, args ...any) {
te.fatal(fmt.Errorf(format, args...))
}
func (te *testie) statusCode(expected int) *testie {
if got := te.resp.StatusCode; expected != got {
te.fatalf("expected status code: %d but got: %d", expected, got)
}
return te
}
func (te *testie) jsonEq(v any) *testie {
media, _, err := mime.ParseMediaType(te.resp.Header.Get("Content-Type"))
if err != nil {
te.fatal(err)
}
if media != "application/json" {
te.fatalf("expected to be a json response but got: %q", media)
}
expected, err := json.Marshal(v)
if err != nil {
te.fatal(err)
}
got, err := io.ReadAll(te.resp.Body)
_ = te.resp.Body.Close()
if err != nil {
te.fatal(err)
}
got = bytes.TrimSuffix(got, []byte("\n"))
if !bytes.EqualFold(expected, got) {
te.fatalf("expected to receive:\n'%s'\nbut got:\n'%s'", string(expected), string(got))
}
return te
}
func testHandler(t *testing.T, handler http.Handler, method, url string, reqOpts ...requestOption) *testie {
t.Helper()
w := httptest.NewRecorder()
req := httptest.NewRequest(method, url, nil)
for _, opt := range reqOpts {
if err := opt(req); err != nil {
t.Fatal(err)
}
}
handler.ServeHTTP(w, req)
resp := w.Result()
resp.Request = req
return &testie{t: t, resp: resp}
}
type requestOption func(*http.Request) error
func withBasicAuth(username, password string) requestOption {
return func(r *http.Request) error {
r.SetBasicAuth(username, password)
return nil
}
}
func withRequestID(id any) requestOption { // useful for logging.
return func(r *http.Request) error {
r.Header.Set("X-Request-Id", fmt.Sprintf("%v", id))
return nil
}
}