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
|
package openapi3filter
import (
"context"
"io"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/require"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/routers/gorillamux"
)
func TestIssue201(t *testing.T) {
loader := openapi3.NewLoader()
ctx := loader.Context
spec := `
openapi: '3.0.3'
info:
version: 1.0.0
title: Sample API
paths:
/_:
get:
description: ''
responses:
default:
description: ''
content:
application/json:
schema:
type: object
headers:
X-Blip:
description: ''
required: true
schema:
type: string
pattern: '^blip$'
x-blop:
description: ''
schema:
type: string
pattern: '^blop$'
X-Blap:
description: ''
required: true
schema:
type: string
pattern: '^blap$'
X-Blup:
description: ''
required: true
schema:
type: string
pattern: '^blup$'
`[1:]
doc, err := loader.LoadFromData([]byte(spec))
require.NoError(t, err)
err = doc.Validate(ctx)
require.NoError(t, err)
for name, testcase := range map[string]struct {
headers map[string]string
err string
}{
"no error": {
headers: map[string]string{
"X-Blip": "blip",
"x-blop": "blop",
"X-Blap": "blap",
"X-Blup": "blup",
},
},
"missing non-required header": {
headers: map[string]string{
"X-Blip": "blip",
// "x-blop": "blop",
"X-Blap": "blap",
"X-Blup": "blup",
},
},
"missing required header": {
err: `response header "X-Blip" missing`,
headers: map[string]string{
// "X-Blip": "blip",
"x-blop": "blop",
"X-Blap": "blap",
"X-Blup": "blup",
},
},
"invalid required header": {
err: `response header "X-Blup" doesn't match schema: string doesn't match the regular expression "^blup$"`,
headers: map[string]string{
"X-Blip": "blip",
"x-blop": "blop",
"X-Blap": "blap",
"X-Blup": "bluuuuuup",
},
},
} {
t.Run(name, func(t *testing.T) {
router, err := gorillamux.NewRouter(doc)
require.NoError(t, err)
r, err := http.NewRequest(http.MethodGet, `/_`, nil)
require.NoError(t, err)
r.Header.Add(headerCT, "application/json")
for k, v := range testcase.headers {
r.Header.Add(k, v)
}
route, pathParams, err := router.FindRoute(r)
require.NoError(t, err)
err = ValidateResponse(context.Background(), &ResponseValidationInput{
RequestValidationInput: &RequestValidationInput{
Request: r,
PathParams: pathParams,
Route: route,
},
Status: 200,
Header: r.Header,
Body: io.NopCloser(strings.NewReader(`{}`)),
})
if e := testcase.err; e != "" {
require.ErrorContains(t, err, e)
} else {
require.NoError(t, err)
}
})
}
}
|