Debian Codegraph @

responses/validate_response_test.go

raw
1 package responses
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "net/http"
8 "strings"
9 "testing"
10
11 "github.com/pb33f/libopenapi"
12 "github.com/pb33f/libopenapi/datamodel/high/base"
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15
16 "github.com/pb33f/libopenapi-validator/config"
17 )
18
19 func TestValidateResponseSchema(t *testing.T) {
20 for name, tc := range map[string]struct {
21 request *http.Request
22 response *http.Response
23 schemaYAML string
24 version float32
25 assertValidResponseSchema assert.BoolAssertionFunc
26 expectedErrorsCount int
27 }{
28 "FailOnBooleanExclusiveMinimum": {
29 request: postRequest(),
30 response: responseWithBody(`{"exclusiveNumber": 10}`),
31 schemaYAML: `type: object
32 properties:
33 exclusiveNumber:
34 type: number
35 description: This number starts its journey where most numbers are too scared to begin!
36 exclusiveMinimum: true
37 minimum: !!float 10`,
38 version: 3.0,
39 assertValidResponseSchema: assert.False,
40 expectedErrorsCount: 1,
41 },
42 "PassWithCorrectExclusiveMinimum": {
43 request: postRequest(),
44 response: responseWithBody(`{"exclusiveNumber": 15}`),
45 schemaYAML: `type: object
46 properties:
47 exclusiveNumber:
48 type: number
49 description: This number is properly constrained by a numeric exclusive minimum.
50 exclusiveMinimum: 12
51 minimum: 12`,
52 version: 3.1,
53 assertValidResponseSchema: assert.True,
54 expectedErrorsCount: 0,
55 },
56 "PassWithValidStringType": {
57 request: postRequest(),
58 response: responseWithBody(`{"greeting": "Hello, world!"}`),
59 schemaYAML: `type: object
60 properties:
61 greeting:
62 type: string
63 description: A simple greeting
64 example: "Hello, world!"`,
65 version: 3.1,
66 assertValidResponseSchema: assert.True,
67 expectedErrorsCount: 0,
68 },
69 "PassWithNullablePropertyInOpenAPI30": {
70 request: postRequest(),
71 response: responseWithBody(`{"name": "John", "middleName": null}`),
72 schemaYAML: `type: object
73 properties:
74 name:
75 type: string
76 description: User's first name
77 middleName:
78 type: string
79 nullable: true
80 description: User's middle name (optional)`,
81 version: 3.0,
82 assertValidResponseSchema: assert.True,
83 expectedErrorsCount: 0,
84 },
85 "PassWithNullablePropertyInOpenAPI31": {
86 request: postRequest(),
87 response: responseWithBody(`{"name": "John", "middleName": null}`),
88 schemaYAML: `type: object
89 properties:
90 name:
91 type: string
92 description: User's first name
93 middleName:
94 type: string
95 nullable: true
96 description: User's middle name (optional)`,
97 version: 3.1,
98 assertValidResponseSchema: assert.False,
99 expectedErrorsCount: 1,
100 },
101 } {
102 t.Run(name, func(t *testing.T) {
103 t.Parallel()
104
105 schema := parseSchemaFromSpec(t, tc.schemaYAML, tc.version)
106
107 valid, errors := ValidateResponseSchema(&ValidateResponseSchemaInput{
108 Request: tc.request,
109 Response: tc.response,
110 Schema: schema,
111 Version: tc.version,
112 })
113
114 tc.assertValidResponseSchema(t, valid)
115 assert.Len(t, errors, tc.expectedErrorsCount)
116 })
117 }
118 }
119
120 func TestBooleanExclusiveMin_ValidValue(t *testing.T) {
121 openAPIVersion := float32(3.0)
122 schema := parseSchemaFromSpec(t, `type: object
123 properties:
124 exclusiveNumber:
125 type: number
126 description: This number starts its journey where most numbers are too scared to begin!
127 exclusiveMinimum: true
128 minimum: 10`, openAPIVersion)
129
130 valid, errors := ValidateResponseSchema(&ValidateResponseSchemaInput{
131 Request: postRequest(),
132 Response: responseWithBody(`{"exclusiveNumber": 13}`),
133 Schema: schema,
134 Version: openAPIVersion,
135 })
136
137 assert.True(t, valid)
138 assert.Empty(t, errors)
139 }
140
141 func TestValidateResponseSchema_CachePopulation(t *testing.T) {
142 schema := parseSchemaFromSpec(t, `type: object
143 properties:
144 name:
145 type: string`, 3.1)
146
147 // Create options with a cache
148 opts := config.NewValidationOptions()
149 require.NotNil(t, opts.SchemaCache)
150
151 // First call should populate the cache
152 valid, errors := ValidateResponseSchema(&ValidateResponseSchemaInput{
153 Request: postRequest(),
154 Response: responseWithBody(`{"name": "test"}`),
155 Schema: schema,
156 Version: 3.1,
157 Options: []config.Option{config.WithExistingOpts(opts)},
158 })
159
160 assert.True(t, valid)
161 assert.Len(t, errors, 0)
162
163 // Verify cache was populated
164 hash := schema.GoLow().Hash()
165 cached, ok := opts.SchemaCache.Load(hash)
166 assert.True(t, ok, "Schema should be in cache")
167 assert.NotNil(t, cached, "Cached entry should not be nil")
168 assert.NotNil(t, cached.CompiledSchema, "Compiled schema should be cached")
169 assert.NotNil(t, cached.RenderedInline, "Rendered schema should be cached")
170 assert.NotNil(t, cached.RenderedJSON, "JSON schema should be cached")
171 }
172
173 func postRequest() *http.Request {
174 req, _ := http.NewRequest(http.MethodPost, "/test", io.NopCloser(strings.NewReader("")))
175 return req
176 }
177
178 func responseWithBody(payload string) *http.Response {
179 return &http.Response{
180 StatusCode: http.StatusOK,
181 Body: io.NopCloser(bytes.NewReader([]byte(payload))),
182 Header: http.Header{"Content-Type": []string{"application/json"}},
183 }
184 }
185
186 // parseSchemaFromSpec creates a base.Schema from an OpenAPI spec YAML string.
187 // This ensures that we're using the native libopenapi logic for generating the schema.
188 func parseSchemaFromSpec(t *testing.T, schemaYAML string, version float32) *base.Schema {
189 // Convert version to API version string (3.0 -> "3.0.0", 3.1 -> "3.1.0")
190 apiVersion := fmt.Sprintf("%.1f.0", version)
191
192 spec := fmt.Sprintf(`openapi: %s
193 info:
194 title: Test
195 version: 1.0.0
196 components:
197 schemas:
198 TestSchema:
199 %s`, apiVersion, indentLines(schemaYAML, " "))
200
201 doc, err := libopenapi.NewDocument([]byte(spec))
202 require.NoError(t, err)
203 model, errs := doc.BuildV3Model()
204 require.Empty(t, errs)
205 schema := model.Model.Components.Schemas.GetOrZero("TestSchema")
206 require.NotNil(t, schema)
207 return schema.Schema()
208 }
209
210 // indentLines adds the specified indentation to each line of the input string
211 func indentLines(s string, indent string) string {
212 lines := strings.Split(strings.TrimSpace(s), "\n")
213 for i, line := range lines {
214 if line != "" {
215 lines[i] = indent + line
216 }
217 }
218 return strings.Join(lines, "\n")
219 }
220
221 func TestValidateResponseSchema_NilSchema(t *testing.T) {
222 // Test when schema is nil
223 valid, errors := ValidateResponseSchema(&ValidateResponseSchemaInput{
224 Request: postRequest(),
225 Response: responseWithBody(`{"name": "test"}`),
226 Schema: nil,
227 Version: 3.1,
228 })
229
230 assert.False(t, valid)
231 require.Len(t, errors, 1)
232 assert.Equal(t, "schema is nil", errors[0].Message)
233 assert.Equal(t, "The schema to validate against is nil", errors[0].Reason)
234 }
235
236 func TestValidateResponseSchema_NilSchemaGoLow(t *testing.T) {
237 // Test when schema.GoLow() is nil by creating a schema without low-level data
238 schema := &base.Schema{} // Empty schema without GoLow() data
239
240 valid, errors := ValidateResponseSchema(&ValidateResponseSchemaInput{
241 Request: postRequest(),
242 Response: responseWithBody(`{"name": "test"}`),
243 Schema: schema,
244 Version: 3.1,
245 })
246
247 assert.False(t, valid)
248 require.Len(t, errors, 1)
249 assert.Equal(t, "schema cannot be rendered", errors[0].Message)
250 assert.Contains(t, errors[0].Reason, "does not have low-level information")
251 }
252
253 func TestValidateResponseSchema_CircularReference(t *testing.T) {
254 // Test when schema has a circular reference that causes render failure
255 spec := `openapi: 3.1.0
256 info:
257 title: Test
258 version: 1.0.0
259 components:
260 schemas:
261 Error:
262 type: object
263 properties:
264 code:
265 type: string
266 details:
267 type: array
268 items:
269 $ref: '#/components/schemas/Error'`
270
271 doc, err := libopenapi.NewDocument([]byte(spec))
272 require.NoError(t, err)
273 model, errs := doc.BuildV3Model()
274 require.Empty(t, errs)
275
276 // Verify circular reference was detected
277 require.Len(t, model.Index.GetCircularReferences(), 1)
278
279 schema := model.Model.Components.Schemas.GetOrZero("Error")
280 require.NotNil(t, schema)
281
282 valid, errors := ValidateResponseSchema(&ValidateResponseSchemaInput{
283 Request: postRequest(),
284 Response: responseWithBody(`{"code": "abc", "details": [{"code": "def"}]}`),
285 Schema: schema.Schema(),
286 Version: 3.1,
287 })
288
289 assert.False(t, valid)
290 require.Len(t, errors, 1)
291 assert.Contains(t, errors[0].Message, "failed schema rendering")
292 assert.Contains(t, errors[0].Reason, "circular reference")
293 }
294
295 func TestValidateResponseSchema_ResponseMissing(t *testing.T) {
296 schema := parseSchemaFromSpec(t, `type: object
297 properties:
298 name:
299 type: string`, 3.1)
300
301 // Response body missing (NoBody) for a non-HEAD request should error
302 valid, errs := ValidateResponseSchema(&ValidateResponseSchemaInput{
303 Request: postRequest(),
304 Response: &http.Response{StatusCode: http.StatusOK, Body: http.NoBody},
305 Schema: schema,
306 Version: 3.1,
307 })
308
309 assert.False(t, valid)
310 require.Len(t, errs, 1)
311 assert.Contains(t, errs[0].Message, "response object is missing")
312 }
313
314 func TestValidateResponseSchema_HeadEmptySkipsValidation(t *testing.T) {
315 schema := parseSchemaFromSpec(t, `type: object`, 3.1)
316
317 req, _ := http.NewRequest(http.MethodHead, "/test", nil)
318 resp := &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
319
320 valid, errs := ValidateResponseSchema(&ValidateResponseSchemaInput{
321 Request: req,
322 Response: resp,
323 Schema: schema,
324 Version: 3.1,
325 })
326
327 assert.True(t, valid)
328 assert.Len(t, errs, 0)
329 }
330
331 func TestValidateResponseSchema_HeadWithBodyFails(t *testing.T) {
332 schema := parseSchemaFromSpec(t, `type: object`, 3.1)
333
334 req, _ := http.NewRequest(http.MethodHead, "/test", nil)
335
336 valid, errs := ValidateResponseSchema(&ValidateResponseSchemaInput{
337 Request: req,
338 Response: responseWithBody(`{"name":"bob"}`),
339 Schema: schema,
340 Version: 3.1,
341 })
342
343 assert.False(t, valid)
344 require.Len(t, errs, 1)
345 assert.Contains(t, errs[0].Reason, "must not contain a body")
346 }