-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
humatest.go
291 lines (254 loc) · 9.09 KB
/
humatest.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
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// Package humatest provides testing utilities for Huma services. It is based on
// the standard library `http.Request` & `http.ResponseWriter` types.
package humatest
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"reflect"
"strings"
"testing/iotest"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humaflow"
"github.com/danielgtaylor/huma/v2/adapters/humaflow/flow"
)
// TB is a subset of the `testing.TB` interface used by the test API and
// implemented by the `*testing.T` and `*testing.B` structs.
type TB interface {
Helper()
Log(args ...any)
Logf(format string, args ...any)
}
// NewContext creates a new test context from an HTTP request and response.
func NewContext(op *huma.Operation, r *http.Request, w http.ResponseWriter) huma.Context {
return humaflow.NewContext(op, r, w)
}
// NewAdapter creates a new test adapter from a router.
func NewAdapter() huma.Adapter {
return humaflow.NewAdapter(flow.New())
}
// TestAPI is a `huma.API` with additional methods specifically for testing.
type TestAPI interface {
huma.API
// Do a request against the API. Args, if provided, should be string headers
// like `Content-Type: application/json`, an `io.Reader` for the request
// body, or a slice/map/struct which will be serialized to JSON and sent
// as the request body. Anything else will panic.
Do(method, path string, args ...any) *httptest.ResponseRecorder
// Get performs a GET request against the API. Args, if provided, should be
// string headers like `Content-Type: application/json`, an `io.Reader`
// for the request body, or a slice/map/struct which will be serialized to
// JSON and sent as the request body. Anything else will panic.
//
// // Make a GET request
// api.Get("/foo")
//
// // Make a GET request with a custom header.
// api.Get("/foo", "X-My-Header: my-value")
Get(path string, args ...any) *httptest.ResponseRecorder
// Post performs a POST request against the API. Args, if provided, should be
// string headers like `Content-Type: application/json`, an `io.Reader`
// for the request body, or a slice/map/struct which will be serialized to
// JSON and sent as the request body. Anything else will panic.
//
// // Make a POST request
// api.Post("/foo", bytes.NewReader(`{"foo": "bar"}`))
//
// // Make a POST request with a custom header.
// api.Post("/foo", "X-My-Header: my-value", MyBody{Foo: "bar"})
Post(path string, args ...any) *httptest.ResponseRecorder
// Put performs a PUT request against the API. Args, if provided, should be
// string headers like `Content-Type: application/json`, an `io.Reader`
// for the request body, or a slice/map/struct which will be serialized to
// JSON and sent as the request body. Anything else will panic.
//
// // Make a PUT request
// api.Put("/foo", bytes.NewReader(`{"foo": "bar"}`))
//
// // Make a PUT request with a custom header.
// api.Put("/foo", "X-My-Header: my-value", MyBody{Foo: "bar"})
Put(path string, args ...any) *httptest.ResponseRecorder
// Patch performs a PATCH request against the API. Args, if provided, should
// be string headers like `Content-Type: application/json`, an `io.Reader`
// for the request body, or a slice/map/struct which will be serialized to
// JSON and sent as the request body. Anything else will panic.
//
// // Make a PATCH request
// api.Patch("/foo", bytes.NewReader(`{"foo": "bar"}`))
//
// // Make a PATCH request with a custom header.
// api.Patch("/foo", "X-My-Header: my-value", MyBody{Foo: "bar"})
Patch(path string, args ...any) *httptest.ResponseRecorder
// Delete performs a DELETE request against the API. Args, if provided, should
// be string headers like `Content-Type: application/json`, an `io.Reader`
// for the request body, or a slice/map/struct which will be serialized to
// JSON and sent as the request body. Anything else will panic.
//
// // Make a DELETE request
// api.Delete("/foo")
//
// // Make a DELETE request with a custom header.
// api.Delete("/foo", "X-My-Header: my-value")
Delete(path string, args ...any) *httptest.ResponseRecorder
}
type testAPI struct {
huma.API
tb TB
}
func (a *testAPI) Do(method, path string, args ...any) *httptest.ResponseRecorder {
a.tb.Helper()
var b io.Reader
isJSON := false
for _, arg := range args {
kind := reflect.Indirect(reflect.ValueOf(arg)).Kind()
if reader, ok := arg.(io.Reader); ok {
b = reader
break
} else if _, ok := arg.(string); ok {
// do nothing
} else if kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice {
encoded, err := json.Marshal(arg)
if err != nil {
panic(err)
}
b = bytes.NewReader(encoded)
isJSON = true
} else {
panic("unsupported argument type, expected string header or io.Reader/slice/map/struct body")
}
}
req, _ := http.NewRequest(method, path, b)
req.RequestURI = path
req.RemoteAddr = "127.0.0.1:12345"
if isJSON {
req.Header.Set("Content-Type", "application/json")
}
for _, arg := range args {
if s, ok := arg.(string); ok {
parts := strings.Split(s, ":")
req.Header.Set(parts[0], strings.TrimSpace(strings.Join(parts[1:], ":")))
if strings.ToLower(parts[0]) == "host" {
req.Host = strings.TrimSpace(parts[1])
}
}
}
resp := httptest.NewRecorder()
bytes, _ := DumpRequest(req)
a.tb.Log("Making request:\n" + strings.TrimSpace(string(bytes)))
a.Adapter().ServeHTTP(resp, req)
bytes, _ = DumpResponse(resp.Result())
a.tb.Log("Got response:\n" + strings.TrimSpace(string(bytes)))
return resp
}
func (a *testAPI) Get(path string, args ...any) *httptest.ResponseRecorder {
a.tb.Helper()
return a.Do(http.MethodGet, path, args...)
}
func (a *testAPI) Post(path string, args ...any) *httptest.ResponseRecorder {
a.tb.Helper()
return a.Do(http.MethodPost, path, args...)
}
func (a *testAPI) Put(path string, args ...any) *httptest.ResponseRecorder {
a.tb.Helper()
return a.Do(http.MethodPut, path, args...)
}
func (a *testAPI) Patch(path string, args ...any) *httptest.ResponseRecorder {
a.tb.Helper()
return a.Do(http.MethodPatch, path, args...)
}
func (a *testAPI) Delete(path string, args ...any) *httptest.ResponseRecorder {
a.tb.Helper()
return a.Do(http.MethodDelete, path, args...)
}
// Wrap returns a `TestAPI` wrapping the given API.
func Wrap(tb TB, api huma.API) TestAPI {
return &testAPI{api, tb}
}
// New creates a new router and test API, making it easy to register operations
// and perform requests against them. Optionally takes a configuration object
// to customize how the API is created. If no configuration is provided then
// a simple default configuration supporting `application/json` is used.
func New(tb TB, configs ...huma.Config) (http.Handler, TestAPI) {
for _, config := range configs {
if config.OpenAPI == nil {
panic("custom huma.Config structs must specify a value for OpenAPI")
}
}
if len(configs) == 0 {
configs = append(configs, huma.Config{
OpenAPI: &huma.OpenAPI{
Info: &huma.Info{
Title: "Test API",
Version: "1.0.0",
},
},
Formats: map[string]huma.Format{
"application/json": huma.DefaultJSONFormat,
"json": huma.DefaultJSONFormat,
},
DefaultFormat: "application/json",
})
}
r := flow.New()
return r, Wrap(tb, humaflow.New(r, configs[0]))
}
func dumpBody(body io.ReadCloser, buf *bytes.Buffer) (io.ReadCloser, error) {
if body == nil {
return nil, nil
}
b, err := io.ReadAll(body)
if err != nil {
return io.NopCloser(iotest.ErrReader(err)), err
}
body.Close()
if strings.Contains(buf.String(), "json") {
json.Indent(buf, b, "", " ")
} else {
buf.Write(b)
}
return io.NopCloser(bytes.NewReader(b)), nil
}
// DumpRequest returns a string representation of an HTTP request, automatically
// pretty printing JSON bodies for readability.
func DumpRequest(req *http.Request) ([]byte, error) {
var buf bytes.Buffer
b, err := httputil.DumpRequest(req, false)
if err == nil {
buf.Write(b)
req.Body, err = dumpBody(req.Body, &buf)
}
return buf.Bytes(), err
}
// DumpResponse returns a string representation of an HTTP response,
// automatically pretty printing JSON bodies for readability.
func DumpResponse(resp *http.Response) ([]byte, error) {
var buf bytes.Buffer
b, err := httputil.DumpResponse(resp, false)
if err == nil {
buf.Write(b)
resp.Body, err = dumpBody(resp.Body, &buf)
}
return buf.Bytes(), err
}
// PrintRequest prints a string representation of an HTTP request to stdout,
// automatically pretty printing JSON bodies for readability.
func PrintRequest(req *http.Request) {
b, _ := DumpRequest(req)
// Turn `/r/n` into `/n` for more straightforward output that is also
// compatible with Go's testable examples.
b = bytes.ReplaceAll(b, []byte("\r"), []byte(""))
fmt.Println(string(b))
}
// PrintResponse prints a string representation of an HTTP response to stdout,
// automatically pretty printing JSON bodies for readability.
func PrintResponse(resp *http.Response) {
b, _ := DumpResponse(resp)
// Turn `/r/n` into `/n` for more straightforward output that is also
// compatible with Go's testable examples.
b = bytes.ReplaceAll(b, []byte("\r"), []byte(""))
fmt.Println(string(b))
}