forked from danielgtaylor/huma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolver_test.go
362 lines (297 loc) · 9.52 KB
/
resolver_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
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package huma
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestExhaustiveErrors(t *testing.T) {
type Input struct {
BoolParam bool `query:"bool"`
IntParam int `query:"int"`
Float32Param float32 `query:"float32"`
Float64Param float64 `query:"float64"`
Tags []int `query:"tags"`
Time time.Time `query:"time"`
Body struct {
Test int `json:"test" minimum:"5"`
}
}
app := newTestRouter()
app.Resource("/").Get("test", "Test").Run(func(ctx Context, input Input) {
// Do nothing
})
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/?bool=bad&int=bad&float32=bad&float64=bad&tags=1,2,bad&time=bad", strings.NewReader(`{"test": 1}`))
r.Host = "example.com"
app.ServeHTTP(w, r)
assert.JSONEq(t, `{"$schema": "https://example.com/schemas/ErrorModel.json", "title":"Unprocessable Entity","status":422,"detail":"Error while processing input parameters","errors":[{"message":"cannot parse boolean","location":"query.bool","value":"bad"},{"message":"cannot parse integer","location":"query.int","value":"bad"},{"message":"cannot parse float","location":"query.float32","value":"bad"},{"message":"cannot parse float","location":"query.float64","value":"bad"},{"message":"cannot parse integer","location":"query[2].tags","value":"bad"},{"message":"unable to validate against schema: invalid character 'b' looking for beginning of value","location":"query.tags","value":"[1,2,bad]"},{"message":"cannot parse time","location":"query.time","value":"bad"},{"message":"Must be greater than or equal to 5","location":"body.test","value":1}]}`, w.Body.String())
}
type Dep1 struct {
// Only *one* of the following two may be set.
One string `json:"one,omitempty"`
Two string `json:"two,omitempty"`
}
func (d *Dep1) Resolve(ctx Context, r *http.Request) {
if d.One != "" && d.Two != "" {
ctx.AddError(&ErrorDetail{
Message: "Only one of ['one', 'two'] is allowed.",
Location: "one",
Value: d.One,
})
}
}
type Dep2 struct {
// Test recursive resolver with complex input structure containing a map of
// lists of struct pointers.
Foo map[string][]*Dep1 `json:"foo"`
}
func TestNestedResolver(t *testing.T) {
app := newTestRouter()
app.Resource("/").Post("test", "Test",
NewResponse(http.StatusNoContent, "desc"),
).Run(func(ctx Context, input struct {
Body Dep2
}) {
ctx.WriteHeader(http.StatusNoContent)
})
// Test happy case just sending ONE of the two possible fields in each struct.
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodPost, "/", strings.NewReader(`{
"foo": {
"a": [{"one": "1"}],
"b": [{"two": "2"}]
}
}`))
app.ServeHTTP(w, r)
assert.Equal(t, http.StatusNoContent, w.Result().StatusCode)
}
func TestNestedResolverError(t *testing.T) {
app := newTestRouter()
app.Resource("/").Post("test", "Test",
NewResponse(http.StatusNoContent, "desc"),
).Run(func(ctx Context, input struct {
Body Dep2
}) {
ctx.WriteHeader(http.StatusNoContent)
})
// Test error case where we send BOTH fields in the same struct, which is
// not allowed. Should get a validation error response generated by the
// `Dep1.Resolve(...)` method above.
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodPost, "/", strings.NewReader(`{
"foo": {
"a": [
{"one": "1", "two": "2"}
]
}
}`))
r.Host = "example.com"
app.ServeHTTP(w, r)
assert.JSONEq(t, `{
"$schema": "https://example.com/schemas/ErrorModel.json",
"status": 422,
"title": "Unprocessable Entity",
"detail": "Error while processing input parameters",
"errors": [
{
"message": "Only one of ['one', 'two'] is allowed.",
"location": "body.foo.a[0].one",
"value": "1"
}
]
}`, w.Body.String())
}
func TestInvalidJSON(t *testing.T) {
app := newTestRouter()
app.Resource("/").Post("test", "Test",
NewResponse(http.StatusNoContent, "desc"),
).Run(func(ctx Context, input struct {
Body string
}) {
ctx.WriteHeader(http.StatusNoContent)
})
// Test happy case just sending ONE of the two possible fields in each struct.
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodPost, "/", strings.NewReader(`{.2asdf2`))
app.ServeHTTP(w, r)
assert.Equal(t, http.StatusBadRequest, w.Result().StatusCode)
}
type QueryParamTestModel struct {
BooleanParam bool `query:"b"`
OtherParam string `query:"s"`
}
func TestBooleanQueryParamNoVal(t *testing.T) {
app := newTestRouter()
app.Resource("/").Get("test", "Test",
NewResponse(http.StatusOK, "desc"),
).Run(func(ctx Context, input QueryParamTestModel) {
out := &QueryParamTestModel{
BooleanParam: input.BooleanParam,
OtherParam: input.OtherParam,
}
j, err := json.Marshal(out)
if err == nil {
ctx.Write(j)
} else {
ctx.WriteError(http.StatusBadRequest, "error marshaling to json", err)
}
})
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/?s=test&b", nil)
app.ServeHTTP(w, r)
assert.Equal(t, http.StatusOK, w.Result().StatusCode)
decoder := json.NewDecoder(w.Body)
var o QueryParamTestModel
err := decoder.Decode(&o)
if err != nil {
assert.Fail(t, "Unable to decode json response")
}
assert.Equal(t, o.BooleanParam, true)
assert.Equal(t, o.OtherParam, "test")
}
func TestBooleanQueryParamTrailingEqual(t *testing.T) {
app := newTestRouter()
app.Resource("/").Get("test", "Test",
NewResponse(http.StatusOK, "desc"),
).Run(func(ctx Context, input QueryParamTestModel) {
out := &QueryParamTestModel{
BooleanParam: input.BooleanParam,
OtherParam: input.OtherParam,
}
j, err := json.Marshal(out)
if err == nil {
ctx.Write(j)
} else {
ctx.WriteError(http.StatusBadRequest, "error marshaling to json", err)
}
})
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/?s=test&b=", nil)
app.ServeHTTP(w, r)
assert.Equal(t, http.StatusOK, w.Result().StatusCode)
decoder := json.NewDecoder(w.Body)
var o QueryParamTestModel
err := decoder.Decode(&o)
if err != nil {
assert.Fail(t, "Unable to decode json response")
}
assert.Equal(t, o.BooleanParam, true)
assert.Equal(t, o.OtherParam, "test")
}
func TestBooleanQueryParamExplicitSet(t *testing.T) {
app := newTestRouter()
app.Resource("/").Get("test", "Test",
NewResponse(http.StatusOK, "desc"),
).Run(func(ctx Context, input QueryParamTestModel) {
out := &QueryParamTestModel{
BooleanParam: input.BooleanParam,
OtherParam: input.OtherParam,
}
j, err := json.Marshal(out)
if err == nil {
ctx.Write(j)
} else {
ctx.WriteError(http.StatusBadRequest, "error marshaling to json", err)
}
})
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/?s=test&b=true", nil)
app.ServeHTTP(w, r)
assert.Equal(t, http.StatusOK, w.Result().StatusCode)
decoder := json.NewDecoder(w.Body)
var o QueryParamTestModel
err := decoder.Decode(&o)
if err != nil {
assert.Fail(t, "Unable to decode json response")
}
assert.Equal(t, o.BooleanParam, true)
assert.Equal(t, o.OtherParam, "test")
}
func TestBooleanQueryParamNotSet(t *testing.T) {
app := newTestRouter()
app.Resource("/").Get("test", "Test",
NewResponse(http.StatusOK, "desc"),
).Run(func(ctx Context, input QueryParamTestModel) {
out := &QueryParamTestModel{
BooleanParam: input.BooleanParam,
OtherParam: input.OtherParam,
}
j, err := json.Marshal(out)
if err == nil {
ctx.Write(j)
} else {
ctx.WriteError(http.StatusBadRequest, "error marshaling to json", err)
}
})
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/?s=test", nil)
app.ServeHTTP(w, r)
assert.Equal(t, http.StatusOK, w.Result().StatusCode)
decoder := json.NewDecoder(w.Body)
var o QueryParamTestModel
err := decoder.Decode(&o)
if err != nil {
assert.Fail(t, "Unable to decode json response")
}
assert.Equal(t, o.BooleanParam, false)
assert.Equal(t, o.OtherParam, "test")
}
func TestStringQueryEmpty(t *testing.T) {
app := newTestRouter()
app.Resource("/").Get("test", "Test",
NewResponse(http.StatusOK, "desc"),
).Run(func(ctx Context, input QueryParamTestModel) {
out := &QueryParamTestModel{
BooleanParam: input.BooleanParam,
OtherParam: input.OtherParam,
}
j, err := json.Marshal(out)
if err == nil {
ctx.Write(j)
} else {
ctx.WriteError(http.StatusBadRequest, "error marshaling to json", err)
}
})
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/?s=&b", nil)
app.ServeHTTP(w, r)
assert.Equal(t, http.StatusOK, w.Result().StatusCode)
decoder := json.NewDecoder(w.Body)
var o QueryParamTestModel
err := decoder.Decode(&o)
if err != nil {
assert.Fail(t, "Unable to decode json response")
}
assert.Equal(t, o.BooleanParam, true)
assert.Equal(t, o.OtherParam, "")
}
func TestRawBody(t *testing.T) {
app := newTestRouter()
app.Resource("/").Get("test", "Test",
NewResponse(http.StatusOK, "desc"),
).Run(func(ctx Context, input struct {
Body struct {
Name string `json:"name"`
Tags []string `json:"tags"`
}
RawBody []byte
}) {
ctx.Write(input.RawBody)
})
// Note the weird formatting
body := `{ "name" : "Huma","tags": [ "one" ,"two"]}`
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/", strings.NewReader(body))
app.ServeHTTP(w, r)
assert.Equal(t, http.StatusOK, w.Result().StatusCode)
assert.Equal(t, body, w.Body.String())
// Invalid input should still fail validation!
w = httptest.NewRecorder()
r, _ = http.NewRequest(http.MethodGet, "/", strings.NewReader("{}"))
app.ServeHTTP(w, r)
assert.Equal(t, http.StatusUnprocessableEntity, w.Result().StatusCode)
}