Repository navigation
Expand file tree
/
Copy pathrequest_test_helpers_test.go
More file actions
182 lines (162 loc) · 5.28 KB
/
Copy pathrequest_test_helpers_test.go
File metadata and controls
182 lines (162 loc) · 5.28 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package httpserver
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/rs/zerolog"
)
// This file contains shared test infrastructure (request builders, setters, and
// capture helpers) used across the parser test files.
// multipartReader is a type alias used by multiple test files.
type multipartReader = multipart.Reader
type capturedRequest[T any] struct {
ctx *Context
request T
}
// captureHandler is a RequestHandler that returns http.StatusOK. When used with
// doRequest, the request is captured automatically by doRequest's wrapper.
func captureHandler[T any](ctx *Context, _ T) {
ctx.NewResponse(http.StatusOK)
}
type RequestSetter func(*http.Request)
// asTestHTTPHandler adapts a [Handler] into an [http.HandlerFunc] for the
// narrow parser/response unit tests that need to exercise [Context] lifecycle
// without involving [Router.Handle]. It is NOT equivalent coverage for
// [Router.Handle] — see [newTestRouter] / [doRouterRequest] for that.
func asTestHTTPHandler(handler Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := &Context{request: r, writer: w}
handler(ctx)
ctx.writeResponse(r.Context())
}
}
func doRequest[T any](t *testing.T, handler RequestHandler[T], method, target string, setters ...RequestSetter) (*capturedRequest[T], *httptest.ResponseRecorder) {
t.Helper()
req, err := http.NewRequest(method, target, nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
for _, setter := range setters {
setter(req)
}
captured := &capturedRequest[T]{}
wrappedHandler := asTestHTTPHandler(RequestParser(func(ctx *Context, req T) {
captured.ctx = ctx
captured.request = req
handler(ctx, req)
}))
rec := httptest.NewRecorder()
wrappedHandler.ServeHTTP(rec, req)
return captured, rec
}
func doServeMuxRequest[T any](t *testing.T, method, pattern, target string, handler RequestHandler[T], setters ...RequestSetter) (*capturedRequest[T], *httptest.ResponseRecorder) {
t.Helper()
req, err := http.NewRequest(method, target, nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
for _, setter := range setters {
setter(req)
}
captured := &capturedRequest[T]{}
mux := http.NewServeMux()
mux.Handle(method+" "+pattern, asTestHTTPHandler(RequestParser(func(ctx *Context, req T) {
captured.ctx = ctx
captured.request = req
handler(ctx, req)
})))
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
return captured, rec
}
func withHeader(key, value string) RequestSetter {
return func(req *http.Request) {
req.Header.Set(key, value)
}
}
func withCookie(name, value string) RequestSetter {
return func(req *http.Request) {
req.AddCookie(&http.Cookie{Name: name, Value: value})
}
}
func withQuery(query string) RequestSetter {
return func(req *http.Request) {
req.URL.RawQuery = query
}
}
func withJSONBody(body any) RequestSetter {
return func(req *http.Request) {
data, err := json.Marshal(body)
if err != nil {
panic(err)
}
buf := bytes.NewBuffer(data)
req.Body = io.NopCloser(buf)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.ContentLength = int64(buf.Len())
}
}
func withFormBody(values url.Values) RequestSetter {
return func(req *http.Request) {
body := values.Encode()
req.Body = io.NopCloser(strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.ContentLength = int64(len(body))
}
}
func withRawBody(contentType string, data []byte) RequestSetter {
return func(req *http.Request) {
req.Body = io.NopCloser(bytes.NewReader(data))
req.Header.Set("Content-Type", contentType)
req.ContentLength = int64(len(data))
}
}
func withMultipartBody(t *testing.T, buildForm func(*multipart.Writer)) RequestSetter {
t.Helper()
return func(req *http.Request) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
buildForm(writer)
if err := writer.Close(); err != nil {
t.Fatalf("failed to close multipart writer: %v", err)
}
req.Body = io.NopCloser(body)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.ContentLength = int64(body.Len())
}
}
// newTestRouter returns a [Router] backed by a fresh [http.ServeMux] and a
// disabled [zerolog.Logger]. Use [doRouterRequest] to dispatch a request
// through the real ServeMux after registering handlers via [Router.Handle] or
// [Router.Group].Handle.
func newTestRouter() Router {
serveMux := http.NewServeMux()
logger := zerolog.Nop()
return Router{serveMux: serveMux, logger: &logger}
}
// doRouterRequest dispatches method/target (after applying setters) through r's
// ServeMux and returns the recorded response. The caller must register matching
// handlers beforehand; this helper only drives the real ServeMux.
func doRouterRequest(r Router, method, target string, setters ...RequestSetter) *httptest.ResponseRecorder {
req, err := http.NewRequest(method, target, nil)
if err != nil {
panic(err)
}
for _, setter := range setters {
setter(req)
}
rec := httptest.NewRecorder()
r.serveMux.ServeHTTP(rec, req)
return rec
}