forked from getkin/kin-openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation_error_test.go
706 lines (642 loc) · 24.3 KB
/
validation_error_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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
package openapi3filter
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/routers"
)
func newPetstoreRequest(t *testing.T, method, path string, body io.Reader) *http.Request {
host := "petstore.swagger.io"
pathPrefix := "v2"
r, err := http.NewRequest(method, fmt.Sprintf("http://%s/%s%s", host, pathPrefix, path), body)
require.NoError(t, err)
r.Header.Set(headerCT, "application/json")
r.Header.Set("Authorization", "Bearer magicstring")
r.Host = host
return r
}
type validationFields struct {
Handler http.Handler
File string
ErrorEncoder ErrorEncoder
}
type validationArgs struct {
r *http.Request
}
type validationTest struct {
name string
fields validationFields
args validationArgs
wantErr bool
wantErrBody string
wantErrReason string
wantErrSchemaReason string
wantErrSchemaPath string
wantErrSchemaValue interface{}
wantErrSchemaOriginReason string
wantErrSchemaOriginPath string
wantErrSchemaOriginValue interface{}
wantErrParam string
wantErrParamIn string
wantErrParseKind ParseErrorKind
wantErrParseValue interface{}
wantErrParseReason string
wantErrResponse *ValidationError
}
func getValidationTests(t *testing.T) []*validationTest {
badHost, err := http.NewRequest(http.MethodGet, "http://unknown-host.com/v2/pet", nil)
require.NoError(t, err)
badPath := newPetstoreRequest(t, http.MethodGet, "/watdis", nil)
badMethod := newPetstoreRequest(t, http.MethodTrace, "/pet", nil)
missingBody1 := newPetstoreRequest(t, http.MethodPost, "/pet", nil)
missingBody2 := newPetstoreRequest(t, http.MethodPost, "/pet", bytes.NewBufferString(``))
noContentType := newPetstoreRequest(t, http.MethodPost, "/pet", bytes.NewBufferString(`{}`))
noContentType.Header.Del(headerCT)
noContentTypeNeeded := newPetstoreRequest(t, http.MethodGet, "/pet/findByStatus?status=sold", nil)
noContentTypeNeeded.Header.Del(headerCT)
unknownContentType := newPetstoreRequest(t, http.MethodPost, "/pet", bytes.NewBufferString(`{}`))
unknownContentType.Header.Set(headerCT, "application/xml")
unsupportedContentType := newPetstoreRequest(t, http.MethodPost, "/pet", bytes.NewBufferString(`{}`))
unsupportedContentType.Header.Set(headerCT, "text/plain")
unsupportedHeaderValue := newPetstoreRequest(t, http.MethodPost, "/pet", bytes.NewBufferString(`{}`))
unsupportedHeaderValue.Header.Set("x-environment", "watdis")
return []*validationTest{
//
// Basics
//
{
name: "error - unknown host",
args: validationArgs{
r: badHost,
},
wantErrReason: routers.ErrPathNotFound.Error(),
wantErrResponse: &ValidationError{Status: http.StatusNotFound, Title: routers.ErrPathNotFound.Error()},
},
{
name: "error - unknown path",
args: validationArgs{
r: badPath,
},
wantErrReason: routers.ErrPathNotFound.Error(),
wantErrResponse: &ValidationError{Status: http.StatusNotFound, Title: routers.ErrPathNotFound.Error()},
},
{
name: "error - unknown method",
args: validationArgs{
r: badMethod,
},
wantErrReason: routers.ErrMethodNotAllowed.Error(),
// TODO: By HTTP spec, this should have an Allow header with what is allowed
// but kin-openapi doesn't provide us the requested method or path, so impossible to provide details
wantErrResponse: &ValidationError{Status: http.StatusMethodNotAllowed,
Title: routers.ErrMethodNotAllowed.Error()},
},
{
name: "error - missing body on POST",
args: validationArgs{
r: missingBody1,
},
wantErrBody: "request body has an error: " + ErrInvalidRequired.Error(),
wantErrResponse: &ValidationError{Status: http.StatusBadRequest,
Title: "request body has an error: " + ErrInvalidRequired.Error()},
},
{
name: "error - empty body on POST",
args: validationArgs{
r: missingBody2,
},
wantErrBody: "request body has an error: " + ErrInvalidRequired.Error(),
wantErrResponse: &ValidationError{Status: http.StatusBadRequest,
Title: "request body has an error: " + ErrInvalidRequired.Error()},
},
//
// Content-Type
//
{
name: "error - missing content-type on POST",
args: validationArgs{
r: noContentType,
},
wantErrReason: prefixInvalidCT + ` ""`,
wantErrResponse: &ValidationError{Status: http.StatusUnsupportedMediaType,
Title: "header Content-Type is required"},
},
{
name: "error - unknown content-type on POST",
args: validationArgs{
r: unknownContentType,
},
wantErrReason: "failed to decode request body",
wantErrParseKind: KindUnsupportedFormat,
wantErrParseReason: prefixUnsupportedCT + ` "application/xml"`,
wantErrResponse: &ValidationError{Status: http.StatusUnsupportedMediaType,
Title: prefixUnsupportedCT + ` "application/xml"`},
},
{
name: "error - unsupported content-type on POST",
args: validationArgs{
r: unsupportedContentType,
},
wantErrReason: prefixInvalidCT + ` "text/plain"`,
wantErrResponse: &ValidationError{Status: http.StatusUnsupportedMediaType,
Title: prefixUnsupportedCT + ` "text/plain"`},
},
{
name: "success - no content-type header required on GET",
args: validationArgs{
r: noContentTypeNeeded,
},
},
//
// Query strings
//
{
name: "error - missing required query string parameter",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/findByStatus", nil),
},
wantErrParam: "status",
wantErrParamIn: "query",
wantErrBody: `parameter "status" in query has an error: value is required but missing`,
wantErrReason: "value is required but missing",
wantErrResponse: &ValidationError{Status: http.StatusBadRequest,
Title: `parameter "status" in query is required`},
},
{
name: "error - wrong query string parameter type as integer",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/findByIds?ids=1,notAnInt", nil),
},
wantErrParam: "ids",
wantErrParamIn: "query",
// This is a nested ParseError. The outer error is a KindOther with no details.
// So we'd need to look at the inner one which is a KindInvalidFormat. So just check the error body.
wantErrBody: `parameter "ids" in query has an error: path 1: value notAnInt: an invalid integer: invalid syntax`,
// TODO: Should we treat query params of the wrong type like a 404 instead of a 400?
wantErrResponse: &ValidationError{Status: http.StatusBadRequest,
Title: `parameter "ids" in query is invalid: notAnInt is an invalid integer`},
},
{
name: "success - ignores unknown query string parameter",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/findByStatus?status=available&wat=isdis", nil),
},
},
{
name: "error - non required query string has empty value",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pets/?tags=", nil),
},
wantErrParam: "tags",
wantErrParamIn: "query",
wantErrBody: `parameter "tags" in query has an error: empty value is not allowed`,
wantErrReason: "empty value is not allowed",
wantErrResponse: &ValidationError{Status: http.StatusBadRequest,
Title: `parameter "tags" in query is not allowed to be empty`},
},
{
name: "success - non required query string has empty value, but has AllowEmptyValue",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pets/?status=", nil),
},
},
{
name: "success - normal case, query strings",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/findByStatus?status=available", nil),
},
},
{
name: "success - normal case, query strings, array",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/findByStatus?status=available&status=sold", nil),
},
},
{
name: "error - invalid query string array serialization",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/findByStatus?status=available,sold", nil),
},
wantErrParam: "status",
wantErrParamIn: "query",
wantErrSchemaReason: "value \"available,sold\" is not one of the allowed values",
wantErrSchemaPath: "/0",
wantErrSchemaValue: "available,sold",
wantErrResponse: &ValidationError{Status: http.StatusBadRequest,
Title: "value \"available,sold\" is not one of the allowed values",
Detail: "value available,sold at /0 must be one of: available, pending, sold; " +
// TODO: do we really want to use this heuristic to guess
// that they're using the wrong serialization?
"perhaps you intended '?status=available&status=sold'",
Source: &ValidationErrorSource{Parameter: "status"}},
},
{
name: "error - invalid enum value for query string parameter",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/findByStatus?status=sold&status=watdis", nil),
},
wantErrParam: "status",
wantErrParamIn: "query",
wantErrSchemaReason: "value \"watdis\" is not one of the allowed values",
wantErrSchemaPath: "/1",
wantErrSchemaValue: "watdis",
wantErrResponse: &ValidationError{Status: http.StatusBadRequest,
Title: "value \"watdis\" is not one of the allowed values",
Detail: "value watdis at /1 must be one of: available, pending, sold",
Source: &ValidationErrorSource{Parameter: "status"}},
},
{
name: "error - invalid enum value, allowing commas (without 'perhaps you intended' recommendation)",
args: validationArgs{
// fish,with,commas isn't an enum value
r: newPetstoreRequest(t, http.MethodGet, "/pet/findByKind?kind=dog|fish,with,commas", nil),
},
wantErrParam: "kind",
wantErrParamIn: "query",
wantErrSchemaReason: "value \"fish,with,commas\" is not one of the allowed values",
wantErrSchemaPath: "/1",
wantErrSchemaValue: "fish,with,commas",
wantErrResponse: &ValidationError{Status: http.StatusBadRequest,
Title: "value \"fish,with,commas\" is not one of the allowed values",
Detail: "value fish,with,commas at /1 must be one of: dog, cat, turtle, bird,with,commas",
// No 'perhaps you intended' because its the right serialization format
Source: &ValidationErrorSource{Parameter: "kind"}},
},
{
name: "success - valid enum value, allowing commas",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/findByKind?kind=dog|bird,with,commas", nil),
},
},
//
// Request header params
//
{
name: "error - invalid enum value for header string parameter",
args: validationArgs{
r: unsupportedHeaderValue,
},
wantErrParam: "x-environment",
wantErrParamIn: "header",
wantErrSchemaReason: "value \"watdis\" is not one of the allowed values",
wantErrSchemaPath: "/",
wantErrSchemaValue: "watdis",
wantErrResponse: &ValidationError{Status: http.StatusBadRequest,
Title: "value \"watdis\" is not one of the allowed values",
Detail: "value watdis at / must be one of: demo, prod",
Source: &ValidationErrorSource{Parameter: "x-environment"}},
},
//
// Request bodies
//
{
name: "error - invalid enum value for header object attribute",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodPost, "/pet", bytes.NewBufferString(`{"status":"watdis"}`)),
},
wantErrReason: "doesn't match the schema",
wantErrSchemaReason: "value \"watdis\" is not one of the allowed values",
wantErrSchemaValue: "watdis",
wantErrSchemaPath: "/status",
wantErrResponse: &ValidationError{Status: http.StatusUnprocessableEntity,
Title: "value \"watdis\" is not one of the allowed values",
Detail: "value watdis at /status must be one of: available, pending, sold",
Source: &ValidationErrorSource{Pointer: "/status"}},
},
{
name: "error - missing required object attribute",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodPost, "/pet", bytes.NewBufferString(`{"name":"Bahama"}`)),
},
wantErrReason: "doesn't match the schema",
wantErrSchemaReason: `property "photoUrls" is missing`,
wantErrSchemaValue: map[string]string{"name": "Bahama"},
wantErrSchemaPath: "/photoUrls",
wantErrResponse: &ValidationError{Status: http.StatusUnprocessableEntity,
Title: `property "photoUrls" is missing`,
Source: &ValidationErrorSource{Pointer: "/photoUrls"}},
},
{
name: "error - missing required nested object attribute",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodPost, "/pet",
bytes.NewBufferString(`{"name":"Bahama","photoUrls":[],"category":{}}`)),
},
wantErrReason: "doesn't match the schema",
wantErrSchemaReason: `property "name" is missing`,
wantErrSchemaValue: map[string]string{},
wantErrSchemaPath: "/category/name",
wantErrResponse: &ValidationError{Status: http.StatusUnprocessableEntity,
Title: `property "name" is missing`,
Source: &ValidationErrorSource{Pointer: "/category/name"}},
},
{
name: "error - missing required deeply nested object attribute",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodPost, "/pet",
bytes.NewBufferString(`{"name":"Bahama","photoUrls":[],"category":{"tags": [{}]}}`)),
},
wantErrReason: "doesn't match the schema",
wantErrSchemaReason: `property "name" is missing`,
wantErrSchemaValue: map[string]string{},
wantErrSchemaPath: "/category/tags/0/name",
wantErrResponse: &ValidationError{Status: http.StatusUnprocessableEntity,
Title: `property "name" is missing`,
Source: &ValidationErrorSource{Pointer: "/category/tags/0/name"}},
},
{
name: "error - wrong attribute type",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodPost, "/pet",
bytes.NewBufferString(`{"name":"Bahama","photoUrls":"http://cat"}`)),
},
wantErrReason: "doesn't match the schema",
wantErrSchemaReason: "field must be set to array or not be present",
wantErrSchemaPath: "/photoUrls",
wantErrSchemaValue: "string",
// TODO: this shouldn't say "or not be present", but this requires recursively resolving
// innerErr.JSONPointer() against e.RequestBody.Content["application/json"].Schema.Value (.Required, .Properties)
wantErrResponse: &ValidationError{Status: http.StatusUnprocessableEntity,
Title: "field must be set to array or not be present",
Source: &ValidationErrorSource{Pointer: "/photoUrls"}},
},
{
name: "error - missing required object attribute from allOf required overlay",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodPost, "/pet2", bytes.NewBufferString(`{"name":"Bahama"}`)),
},
wantErrReason: "doesn't match the schema",
wantErrSchemaPath: "/",
wantErrSchemaValue: map[string]string{"name": "Bahama"},
wantErrSchemaOriginReason: `property "photoUrls" is missing`,
wantErrSchemaOriginValue: map[string]string{"name": "Bahama"},
wantErrSchemaOriginPath: "/photoUrls",
wantErrResponse: &ValidationError{Status: http.StatusUnprocessableEntity,
Title: `property "photoUrls" is missing`,
Source: &ValidationErrorSource{Pointer: "/photoUrls"}},
},
{
name: "success - ignores unknown object attribute",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodPost, "/pet",
bytes.NewBufferString(`{"wat":"isdis","name":"Bahama","photoUrls":[]}`)),
},
},
{
name: "success - normal case, POST",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodPost, "/pet",
bytes.NewBufferString(`{"name":"Bahama","photoUrls":[]}`)),
},
},
{
name: "success - required properties are not required on PATCH if required overlaid using allOf elsewhere",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodPatch, "/pet", bytes.NewBufferString(`{}`)),
},
},
//
// Path params
//
{
name: "error - missing path param",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/", nil),
},
wantErrParam: "petId",
wantErrParamIn: "path",
wantErrBody: `parameter "petId" in path has an error: value is required but missing`,
wantErrReason: "value is required but missing",
wantErrResponse: &ValidationError{Status: http.StatusBadRequest,
Title: `parameter "petId" in path is required`},
},
{
name: "error - wrong path param type",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/NotAnInt", nil),
},
wantErrParam: "petId",
wantErrParamIn: "path",
wantErrParseKind: KindInvalidFormat,
wantErrParseValue: "NotAnInt",
wantErrParseReason: "an invalid integer",
wantErrResponse: &ValidationError{Status: http.StatusNotFound,
Title: `resource not found with "petId" value: NotAnInt`},
},
{
name: "success - normal case, with path params",
args: validationArgs{
r: newPetstoreRequest(t, http.MethodGet, "/pet/23", nil),
},
},
}
}
func TestValidationHandler_validateRequest(t *testing.T) {
tests := getValidationTests(t)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := require.New(t)
h, err := buildValidationHandler(tt)
req.NoError(err)
err = h.validateRequest(tt.args.r)
req.Equal(tt.wantErr, err != nil)
if err != nil {
if tt.wantErrBody != "" {
req.Equal(tt.wantErrBody, err.Error())
}
if e, ok := err.(*routers.RouteError); ok {
req.Equal(tt.wantErrReason, e.Error())
return
}
e, ok := err.(*RequestError)
req.True(ok, "not a RequestError: %T -- %#v", err, err)
req.Equal(tt.wantErrReason, e.Reason)
if e.Parameter != nil {
req.Equal(tt.wantErrParam, e.Parameter.Name)
req.Equal(tt.wantErrParamIn, e.Parameter.In)
} else {
req.False(tt.wantErrParam != "" || tt.wantErrParamIn != "",
"error = %v, no Parameter -- %#v", e, e)
}
if innerErr, ok := e.Err.(*openapi3.SchemaError); ok {
req.Equal(tt.wantErrSchemaReason, innerErr.Reason)
pointer := toJSONPointer(innerErr.JSONPointer())
req.Equal(tt.wantErrSchemaPath, pointer)
req.Equal(fmt.Sprintf("%v", tt.wantErrSchemaValue), fmt.Sprintf("%v", innerErr.Value))
if originErr, ok := innerErr.Origin.(*openapi3.SchemaError); ok {
req.Equal(tt.wantErrSchemaOriginReason, originErr.Reason)
pointer := toJSONPointer(originErr.JSONPointer())
req.Equal(tt.wantErrSchemaOriginPath, pointer)
req.Equal(fmt.Sprintf("%v", tt.wantErrSchemaOriginValue), fmt.Sprintf("%v", originErr.Value))
}
} else {
req.False(tt.wantErrSchemaReason != "" || tt.wantErrSchemaPath != "",
"error = %v, not a SchemaError -- %#v", e.Err, e.Err)
req.False(tt.wantErrSchemaOriginReason != "" || tt.wantErrSchemaOriginPath != "",
"error = %v, not a SchemaError with Origin -- %#v", e.Err, e.Err)
}
if innerErr, ok := e.Err.(*ParseError); ok {
req.Equal(tt.wantErrParseKind, innerErr.Kind)
req.Equal(tt.wantErrParseValue, innerErr.Value)
req.Equal(tt.wantErrParseReason, innerErr.Reason)
} else {
req.False(tt.wantErrParseValue != nil || tt.wantErrParseReason != "",
"error = %v, not a ParseError -- %#v", e.Err, e.Err)
}
}
})
}
}
func TestValidationErrorEncoder(t *testing.T) {
tests := getValidationTests(t)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockEncoder := &mockErrorEncoder{}
encoder := &ValidationErrorEncoder{Encoder: mockEncoder.Encode}
req := require.New(t)
h, err := buildValidationHandler(tt)
req.NoError(err)
err = h.validateRequest(tt.args.r)
req.Equal(tt.wantErr, err != nil)
if err != nil {
encoder.Encode(tt.args.r.Context(), err, httptest.NewRecorder())
if tt.wantErrResponse != mockEncoder.Err {
req.Equal(tt.wantErrResponse, mockEncoder.Err)
}
}
})
}
}
func buildValidationHandler(tt *validationTest) (*ValidationHandler, error) {
if tt.fields.File == "" {
tt.fields.File = "fixtures/petstore.json"
}
h := &ValidationHandler{
Handler: tt.fields.Handler,
File: tt.fields.File,
ErrorEncoder: tt.fields.ErrorEncoder,
}
tt.wantErr = tt.wantErr ||
(tt.wantErrBody != "") ||
(tt.wantErrReason != "") ||
(tt.wantErrSchemaReason != "") ||
(tt.wantErrSchemaPath != "") ||
(tt.wantErrParseValue != nil) ||
(tt.wantErrParseReason != "")
err := h.Load()
return h, err
}
type testHandler struct {
Called bool
}
func (h *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.Called = true
}
type mockErrorEncoder struct {
Called bool
Ctx context.Context
Err error
W http.ResponseWriter
}
func (e *mockErrorEncoder) Encode(ctx context.Context, err error, w http.ResponseWriter) {
e.Called = true
e.Ctx = ctx
e.Err = err
e.W = w
}
func runTest_ServeHTTP(t *testing.T, handler http.Handler, encoder ErrorEncoder, req *http.Request) *http.Response {
h := &ValidationHandler{
Handler: handler,
ErrorEncoder: encoder,
File: "fixtures/petstore.json",
}
err := h.Load()
require.NoError(t, err)
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
return w.Result()
}
func runTest_Middleware(t *testing.T, handler http.Handler, encoder ErrorEncoder, req *http.Request) *http.Response {
h := &ValidationHandler{
ErrorEncoder: encoder,
File: "fixtures/petstore.json",
}
err := h.Load()
require.NoError(t, err)
w := httptest.NewRecorder()
h.Middleware(handler).ServeHTTP(w, req)
return w.Result()
}
func TestValidationHandler_ServeHTTP(t *testing.T) {
t.Run("errors on invalid requests", func(t *testing.T) {
httpCtx := context.WithValue(context.Background(), "pig", "tails")
r, err := http.NewRequest(http.MethodGet, "http://unknown-host.com/v2/pet", nil)
require.NoError(t, err)
r = r.WithContext(httpCtx)
handler := &testHandler{}
encoder := &mockErrorEncoder{}
runTest_ServeHTTP(t, handler, encoder.Encode, r)
require.False(t, handler.Called)
require.True(t, encoder.Called)
require.Equal(t, httpCtx, encoder.Ctx)
require.NotNil(t, encoder.Err)
})
t.Run("passes valid requests through", func(t *testing.T) {
r := newPetstoreRequest(t, http.MethodGet, "/pet/findByStatus?status=sold", nil)
handler := &testHandler{}
encoder := &mockErrorEncoder{}
runTest_ServeHTTP(t, handler, encoder.Encode, r)
require.True(t, handler.Called)
require.False(t, encoder.Called)
})
t.Run("uses error encoder", func(t *testing.T) {
r := newPetstoreRequest(t, http.MethodPost, "/pet", bytes.NewBufferString(`{"name":"Bahama","photoUrls":"http://cat"}`))
handler := &testHandler{}
encoder := &ValidationErrorEncoder{Encoder: (ErrorEncoder)(DefaultErrorEncoder)}
resp := runTest_ServeHTTP(t, handler, encoder.Encode, r)
body, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusUnprocessableEntity, resp.StatusCode)
require.Equal(t, "[422][][] field must be set to array or not be present [source pointer=/photoUrls]", string(body))
})
}
func TestValidationHandler_Middleware(t *testing.T) {
t.Run("errors on invalid requests", func(t *testing.T) {
httpCtx := context.WithValue(context.Background(), "pig", "tails")
r, err := http.NewRequest(http.MethodGet, "http://unknown-host.com/v2/pet", nil)
require.NoError(t, err)
r = r.WithContext(httpCtx)
handler := &testHandler{}
encoder := &mockErrorEncoder{}
runTest_Middleware(t, handler, encoder.Encode, r)
require.False(t, handler.Called)
require.True(t, encoder.Called)
require.Equal(t, httpCtx, encoder.Ctx)
require.NotNil(t, encoder.Err)
})
t.Run("passes valid requests through", func(t *testing.T) {
r := newPetstoreRequest(t, http.MethodGet, "/pet/findByStatus?status=sold", nil)
handler := &testHandler{}
encoder := &mockErrorEncoder{}
runTest_Middleware(t, handler, encoder.Encode, r)
require.True(t, handler.Called)
require.False(t, encoder.Called)
})
t.Run("uses error encoder", func(t *testing.T) {
r := newPetstoreRequest(t, http.MethodPost, "/pet", bytes.NewBufferString(`{"name":"Bahama","photoUrls":"http://cat"}`))
handler := &testHandler{}
encoder := &ValidationErrorEncoder{Encoder: (ErrorEncoder)(DefaultErrorEncoder)}
resp := runTest_Middleware(t, handler, encoder.Encode, r)
body, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusUnprocessableEntity, resp.StatusCode)
require.Equal(t, "[422][][] field must be set to array or not be present [source pointer=/photoUrls]", string(body))
})
}