File: issue356_test.go

package info (click to toggle)
golang-github-getkin-kin-openapi 0.124.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,288 kB
  • sloc: sh: 344; makefile: 4
file content (145 lines) | stat: -rw-r--r-- 3,867 bytes parent folder | download | duplicates (3)
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
package routers_test

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/getkin/kin-openapi/openapi3filter"
	"github.com/getkin/kin-openapi/routers"
	"github.com/getkin/kin-openapi/routers/gorillamux"
	"github.com/getkin/kin-openapi/routers/legacy"
)

func TestIssue356(t *testing.T) {
	spec := func(servers string) []byte {
		return []byte(`
openapi: 3.0.0
info:
  title: Example
  version: '1.0'
  description: test
servers:
` + servers + `
paths:
  /test:
    post:
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema: {type: object}
      requestBody:
        content:
          application/json:
            schema: {type: object}
        description: ''
      description: Create a test object
`)
	}

	for servers, expectError := range map[string]bool{
		`
- url: http://localhost:3000/base
- url: /base
`: false,

		`
- url: /base
- url: http://localhost:3000/base
`: false,

		`- url: /base`: false,

		`- url: http://localhost:3000/base`: true,

		``: true,
	} {
		loader := &openapi3.Loader{Context: context.Background()}
		t.Logf("using servers: %q (%v)", servers, expectError)
		doc, err := loader.LoadFromData(spec(servers))
		require.NoError(t, err)
		err = doc.Validate(context.Background())
		require.NoError(t, err)
		gorillamuxNewRouterWrapped := func(doc *openapi3.T, opts ...openapi3.ValidationOption) (routers.Router, error) {
			return gorillamux.NewRouter(doc)
		}

		for i, newRouter := range []func(*openapi3.T, ...openapi3.ValidationOption) (routers.Router, error){gorillamuxNewRouterWrapped, legacy.NewRouter} {
			t.Logf("using NewRouter from %s", map[int]string{0: "gorillamux", 1: "legacy"}[i])
			router, err := newRouter(doc)
			require.NoError(t, err)

			if true {
				t.Logf("using naked newRouter")
				httpReq, err := http.NewRequest(http.MethodPost, "/base/test", strings.NewReader(`{}`))
				require.NoError(t, err)
				httpReq.Header.Set("Content-Type", "application/json")

				route, pathParams, err := router.FindRoute(httpReq)
				if expectError {
					require.Error(t, err, routers.ErrPathNotFound)
					return
				}
				require.NoError(t, err)

				requestValidationInput := &openapi3filter.RequestValidationInput{
					Request:    httpReq,
					PathParams: pathParams,
					Route:      route,
				}
				err = openapi3filter.ValidateRequest(context.Background(), requestValidationInput)
				require.NoError(t, err)
			}

			if true {
				t.Logf("using httptest.NewServer")
				ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					route, pathParams, err := router.FindRoute(r)
					if err != nil {
						w.WriteHeader(http.StatusInternalServerError)
						w.Write([]byte(err.Error()))
						return
					}

					requestValidationInput := &openapi3filter.RequestValidationInput{
						Request:    r,
						PathParams: pathParams,
						Route:      route,
					}
					err = openapi3filter.ValidateRequest(r.Context(), requestValidationInput)
					require.NoError(t, err)

					w.Header().Set("Content-Type", "application/json")
					w.Write([]byte("{}"))
				}))
				defer ts.Close()

				req, err := http.NewRequest(http.MethodPost, ts.URL+"/base/test", strings.NewReader(`{}`))
				require.NoError(t, err)
				req.Header.Set("Content-Type", "application/json")

				rep, err := http.DefaultClient.Do(req)
				require.NoError(t, err)
				defer rep.Body.Close()
				body, err := io.ReadAll(rep.Body)
				require.NoError(t, err)

				if expectError {
					require.Equal(t, 500, rep.StatusCode)
					require.Equal(t, routers.ErrPathNotFound.Error(), string(body))
					return
				}
				require.Equal(t, 200, rep.StatusCode)
				require.Equal(t, "{}", string(body))
			}
		}
	}
}