-
Notifications
You must be signed in to change notification settings - Fork 1
/
open_api_helper.go
97 lines (80 loc) · 2.65 KB
/
open_api_helper.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
package helpers
import (
"context"
"net/http"
"net/http/httptest"
"path"
"runtime"
"testing"
"github.com/getkin/kin-openapi/routers/gorillamux"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
oarouters "github.com/getkin/kin-openapi/routers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var router oarouters.Router
func init() {
ctx := context.Background()
loader := &openapi3.Loader{Context: ctx, IsExternalRefsAllowed: true}
_, filename, _, _ := runtime.Caller(0)
apiDefinitionPath := path.Join(filename, "..", "..", "..", "api", "skyscraper.yaml")
doc, err := loader.LoadFromFile(apiDefinitionPath)
if err != nil {
panic(err)
}
// Our test requests are relative, so the server URL doesn't get found.
doc.Servers = nil
err = doc.Validate(ctx)
if err != nil {
panic(err)
}
router, err = gorillamux.NewRouter(doc)
if err != nil {
panic(err)
}
}
func AssertOpenAPI(t *testing.T, rr *httptest.ResponseRecorder, req *http.Request) []byte {
t.Helper()
ctx := context.Background()
// The request body exists and was already read once when the request
// was sent. Replay it to allow ValidateRequest() to read it again.
if req.Body != nil && req.Body != http.NoBody {
req.Body, _ = req.GetBody()
}
// Validate request.
route, pathParams, err := router.FindRoute(req)
require.NoError(t, err, "could not find route")
requestValidationInput := &openapi3filter.RequestValidationInput{
Request: req,
PathParams: pathParams,
Route: route,
Options: &openapi3filter.Options{
AuthenticationFunc: openapi3filter.NoopAuthenticationFunc,
},
}
// Don't validate the request body if the response indicates an error,
// to allow testing server-side validation using known bad values.
result := rr.Result()
if result.StatusCode >= http.StatusBadRequest {
requestValidationInput.Options.ExcludeRequestBody = true
}
err = openapi3filter.ValidateRequest(ctx, requestValidationInput)
assert.NoError(t, err, "http request is not valid")
// Validate response.
responseValidationInput := &openapi3filter.ResponseValidationInput{
RequestValidationInput: requestValidationInput,
Status: result.StatusCode,
//Header: result.Header,
Header: http.Header{"Content-Type": []string{rr.Header().Get("Content-Type")}},
Options: &openapi3filter.Options{
IncludeResponseStatus: true,
},
}
bodyBytes := rr.Body.Bytes()
responseValidationInput.SetBodyBytes(bodyBytes)
err = openapi3filter.ValidateResponse(ctx, responseValidationInput)
assert.NoError(t, err, "http response is not valid")
_ = result.Body.Close()
return bodyBytes
}