| 1 |
// Copyright 2023-2025 Princess Beef Heavy Industries, LLC / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
package validator |
| 5 |
|
| 6 |
import ( |
| 7 |
"bytes" |
| 8 |
"encoding/json" |
| 9 |
"fmt" |
| 10 |
"io" |
| 11 |
"net/http" |
| 12 |
"net/http/httptest" |
| 13 |
"net/url" |
| 14 |
"os" |
| 15 |
"strings" |
| 16 |
"sync" |
| 17 |
"testing" |
| 18 |
"unicode" |
| 19 |
|
| 20 |
"github.com/dlclark/regexp2" |
| 21 |
"github.com/pb33f/libopenapi" |
| 22 |
"github.com/santhosh-tekuri/jsonschema/v6" |
| 23 |
"github.com/stretchr/testify/assert" |
| 24 |
"github.com/stretchr/testify/require" |
| 25 |
|
| 26 |
v3 "github.com/pb33f/libopenapi/datamodel/high/v3" |
| 27 |
|
| 28 |
"github.com/pb33f/libopenapi-validator/cache" |
| 29 |
"github.com/pb33f/libopenapi-validator/config" |
| 30 |
"github.com/pb33f/libopenapi-validator/errors" |
| 31 |
"github.com/pb33f/libopenapi-validator/helpers" |
| 32 |
) |
| 33 |
|
| 34 |
func TestNewValidator(t *testing.T) { |
| 35 |
spec := `openapi: 3.1.0 |
| 36 |
paths: |
| 37 |
/burgers/createBurger: |
| 38 |
post: |
| 39 |
requestBody: |
| 40 |
content: |
| 41 |
application/json: |
| 42 |
schema: |
| 43 |
type: object |
| 44 |
properties: |
| 45 |
name: |
| 46 |
type: string |
| 47 |
patties: |
| 48 |
type: integer |
| 49 |
vegetarian: |
| 50 |
type: boolean` |
| 51 |
|
| 52 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 53 |
|
| 54 |
v, _ := NewValidator(doc) |
| 55 |
assert.NotNil(t, v.GetParameterValidator()) |
| 56 |
assert.NotNil(t, v.GetResponseBodyValidator()) |
| 57 |
assert.NotNil(t, v.GetRequestBodyValidator()) |
| 58 |
} |
| 59 |
|
| 60 |
func TestNewValidator_concurrent(t *testing.T) { |
| 61 |
spec := `openapi: 3.1.0 |
| 62 |
paths: |
| 63 |
/burgers/createBurger: |
| 64 |
post: |
| 65 |
requestBody: |
| 66 |
content: |
| 67 |
application/json: |
| 68 |
schema: |
| 69 |
type: object |
| 70 |
properties: |
| 71 |
name: |
| 72 |
type: string |
| 73 |
patties: |
| 74 |
type: integer |
| 75 |
vegetarian: |
| 76 |
type: boolean |
| 77 |
/burgers/createBurger/{burgerId}: |
| 78 |
post: |
| 79 |
parameters: |
| 80 |
- in: path |
| 81 |
name: burgerId |
| 82 |
required: true |
| 83 |
schema: |
| 84 |
type: string |
| 85 |
requestBody: |
| 86 |
content: |
| 87 |
application/json: |
| 88 |
schema: |
| 89 |
type: object |
| 90 |
properties: |
| 91 |
name: |
| 92 |
type: string |
| 93 |
patties: |
| 94 |
type: integer |
| 95 |
vegetarian: |
| 96 |
type: boolean` |
| 97 |
|
| 98 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 99 |
|
| 100 |
assert.Empty(t, err) |
| 101 |
|
| 102 |
v, _ := NewValidator(doc) |
| 103 |
|
| 104 |
body := map[string]interface{}{ |
| 105 |
"name": "Big Mac", |
| 106 |
"patties": 2, |
| 107 |
"vegetarian": true, |
| 108 |
} |
| 109 |
|
| 110 |
bodyBytes, _ := json.Marshal(body) |
| 111 |
|
| 112 |
var wg sync.WaitGroup |
| 113 |
wg.Add(2) |
| 114 |
go func() { |
| 115 |
defer wg.Done() |
| 116 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 117 |
bytes.NewBuffer(bodyBytes)) |
| 118 |
request.Header.Set("Content-Type", "application/json") |
| 119 |
|
| 120 |
valid, errors := v.ValidateHttpRequest(request) |
| 121 |
|
| 122 |
assert.True(t, valid) |
| 123 |
assert.Len(t, errors, 0) |
| 124 |
}() |
| 125 |
|
| 126 |
go func() { |
| 127 |
defer wg.Done() |
| 128 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger/toto", |
| 129 |
bytes.NewBuffer(bodyBytes)) |
| 130 |
request.Header.Set("Content-Type", "application/json") |
| 131 |
|
| 132 |
valid, errors := v.ValidateHttpRequest(request) |
| 133 |
|
| 134 |
assert.True(t, valid) |
| 135 |
assert.Len(t, errors, 0) |
| 136 |
}() |
| 137 |
|
| 138 |
wg.Wait() |
| 139 |
} |
| 140 |
|
| 141 |
func TestNewValidator_ValidateDocument(t *testing.T) { |
| 142 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 143 |
v, _ := NewValidator(doc) |
| 144 |
valid, errs := v.ValidateDocument() |
| 145 |
assert.True(t, valid) |
| 146 |
assert.Len(t, errs, 0) |
| 147 |
} |
| 148 |
|
| 149 |
type dlclarkRegexp regexp2.Regexp |
| 150 |
|
| 151 |
func (re *dlclarkRegexp) MatchString(s string) bool { |
| 152 |
matched, err := (*regexp2.Regexp)(re).MatchString(s) |
| 153 |
return err == nil && matched |
| 154 |
} |
| 155 |
|
| 156 |
func (re *dlclarkRegexp) String() string { |
| 157 |
return (*regexp2.Regexp)(re).String() |
| 158 |
} |
| 159 |
|
| 160 |
func dlclarkCompile(s string) (jsonschema.Regexp, error) { |
| 161 |
re, err := regexp2.Compile(s, regexp2.ECMAScript) |
| 162 |
if err != nil { |
| 163 |
return nil, err |
| 164 |
} |
| 165 |
return (*dlclarkRegexp)(re), nil |
| 166 |
} |
| 167 |
|
| 168 |
func TestNewValidator_WithRegex(t *testing.T) { |
| 169 |
doc, err := libopenapi.NewDocument(petstoreBytes) |
| 170 |
require.Nil(t, err, "Failed to load spec") |
| 171 |
|
| 172 |
v, errs := NewValidator(doc, config.WithRegexEngine(dlclarkCompile)) |
| 173 |
require.Empty(t, errs, "Failed to build validator") |
| 174 |
require.NotNil(t, v, "Failed to build validator") |
| 175 |
|
| 176 |
valid, valErrs := v.ValidateDocument() |
| 177 |
assert.True(t, valid) |
| 178 |
assert.Empty(t, valErrs) |
| 179 |
} |
| 180 |
|
| 181 |
func TestNewValidator_WithCustomFormat_NoErrors(t *testing.T) { |
| 182 |
spec := `openapi: 3.1.0 |
| 183 |
paths: |
| 184 |
/burgers/createBurger: |
| 185 |
post: |
| 186 |
requestBody: |
| 187 |
content: |
| 188 |
application/json: |
| 189 |
schema: |
| 190 |
type: object |
| 191 |
properties: |
| 192 |
name: |
| 193 |
type: string |
| 194 |
format: capital |
| 195 |
patties: |
| 196 |
type: integer |
| 197 |
vegetarian: |
| 198 |
type: boolean` |
| 199 |
|
| 200 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 201 |
require.NoError(t, err, "Failed to load spec") |
| 202 |
require.NotNil(t, doc, "Failed to load spec") |
| 203 |
|
| 204 |
v, errs := NewValidator( |
| 205 |
doc, |
| 206 |
config.WithFormatAssertions(), |
| 207 |
config.WithCustomFormat("capital", func(v any) error { |
| 208 |
s, ok := v.(string) |
| 209 |
if !ok { |
| 210 |
return fmt.Errorf("expected string") |
| 211 |
} |
| 212 |
|
| 213 |
if s == "" { |
| 214 |
return nil |
| 215 |
} |
| 216 |
|
| 217 |
r := []rune(s)[0] |
| 218 |
|
| 219 |
if !unicode.IsUpper(r) { |
| 220 |
return fmt.Errorf("expected first latter to be uppercase") |
| 221 |
} |
| 222 |
|
| 223 |
return nil |
| 224 |
}), |
| 225 |
) |
| 226 |
require.Empty(t, errs, "Failed to build validator") |
| 227 |
require.NotNil(t, v, "Failed to build validator") |
| 228 |
|
| 229 |
body := map[string]interface{}{ |
| 230 |
"name": "Big Mac", |
| 231 |
"patties": 2, |
| 232 |
"vegetarian": true, |
| 233 |
} |
| 234 |
|
| 235 |
bodyBytes, _ := json.Marshal(body) |
| 236 |
|
| 237 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 238 |
bytes.NewBuffer(bodyBytes)) |
| 239 |
request.Header.Set("Content-Type", "application/json") |
| 240 |
|
| 241 |
valid, errors := v.ValidateHttpRequest(request) |
| 242 |
|
| 243 |
assert.True(t, valid) |
| 244 |
assert.Len(t, errors, 0) |
| 245 |
} |
| 246 |
|
| 247 |
func TestStrictMode_ValidateHttpRequestIntegration(t *testing.T) { |
| 248 |
spec := `openapi: 3.1.0 |
| 249 |
paths: |
| 250 |
/things/{id}: |
| 251 |
post: |
| 252 |
parameters: |
| 253 |
- in: path |
| 254 |
name: id |
| 255 |
required: true |
| 256 |
schema: |
| 257 |
type: string |
| 258 |
- in: query |
| 259 |
name: q |
| 260 |
schema: |
| 261 |
type: string |
| 262 |
- in: header |
| 263 |
name: X-Known |
| 264 |
schema: |
| 265 |
type: string |
| 266 |
- in: cookie |
| 267 |
name: session |
| 268 |
schema: |
| 269 |
type: string |
| 270 |
requestBody: |
| 271 |
required: true |
| 272 |
content: |
| 273 |
application/json: |
| 274 |
schema: |
| 275 |
type: object |
| 276 |
properties: |
| 277 |
name: |
| 278 |
type: string |
| 279 |
responses: |
| 280 |
"200": |
| 281 |
description: ok |
| 282 |
content: |
| 283 |
application/json: |
| 284 |
schema: |
| 285 |
type: object |
| 286 |
properties: |
| 287 |
ok: |
| 288 |
type: boolean` |
| 289 |
|
| 290 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 291 |
require.NoError(t, err) |
| 292 |
|
| 293 |
v, errs := NewValidator(doc, config.WithStrictMode()) |
| 294 |
require.Empty(t, errs) |
| 295 |
|
| 296 |
body := map[string]any{ |
| 297 |
"name": "ok", |
| 298 |
"extra": "nope", |
| 299 |
} |
| 300 |
bodyBytes, _ := json.Marshal(body) |
| 301 |
|
| 302 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/things/123?q=ok&extra=1", bytes.NewBuffer(bodyBytes)) |
| 303 |
request.Header.Set("Content-Type", "application/json") |
| 304 |
request.Header.Set("X-Known", "known") |
| 305 |
request.Header.Set("X-Extra", "nope") |
| 306 |
request.AddCookie(&http.Cookie{Name: "session", Value: "ok"}) |
| 307 |
request.AddCookie(&http.Cookie{Name: "other", Value: "nope"}) |
| 308 |
|
| 309 |
valid, valErrs := v.ValidateHttpRequest(request) |
| 310 |
assert.False(t, valid) |
| 311 |
|
| 312 |
strictSubTypes := make(map[string]bool) |
| 313 |
for _, vErr := range valErrs { |
| 314 |
if vErr.ValidationType == errors.StrictValidationType { |
| 315 |
strictSubTypes[vErr.ValidationSubType] = true |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
assert.True(t, strictSubTypes[errors.StrictSubTypeProperty]) |
| 320 |
assert.True(t, strictSubTypes[errors.StrictSubTypeHeader]) |
| 321 |
assert.True(t, strictSubTypes[errors.StrictSubTypeQuery]) |
| 322 |
assert.True(t, strictSubTypes[errors.StrictSubTypeCookie]) |
| 323 |
} |
| 324 |
|
| 325 |
func TestStrictMode_ValidateHttpResponseHeadersIntegration(t *testing.T) { |
| 326 |
spec := `openapi: 3.1.0 |
| 327 |
paths: |
| 328 |
/things/{id}: |
| 329 |
get: |
| 330 |
parameters: |
| 331 |
- in: path |
| 332 |
name: id |
| 333 |
required: true |
| 334 |
schema: |
| 335 |
type: string |
| 336 |
responses: |
| 337 |
"200": |
| 338 |
description: ok |
| 339 |
headers: |
| 340 |
X-Res: |
| 341 |
schema: |
| 342 |
type: string |
| 343 |
content: |
| 344 |
application/json: |
| 345 |
schema: |
| 346 |
type: object |
| 347 |
properties: |
| 348 |
ok: |
| 349 |
type: boolean` |
| 350 |
|
| 351 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 352 |
require.NoError(t, err) |
| 353 |
|
| 354 |
v, errs := NewValidator(doc, config.WithStrictMode()) |
| 355 |
require.Empty(t, errs) |
| 356 |
|
| 357 |
request, _ := http.NewRequest(http.MethodGet, "https://things.com/things/123", http.NoBody) |
| 358 |
|
| 359 |
body := map[string]any{"ok": true} |
| 360 |
bodyBytes, _ := json.Marshal(body) |
| 361 |
|
| 362 |
response := &http.Response{ |
| 363 |
StatusCode: 200, |
| 364 |
Header: http.Header{ |
| 365 |
"Content-Type": {"application/json"}, |
| 366 |
"X-Res": {"ok"}, |
| 367 |
"X-Extra": {"nope"}, |
| 368 |
}, |
| 369 |
Body: io.NopCloser(bytes.NewBuffer(bodyBytes)), |
| 370 |
} |
| 371 |
|
| 372 |
valid, valErrs := v.ValidateHttpResponse(request, response) |
| 373 |
assert.False(t, valid) |
| 374 |
|
| 375 |
foundStrictHeader := false |
| 376 |
for _, vErr := range valErrs { |
| 377 |
if vErr.ValidationType == errors.StrictValidationType && |
| 378 |
vErr.ValidationSubType == errors.StrictSubTypeHeader { |
| 379 |
foundStrictHeader = true |
| 380 |
break |
| 381 |
} |
| 382 |
} |
| 383 |
assert.True(t, foundStrictHeader) |
| 384 |
} |
| 385 |
|
| 386 |
func TestNewValidator_WithCustomFormat_FormatError(t *testing.T) { |
| 387 |
spec := `openapi: 3.1.0 |
| 388 |
paths: |
| 389 |
/burgers/createBurger: |
| 390 |
post: |
| 391 |
requestBody: |
| 392 |
content: |
| 393 |
application/json: |
| 394 |
schema: |
| 395 |
type: object |
| 396 |
properties: |
| 397 |
name: |
| 398 |
type: string |
| 399 |
format: capital |
| 400 |
patties: |
| 401 |
type: integer |
| 402 |
vegetarian: |
| 403 |
type: boolean` |
| 404 |
|
| 405 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 406 |
require.NoError(t, err, "Failed to load spec") |
| 407 |
require.NotNil(t, doc, "Failed to load spec") |
| 408 |
|
| 409 |
v, errs := NewValidator( |
| 410 |
doc, |
| 411 |
config.WithFormatAssertions(), |
| 412 |
config.WithCustomFormat("capital", func(v any) error { |
| 413 |
s, ok := v.(string) |
| 414 |
if !ok { |
| 415 |
return fmt.Errorf("expected string") |
| 416 |
} |
| 417 |
|
| 418 |
if s == "" { |
| 419 |
return nil |
| 420 |
} |
| 421 |
|
| 422 |
r := []rune(s)[0] |
| 423 |
|
| 424 |
if !unicode.IsUpper(r) { |
| 425 |
return fmt.Errorf("expected first latter to be uppercase") |
| 426 |
} |
| 427 |
|
| 428 |
return nil |
| 429 |
}), |
| 430 |
) |
| 431 |
require.Empty(t, errs, "Failed to build validator") |
| 432 |
require.NotNil(t, v, "Failed to build validator") |
| 433 |
|
| 434 |
v.GetRequestBodyValidator() |
| 435 |
|
| 436 |
body := map[string]interface{}{ |
| 437 |
"name": "big mac", |
| 438 |
"patties": 2, |
| 439 |
"vegetarian": true, |
| 440 |
} |
| 441 |
|
| 442 |
bodyBytes, _ := json.Marshal(body) |
| 443 |
|
| 444 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 445 |
bytes.NewBuffer(bodyBytes)) |
| 446 |
request.Header.Set("Content-Type", "application/json") |
| 447 |
|
| 448 |
valid, errors := v.ValidateHttpRequest(request) |
| 449 |
|
| 450 |
assert.False(t, valid) |
| 451 |
require.Len(t, errors, 1) |
| 452 |
assert.Equal(t, "POST request body for '/burgers/createBurger' failed to validate schema", errors[0].Message) |
| 453 |
require.Len(t, errors[0].SchemaValidationErrors, 1) |
| 454 |
require.NotNil(t, errors[0].SchemaValidationErrors[0]) |
| 455 |
assert.Equal(t, "/properties/name/format", errors[0].SchemaValidationErrors[0].KeywordLocation) |
| 456 |
assert.Equal(t, "'big mac' is not valid capital: expected first latter to be uppercase", errors[0].SchemaValidationErrors[0].Reason) |
| 457 |
} |
| 458 |
|
| 459 |
func TestNewValidator_WithCustomFormat_NoErrorsWhenFormatAssertionDisabled(t *testing.T) { |
| 460 |
spec := `openapi: 3.1.0 |
| 461 |
paths: |
| 462 |
/burgers/createBurger: |
| 463 |
post: |
| 464 |
requestBody: |
| 465 |
content: |
| 466 |
application/json: |
| 467 |
schema: |
| 468 |
type: object |
| 469 |
properties: |
| 470 |
name: |
| 471 |
type: string |
| 472 |
format: capital |
| 473 |
patties: |
| 474 |
type: integer |
| 475 |
vegetarian: |
| 476 |
type: boolean` |
| 477 |
|
| 478 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 479 |
require.NoError(t, err, "Failed to load spec") |
| 480 |
require.NotNil(t, doc, "Failed to load spec") |
| 481 |
|
| 482 |
v, errs := NewValidator( |
| 483 |
doc, |
| 484 |
config.WithCustomFormat("capital", func(v any) error { |
| 485 |
s, ok := v.(string) |
| 486 |
if !ok { |
| 487 |
return fmt.Errorf("expected string") |
| 488 |
} |
| 489 |
|
| 490 |
if s == "" { |
| 491 |
return nil |
| 492 |
} |
| 493 |
|
| 494 |
r := []rune(s)[0] |
| 495 |
|
| 496 |
if !unicode.IsUpper(r) { |
| 497 |
return fmt.Errorf("expected first latter to be uppercase") |
| 498 |
} |
| 499 |
|
| 500 |
return nil |
| 501 |
}), |
| 502 |
) |
| 503 |
require.Empty(t, errs, "Failed to build validator") |
| 504 |
require.NotNil(t, v, "Failed to build validator") |
| 505 |
|
| 506 |
v.GetRequestBodyValidator() |
| 507 |
|
| 508 |
body := map[string]interface{}{ |
| 509 |
"name": "big mac", |
| 510 |
"patties": 2, |
| 511 |
"vegetarian": true, |
| 512 |
} |
| 513 |
|
| 514 |
bodyBytes, _ := json.Marshal(body) |
| 515 |
|
| 516 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 517 |
bytes.NewBuffer(bodyBytes)) |
| 518 |
request.Header.Set("Content-Type", "application/json") |
| 519 |
|
| 520 |
valid, errors := v.ValidateHttpRequest(request) |
| 521 |
|
| 522 |
assert.True(t, valid) |
| 523 |
assert.Len(t, errors, 0) |
| 524 |
} |
| 525 |
|
| 526 |
func TestNewValidator_BadDoc(t *testing.T) { |
| 527 |
spec := `swagger: 2.0` |
| 528 |
|
| 529 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 530 |
|
| 531 |
_, errs := NewValidator(doc) |
| 532 |
|
| 533 |
assert.Len(t, errs, 1) |
| 534 |
} |
| 535 |
|
| 536 |
func TestNewValidator_ValidateHttpRequest_BadPath(t *testing.T) { |
| 537 |
spec := `openapi: 3.1.0 |
| 538 |
paths: |
| 539 |
/burgers/createBurger: |
| 540 |
post: |
| 541 |
requestBody: |
| 542 |
content: |
| 543 |
application/json: |
| 544 |
schema: |
| 545 |
type: object |
| 546 |
properties: |
| 547 |
name: |
| 548 |
type: string |
| 549 |
patties: |
| 550 |
type: integer |
| 551 |
vegetarian: |
| 552 |
type: boolean` |
| 553 |
|
| 554 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 555 |
|
| 556 |
v, _ := NewValidator(doc) |
| 557 |
|
| 558 |
body := map[string]interface{}{ |
| 559 |
"name": "Big Mac", |
| 560 |
"patties": 2, |
| 561 |
"vegetarian": true, |
| 562 |
} |
| 563 |
|
| 564 |
bodyBytes, _ := json.Marshal(body) |
| 565 |
|
| 566 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/I am a potato man", |
| 567 |
bytes.NewBuffer(bodyBytes)) |
| 568 |
request.Header.Set("Content-Type", "application/json") |
| 569 |
|
| 570 |
valid, errors := v.ValidateHttpRequest(request) |
| 571 |
|
| 572 |
assert.False(t, valid) |
| 573 |
assert.Len(t, errors, 1) |
| 574 |
assert.Equal(t, "POST Path '/I am a potato man' not found", errors[0].Message) |
| 575 |
} |
| 576 |
|
| 577 |
func TestNewValidator_ValidateHttpRequestSync_BadPath(t *testing.T) { |
| 578 |
spec := `openapi: 3.1.0 |
| 579 |
paths: |
| 580 |
/burgers/createBurger: |
| 581 |
post: |
| 582 |
requestBody: |
| 583 |
content: |
| 584 |
application/json: |
| 585 |
schema: |
| 586 |
type: object |
| 587 |
properties: |
| 588 |
name: |
| 589 |
type: string |
| 590 |
patties: |
| 591 |
type: integer |
| 592 |
vegetarian: |
| 593 |
type: boolean` |
| 594 |
|
| 595 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 596 |
|
| 597 |
v, _ := NewValidator(doc) |
| 598 |
|
| 599 |
body := map[string]interface{}{ |
| 600 |
"name": "Big Mac", |
| 601 |
"patties": 2, |
| 602 |
"vegetarian": true, |
| 603 |
} |
| 604 |
|
| 605 |
bodyBytes, _ := json.Marshal(body) |
| 606 |
|
| 607 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/I am a potato man", |
| 608 |
bytes.NewBuffer(bodyBytes)) |
| 609 |
request.Header.Set("Content-Type", "application/json") |
| 610 |
|
| 611 |
valid, errors := v.ValidateHttpRequestSync(request) |
| 612 |
|
| 613 |
assert.False(t, valid) |
| 614 |
assert.Len(t, errors, 1) |
| 615 |
assert.Equal(t, "POST Path '/I am a potato man' not found", errors[0].Message) |
| 616 |
} |
| 617 |
|
| 618 |
func TestNewValidator_ValidateHttpRequest_ValidPostSimpleSchema(t *testing.T) { |
| 619 |
spec := `openapi: 3.1.0 |
| 620 |
paths: |
| 621 |
/burgers/createBurger: |
| 622 |
post: |
| 623 |
requestBody: |
| 624 |
content: |
| 625 |
application/json: |
| 626 |
schema: |
| 627 |
type: object |
| 628 |
properties: |
| 629 |
name: |
| 630 |
type: string |
| 631 |
patties: |
| 632 |
type: integer |
| 633 |
vegetarian: |
| 634 |
type: boolean` |
| 635 |
|
| 636 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 637 |
|
| 638 |
v, _ := NewValidator(doc) |
| 639 |
|
| 640 |
body := map[string]interface{}{ |
| 641 |
"name": "Big Mac", |
| 642 |
"patties": 2, |
| 643 |
"vegetarian": true, |
| 644 |
} |
| 645 |
|
| 646 |
bodyBytes, _ := json.Marshal(body) |
| 647 |
|
| 648 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 649 |
bytes.NewBuffer(bodyBytes)) |
| 650 |
request.Header.Set("Content-Type", "application/json") |
| 651 |
|
| 652 |
valid, errors := v.ValidateHttpRequest(request) |
| 653 |
|
| 654 |
assert.True(t, valid) |
| 655 |
assert.Len(t, errors, 0) |
| 656 |
} |
| 657 |
|
| 658 |
func TestNewValidator_ValidateHttpRequestSync_ValidPostSimpleSchema(t *testing.T) { |
| 659 |
spec := `openapi: 3.1.0 |
| 660 |
paths: |
| 661 |
/burgers/createBurger: |
| 662 |
post: |
| 663 |
requestBody: |
| 664 |
content: |
| 665 |
application/json: |
| 666 |
schema: |
| 667 |
type: object |
| 668 |
properties: |
| 669 |
name: |
| 670 |
type: string |
| 671 |
patties: |
| 672 |
type: integer |
| 673 |
vegetarian: |
| 674 |
type: boolean` |
| 675 |
|
| 676 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 677 |
|
| 678 |
v, _ := NewValidator(doc) |
| 679 |
|
| 680 |
body := map[string]interface{}{ |
| 681 |
"name": "Big Mac", |
| 682 |
"patties": 2, |
| 683 |
"vegetarian": true, |
| 684 |
} |
| 685 |
|
| 686 |
bodyBytes, _ := json.Marshal(body) |
| 687 |
|
| 688 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 689 |
bytes.NewBuffer(bodyBytes)) |
| 690 |
request.Header.Set("Content-Type", "application/json") |
| 691 |
|
| 692 |
valid, errors := v.ValidateHttpRequestSync(request) |
| 693 |
|
| 694 |
assert.True(t, valid) |
| 695 |
assert.Len(t, errors, 0) |
| 696 |
} |
| 697 |
|
| 698 |
func TestNewValidator_ValidateHttpRequestSync_ValidPostSimpleSchema_FoundPath(t *testing.T) { |
| 699 |
spec := `openapi: 3.1.0 |
| 700 |
paths: |
| 701 |
/burgers/createBurger: |
| 702 |
post: |
| 703 |
requestBody: |
| 704 |
content: |
| 705 |
application/json: |
| 706 |
schema: |
| 707 |
type: object |
| 708 |
properties: |
| 709 |
name: |
| 710 |
type: string |
| 711 |
patties: |
| 712 |
type: integer |
| 713 |
vegetarian: |
| 714 |
type: boolean` |
| 715 |
|
| 716 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 717 |
|
| 718 |
v, _ := NewValidator(doc) |
| 719 |
|
| 720 |
body := map[string]interface{}{ |
| 721 |
"name": "Big Mac", |
| 722 |
"patties": 2, |
| 723 |
"vegetarian": true, |
| 724 |
} |
| 725 |
|
| 726 |
bodyBytes, _ := json.Marshal(body) |
| 727 |
|
| 728 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 729 |
bytes.NewBuffer(bodyBytes)) |
| 730 |
request.Header.Set("Content-Type", "application/json") |
| 731 |
|
| 732 |
valid, errors := v.ValidateHttpRequestSyncWithPathItem(request, &v3.PathItem{ |
| 733 |
Post: &v3.Operation{}, |
| 734 |
}, "/burgers/createBurger") |
| 735 |
|
| 736 |
assert.True(t, valid) |
| 737 |
assert.Len(t, errors, 0) |
| 738 |
} |
| 739 |
|
| 740 |
func TestNewValidator_slash_server_url(t *testing.T) { |
| 741 |
spec := `openapi: 3.1.0 |
| 742 |
servers: |
| 743 |
- url: / |
| 744 |
paths: |
| 745 |
/burgers/{burgerId}/locate: |
| 746 |
patch: |
| 747 |
operationId: locateBurger |
| 748 |
parameters: |
| 749 |
- name: burgerId |
| 750 |
in: path |
| 751 |
required: true |
| 752 |
schema: |
| 753 |
type: string |
| 754 |
format: uuid |
| 755 |
` |
| 756 |
|
| 757 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 758 |
require.NoError(t, err) |
| 759 |
|
| 760 |
request, _ := http.NewRequest(http.MethodPatch, "https://things.com/burgers/edd0189c-420b-489c-98f2-0facc5a26f3a/locate", nil) |
| 761 |
v, _ := NewValidator(doc) |
| 762 |
|
| 763 |
valid, errors := v.ValidateHttpRequest(request) |
| 764 |
|
| 765 |
assert.True(t, valid) |
| 766 |
assert.Len(t, errors, 0) |
| 767 |
} |
| 768 |
|
| 769 |
func TestNewValidator_ValidateHttpRequest_SetPath_ValidPostSimpleSchema(t *testing.T) { |
| 770 |
spec := `openapi: 3.1.0 |
| 771 |
paths: |
| 772 |
/burgers/createBurger: |
| 773 |
post: |
| 774 |
requestBody: |
| 775 |
content: |
| 776 |
application/json: |
| 777 |
schema: |
| 778 |
type: object |
| 779 |
properties: |
| 780 |
name: |
| 781 |
type: string |
| 782 |
patties: |
| 783 |
type: integer |
| 784 |
vegetarian: |
| 785 |
type: boolean` |
| 786 |
|
| 787 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 788 |
|
| 789 |
v, _ := NewValidator(doc) |
| 790 |
|
| 791 |
body := map[string]interface{}{ |
| 792 |
"name": "Big Mac", |
| 793 |
"patties": 2, |
| 794 |
"vegetarian": true, |
| 795 |
} |
| 796 |
|
| 797 |
bodyBytes, _ := json.Marshal(body) |
| 798 |
|
| 799 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 800 |
bytes.NewBuffer(bodyBytes)) |
| 801 |
request.Header.Set("Content-Type", "application/json") |
| 802 |
|
| 803 |
valid, errors := v.ValidateHttpRequest(request) |
| 804 |
|
| 805 |
assert.True(t, valid) |
| 806 |
assert.Len(t, errors, 0) |
| 807 |
} |
| 808 |
|
| 809 |
func TestNewValidator_ValidateHttpRequestSync_SetPath_ValidPostSimpleSchema(t *testing.T) { |
| 810 |
spec := `openapi: 3.1.0 |
| 811 |
paths: |
| 812 |
/burgers/createBurger: |
| 813 |
post: |
| 814 |
requestBody: |
| 815 |
content: |
| 816 |
application/json: |
| 817 |
schema: |
| 818 |
type: object |
| 819 |
properties: |
| 820 |
name: |
| 821 |
type: string |
| 822 |
patties: |
| 823 |
type: integer |
| 824 |
vegetarian: |
| 825 |
type: boolean` |
| 826 |
|
| 827 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 828 |
|
| 829 |
v, _ := NewValidator(doc) |
| 830 |
|
| 831 |
body := map[string]interface{}{ |
| 832 |
"name": "Big Mac", |
| 833 |
"patties": 2, |
| 834 |
"vegetarian": true, |
| 835 |
} |
| 836 |
|
| 837 |
bodyBytes, _ := json.Marshal(body) |
| 838 |
|
| 839 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 840 |
bytes.NewBuffer(bodyBytes)) |
| 841 |
request.Header.Set("Content-Type", "application/json") |
| 842 |
|
| 843 |
valid, errors := v.ValidateHttpRequestSync(request) |
| 844 |
|
| 845 |
assert.True(t, valid) |
| 846 |
assert.Len(t, errors, 0) |
| 847 |
} |
| 848 |
|
| 849 |
func TestNewValidator_ValidateHttpRequest_InvalidPostSchema(t *testing.T) { |
| 850 |
spec := `openapi: 3.1.0 |
| 851 |
paths: |
| 852 |
/burgers/createBurger: |
| 853 |
post: |
| 854 |
requestBody: |
| 855 |
content: |
| 856 |
application/json: |
| 857 |
schema: |
| 858 |
type: object |
| 859 |
properties: |
| 860 |
name: |
| 861 |
type: string |
| 862 |
patties: |
| 863 |
type: integer |
| 864 |
vegetarian: |
| 865 |
type: boolean` |
| 866 |
|
| 867 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 868 |
|
| 869 |
v, _ := NewValidator(doc) |
| 870 |
|
| 871 |
// mix up the primitives to fire two schema violations. |
| 872 |
body := map[string]interface{}{ |
| 873 |
"name": "Big Mac", |
| 874 |
"patties": false, // wrong. |
| 875 |
"vegetarian": false, |
| 876 |
} |
| 877 |
|
| 878 |
bodyBytes, _ := json.Marshal(body) |
| 879 |
|
| 880 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 881 |
bytes.NewBuffer(bodyBytes)) |
| 882 |
request.Header.Set("Content-Type", "application/json") |
| 883 |
|
| 884 |
valid, errors := v.ValidateHttpRequest(request) |
| 885 |
|
| 886 |
assert.False(t, valid) |
| 887 |
assert.Len(t, errors, 1) |
| 888 |
assert.Equal(t, "got boolean, want integer", errors[0].SchemaValidationErrors[0].Reason) |
| 889 |
} |
| 890 |
|
| 891 |
func TestNewValidator_ValidateHttpRequestSync_InvalidPostSchema(t *testing.T) { |
| 892 |
spec := `openapi: 3.1.0 |
| 893 |
paths: |
| 894 |
/burgers/createBurger: |
| 895 |
post: |
| 896 |
requestBody: |
| 897 |
content: |
| 898 |
application/json: |
| 899 |
schema: |
| 900 |
type: object |
| 901 |
properties: |
| 902 |
name: |
| 903 |
type: string |
| 904 |
patties: |
| 905 |
type: integer |
| 906 |
vegetarian: |
| 907 |
type: boolean` |
| 908 |
|
| 909 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 910 |
|
| 911 |
v, _ := NewValidator(doc) |
| 912 |
|
| 913 |
// mix up the primitives to fire two schema violations. |
| 914 |
body := map[string]interface{}{ |
| 915 |
"name": "Big Mac", |
| 916 |
"patties": false, // wrong. |
| 917 |
"vegetarian": false, |
| 918 |
} |
| 919 |
|
| 920 |
bodyBytes, _ := json.Marshal(body) |
| 921 |
|
| 922 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 923 |
bytes.NewBuffer(bodyBytes)) |
| 924 |
request.Header.Set("Content-Type", "application/json") |
| 925 |
|
| 926 |
valid, errors := v.ValidateHttpRequestSync(request) |
| 927 |
|
| 928 |
assert.False(t, valid) |
| 929 |
assert.Len(t, errors, 1) |
| 930 |
assert.Equal(t, "got boolean, want integer", errors[0].SchemaValidationErrors[0].Reason) |
| 931 |
} |
| 932 |
|
| 933 |
func TestNewValidator_ValidateHttpRequest_InvalidQuery(t *testing.T) { |
| 934 |
spec := `openapi: 3.1.0 |
| 935 |
paths: |
| 936 |
/burgers/createBurger: |
| 937 |
parameters: |
| 938 |
- in: query |
| 939 |
name: cheese |
| 940 |
required: true |
| 941 |
schema: |
| 942 |
type: string |
| 943 |
post: |
| 944 |
requestBody: |
| 945 |
content: |
| 946 |
application/json: |
| 947 |
schema: |
| 948 |
type: object |
| 949 |
properties: |
| 950 |
name: |
| 951 |
type: string |
| 952 |
patties: |
| 953 |
type: integer |
| 954 |
vegetarian: |
| 955 |
type: boolean` |
| 956 |
|
| 957 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 958 |
|
| 959 |
v, _ := NewValidator(doc) |
| 960 |
|
| 961 |
body := map[string]interface{}{ |
| 962 |
"name": "Big Mac", |
| 963 |
"patties": 2, // wrong. |
| 964 |
"vegetarian": false, |
| 965 |
} |
| 966 |
|
| 967 |
bodyBytes, _ := json.Marshal(body) |
| 968 |
|
| 969 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 970 |
bytes.NewBuffer(bodyBytes)) |
| 971 |
request.Header.Set("Content-Type", "application/json") |
| 972 |
|
| 973 |
valid, errors := v.ValidateHttpRequest(request) |
| 974 |
|
| 975 |
assert.False(t, valid) |
| 976 |
assert.Len(t, errors, 1) |
| 977 |
assert.Equal(t, "Query parameter 'cheese' is missing", errors[0].Message) |
| 978 |
} |
| 979 |
|
| 980 |
func TestNewValidator_ValidateHttpRequestSync_InvalidQuery(t *testing.T) { |
| 981 |
spec := `openapi: 3.1.0 |
| 982 |
paths: |
| 983 |
/burgers/createBurger: |
| 984 |
parameters: |
| 985 |
- in: query |
| 986 |
name: cheese |
| 987 |
required: true |
| 988 |
schema: |
| 989 |
type: string |
| 990 |
post: |
| 991 |
requestBody: |
| 992 |
content: |
| 993 |
application/json: |
| 994 |
schema: |
| 995 |
type: object |
| 996 |
properties: |
| 997 |
name: |
| 998 |
type: string |
| 999 |
patties: |
| 1000 |
type: integer |
| 1001 |
vegetarian: |
| 1002 |
type: boolean` |
| 1003 |
|
| 1004 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 1005 |
|
| 1006 |
v, _ := NewValidator(doc) |
| 1007 |
|
| 1008 |
body := map[string]interface{}{ |
| 1009 |
"name": "Big Mac", |
| 1010 |
"patties": 2, // wrong. |
| 1011 |
"vegetarian": false, |
| 1012 |
} |
| 1013 |
|
| 1014 |
bodyBytes, _ := json.Marshal(body) |
| 1015 |
|
| 1016 |
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", |
| 1017 |
bytes.NewBuffer(bodyBytes)) |
| 1018 |
request.Header.Set("Content-Type", "application/json") |
| 1019 |
|
| 1020 |
valid, errors := v.ValidateHttpRequestSync(request) |
| 1021 |
|
| 1022 |
assert.False(t, valid) |
| 1023 |
assert.Len(t, errors, 1) |
| 1024 |
assert.Equal(t, "Query parameter 'cheese' is missing", errors[0].Message) |
| 1025 |
} |
| 1026 |
|
| 1027 |
var petstoreBytes []byte |
| 1028 |
|
| 1029 |
func init() { |
| 1030 |
petstoreBytes, _ = os.ReadFile("test_specs/petstorev3.json") |
| 1031 |
} |
| 1032 |
|
| 1033 |
func TestNewValidator_PetStore_MissingContentType(t *testing.T) { |
| 1034 |
// create a new document from the petstore spec |
| 1035 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1036 |
|
| 1037 |
// create a doc |
| 1038 |
v, _ := NewValidator(doc) |
| 1039 |
|
| 1040 |
// create a pet |
| 1041 |
body := map[string]interface{}{ |
| 1042 |
"id": 123, |
| 1043 |
"name": "cotton", |
| 1044 |
"category": map[string]interface{}{ |
| 1045 |
"id": 123, |
| 1046 |
"name": "dogs", |
| 1047 |
}, |
| 1048 |
"photoUrls": []string{"https://example.com"}, |
| 1049 |
} |
| 1050 |
|
| 1051 |
// marshal the body into bytes. |
| 1052 |
bodyBytes, _ := json.Marshal(body) |
| 1053 |
|
| 1054 |
// create a new put request |
| 1055 |
request, _ := http.NewRequest(http.MethodPut, "https://hyperspace-superherbs.com/pet", |
| 1056 |
bytes.NewBuffer(bodyBytes)) |
| 1057 |
request.Header.Set("Content-Type", "application/json") |
| 1058 |
|
| 1059 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1060 |
res := httptest.NewRecorder() |
| 1061 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1062 |
w.Header().Set(helpers.ContentTypeHeader, "application/not-json") |
| 1063 |
w.WriteHeader(http.StatusOK) |
| 1064 |
_, _ = w.Write(bodyBytes) |
| 1065 |
} |
| 1066 |
|
| 1067 |
// fire the request |
| 1068 |
handler(res, request) |
| 1069 |
|
| 1070 |
// validate the response (should be clean) |
| 1071 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1072 |
|
| 1073 |
// should all be perfectly valid. |
| 1074 |
assert.False(t, valid) |
| 1075 |
assert.Len(t, errors, 1) |
| 1076 |
assert.Equal(t, "PUT / 200 operation response content type 'application/not-json' does not exist", |
| 1077 |
errors[0].Message) |
| 1078 |
|
| 1079 |
assert.Equal(t, "The content type 'application/not-json' of the PUT response received "+ |
| 1080 |
"has not been defined, it's an unknown type", |
| 1081 |
errors[0].Reason) |
| 1082 |
} |
| 1083 |
|
| 1084 |
func TestNewValidator_PetStore_PetPost200_Valid_PathPreset(t *testing.T) { |
| 1085 |
// create a new document from the petstore spec |
| 1086 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1087 |
|
| 1088 |
// create a doc |
| 1089 |
v, _ := NewValidator(doc) |
| 1090 |
|
| 1091 |
// create a pet |
| 1092 |
body := map[string]interface{}{ |
| 1093 |
"id": 123, |
| 1094 |
"name": "cotton", |
| 1095 |
"category": map[string]interface{}{ |
| 1096 |
"id": 123, |
| 1097 |
"name": "dogs", |
| 1098 |
}, |
| 1099 |
"photoUrls": []string{"https://example.com"}, |
| 1100 |
} |
| 1101 |
|
| 1102 |
// marshal the body into bytes. |
| 1103 |
bodyBytes, _ := json.Marshal(body) |
| 1104 |
|
| 1105 |
// create a new put request |
| 1106 |
request, _ := http.NewRequest(http.MethodPut, "https://hyperspace-superherbs.com/pet", |
| 1107 |
bytes.NewBuffer(bodyBytes)) |
| 1108 |
request.Header.Set("Content-Type", "application/json") |
| 1109 |
|
| 1110 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1111 |
res := httptest.NewRecorder() |
| 1112 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1113 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1114 |
w.WriteHeader(http.StatusOK) |
| 1115 |
_, _ = w.Write(bodyBytes) |
| 1116 |
} |
| 1117 |
|
| 1118 |
// fire the request |
| 1119 |
handler(res, request) |
| 1120 |
|
| 1121 |
// validate the response (should be clean) |
| 1122 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1123 |
|
| 1124 |
// should all be perfectly valid. |
| 1125 |
assert.True(t, valid) |
| 1126 |
assert.Len(t, errors, 0) |
| 1127 |
} |
| 1128 |
|
| 1129 |
func TestNewValidator_PetStore_PetPost200_Valid(t *testing.T) { |
| 1130 |
// create a new document from the petstore spec |
| 1131 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1132 |
|
| 1133 |
// create a doc |
| 1134 |
v, _ := NewValidator(doc) |
| 1135 |
|
| 1136 |
// create a pet |
| 1137 |
body := map[string]interface{}{ |
| 1138 |
"id": 123, |
| 1139 |
"name": "cotton", |
| 1140 |
"category": map[string]interface{}{ |
| 1141 |
"id": 123, |
| 1142 |
"name": "dogs", |
| 1143 |
}, |
| 1144 |
"photoUrls": []string{"https://example.com"}, |
| 1145 |
} |
| 1146 |
|
| 1147 |
// marshal the body into bytes. |
| 1148 |
bodyBytes, _ := json.Marshal(body) |
| 1149 |
|
| 1150 |
// create a new put request |
| 1151 |
request, _ := http.NewRequest(http.MethodPut, "https://hyperspace-superherbs.com/pet", |
| 1152 |
bytes.NewBuffer(bodyBytes)) |
| 1153 |
request.Header.Set("Content-Type", "application/json") |
| 1154 |
|
| 1155 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1156 |
res := httptest.NewRecorder() |
| 1157 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1158 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1159 |
w.WriteHeader(http.StatusOK) |
| 1160 |
_, _ = w.Write(bodyBytes) |
| 1161 |
} |
| 1162 |
|
| 1163 |
// fire the request |
| 1164 |
handler(res, request) |
| 1165 |
|
| 1166 |
// validate the response (should be clean) |
| 1167 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1168 |
|
| 1169 |
// should all be perfectly valid. |
| 1170 |
assert.True(t, valid) |
| 1171 |
assert.Len(t, errors, 0) |
| 1172 |
} |
| 1173 |
|
| 1174 |
func TestNewValidator_PetStore_PetPost200_Invalid(t *testing.T) { |
| 1175 |
// create a new document from the petstore spec |
| 1176 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1177 |
|
| 1178 |
// create a doc |
| 1179 |
v, _ := NewValidator(doc) |
| 1180 |
|
| 1181 |
// create a pet, but is missing the photoUrls field |
| 1182 |
body := map[string]interface{}{ |
| 1183 |
"id": 123, |
| 1184 |
"name": "cotton", |
| 1185 |
"category": map[string]interface{}{ |
| 1186 |
"id": 123, |
| 1187 |
"name": "dogs", |
| 1188 |
}, |
| 1189 |
} |
| 1190 |
|
| 1191 |
// marshal the body into bytes. |
| 1192 |
bodyBytes, _ := json.Marshal(body) |
| 1193 |
|
| 1194 |
// create a new put request |
| 1195 |
request, _ := http.NewRequest(http.MethodPost, "https://hyperspace-superherbs.com/pet", |
| 1196 |
bytes.NewBuffer(bodyBytes)) |
| 1197 |
request.Header.Set("Content-Type", "application/json") |
| 1198 |
|
| 1199 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1200 |
res := httptest.NewRecorder() |
| 1201 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1202 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1203 |
w.WriteHeader(http.StatusProxyAuthRequired) // this is not defined by the contract, so it should fail. |
| 1204 |
_, _ = w.Write(bodyBytes) |
| 1205 |
} |
| 1206 |
|
| 1207 |
// fire the request |
| 1208 |
handler(res, request) |
| 1209 |
|
| 1210 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1211 |
|
| 1212 |
// we have a schema violation, and a response code violation, our validator should have picked them |
| 1213 |
// both up. |
| 1214 |
assert.False(t, valid) |
| 1215 |
assert.Len(t, errors, 2) |
| 1216 |
|
| 1217 |
// check errors |
| 1218 |
for i := range errors { |
| 1219 |
if errors[i].SchemaValidationErrors != nil { |
| 1220 |
assert.Equal(t, "missing property 'photoUrls'", errors[i].SchemaValidationErrors[0].Reason) |
| 1221 |
} else { |
| 1222 |
assert.Equal(t, "POST operation request response code '407' does not exist", errors[i].Message) |
| 1223 |
} |
| 1224 |
} |
| 1225 |
} |
| 1226 |
|
| 1227 |
func TestNewValidator_PetStore_PetFindByStatusGet200_Valid(t *testing.T) { |
| 1228 |
// create a new document from the petstore spec |
| 1229 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1230 |
|
| 1231 |
// create a doc |
| 1232 |
v, _ := NewValidator(doc) |
| 1233 |
|
| 1234 |
// create a pet |
| 1235 |
body := map[string]interface{}{ |
| 1236 |
"id": 123, |
| 1237 |
"name": "cotton", |
| 1238 |
"category": map[string]interface{}{ |
| 1239 |
"id": 123, |
| 1240 |
"name": "dogs", |
| 1241 |
}, |
| 1242 |
"photoUrls": []string{"https://example.com"}, |
| 1243 |
} |
| 1244 |
|
| 1245 |
// marshal the body into bytes. |
| 1246 |
bodyBytes, _ := json.Marshal([]interface{}{body}) // operation returns an array of pets |
| 1247 |
|
| 1248 |
// create a new put request |
| 1249 |
request, _ := http.NewRequest(http.MethodGet, |
| 1250 |
"https://hyperspace-superherbs.com/pet/findByStatus?status=sold", nil) |
| 1251 |
request.Header.Set("Content-Type", "application/json") |
| 1252 |
|
| 1253 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1254 |
res := httptest.NewRecorder() |
| 1255 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1256 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1257 |
w.WriteHeader(http.StatusOK) |
| 1258 |
_, _ = w.Write(bodyBytes) |
| 1259 |
} |
| 1260 |
|
| 1261 |
// fire the request |
| 1262 |
handler(res, request) |
| 1263 |
|
| 1264 |
// validate the response (should be clean) |
| 1265 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1266 |
|
| 1267 |
// should all be perfectly valid. |
| 1268 |
assert.True(t, valid) |
| 1269 |
assert.Len(t, errors, 0) |
| 1270 |
} |
| 1271 |
|
| 1272 |
func TestNewValidator_PetStore_PetFindByStatusGet200_BadEnum(t *testing.T) { |
| 1273 |
// create a new document from the petstore spec |
| 1274 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1275 |
|
| 1276 |
// create a doc |
| 1277 |
v, _ := NewValidator(doc) |
| 1278 |
|
| 1279 |
// create a pet |
| 1280 |
body := map[string]interface{}{ |
| 1281 |
"id": 123, |
| 1282 |
"name": "cotton", |
| 1283 |
"category": map[string]interface{}{ |
| 1284 |
"id": 123, |
| 1285 |
"name": "dogs", |
| 1286 |
}, |
| 1287 |
"photoUrls": []string{"https://example.com"}, |
| 1288 |
} |
| 1289 |
|
| 1290 |
// marshal the body into bytes. |
| 1291 |
bodyBytes, _ := json.Marshal([]interface{}{body}) // operation returns an array of pets |
| 1292 |
|
| 1293 |
// create a new put request |
| 1294 |
request, _ := http.NewRequest(http.MethodGet, |
| 1295 |
"https://hyperspace-superherbs.com/pet/findByStatus?status=invalidEnum", nil) // enum is invalid |
| 1296 |
request.Header.Set("Content-Type", "application/json") |
| 1297 |
|
| 1298 |
// simulate a request/response, in this case the contract returns a 200 with a pet |
| 1299 |
res := httptest.NewRecorder() |
| 1300 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1301 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1302 |
w.Header().Set("Herbs-And-Spice", helpers.JSONContentType) |
| 1303 |
w.WriteHeader(http.StatusOK) |
| 1304 |
_, _ = w.Write(bodyBytes) |
| 1305 |
} |
| 1306 |
|
| 1307 |
// fire the request |
| 1308 |
handler(res, request) |
| 1309 |
|
| 1310 |
// validate the response (should be clean) |
| 1311 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1312 |
|
| 1313 |
// should all be perfectly valid. |
| 1314 |
assert.False(t, valid) |
| 1315 |
assert.Len(t, errors, 1) |
| 1316 |
assert.Equal(t, "Query parameter 'status' does not match allowed values", errors[0].Message) |
| 1317 |
assert.Equal(t, "Instead of 'invalidEnum', use one of the allowed values: 'available, pending, sold'", errors[0].HowToFix) |
| 1318 |
} |
| 1319 |
|
| 1320 |
func TestNewValidator_PetStore_PetFindByTagsGet200_Valid(t *testing.T) { |
| 1321 |
// create a new document from the petstore spec |
| 1322 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1323 |
|
| 1324 |
// create a doc |
| 1325 |
v, _ := NewValidator(doc) |
| 1326 |
|
| 1327 |
// create a pet |
| 1328 |
body := map[string]interface{}{ |
| 1329 |
"id": 123, |
| 1330 |
"name": "cotton", |
| 1331 |
"category": map[string]interface{}{ |
| 1332 |
"id": 123, |
| 1333 |
"name": "dogs", |
| 1334 |
}, |
| 1335 |
"photoUrls": []string{"https://example.com"}, |
| 1336 |
} |
| 1337 |
|
| 1338 |
// marshal the body into bytes. |
| 1339 |
bodyBytes, _ := json.Marshal([]interface{}{body}) // operation returns an array of pets |
| 1340 |
|
| 1341 |
// create a new put request |
| 1342 |
request, _ := http.NewRequest(http.MethodGet, |
| 1343 |
"https://hyperspace-superherbs.com/pet/findByTags?tags=fuzzy&tags=wuzzy", nil) |
| 1344 |
request.Header.Set("Content-Type", "application/json") |
| 1345 |
|
| 1346 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1347 |
res := httptest.NewRecorder() |
| 1348 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1349 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1350 |
w.WriteHeader(http.StatusOK) |
| 1351 |
_, _ = w.Write(bodyBytes) |
| 1352 |
} |
| 1353 |
|
| 1354 |
// fire the request |
| 1355 |
handler(res, request) |
| 1356 |
|
| 1357 |
// validate the response (should be clean) |
| 1358 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1359 |
|
| 1360 |
// should all be perfectly valid. |
| 1361 |
assert.True(t, valid) |
| 1362 |
assert.Len(t, errors, 0) |
| 1363 |
} |
| 1364 |
|
| 1365 |
func TestNewValidator_PetStore_PetFindByTagsGet200_InvalidExplode(t *testing.T) { |
| 1366 |
// create a new document from the petstore spec |
| 1367 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1368 |
|
| 1369 |
// create a doc |
| 1370 |
v, _ := NewValidator(doc) |
| 1371 |
|
| 1372 |
// create a pet |
| 1373 |
body := map[string]interface{}{ |
| 1374 |
"id": 123, |
| 1375 |
"name": "cotton", |
| 1376 |
"category": map[string]interface{}{ |
| 1377 |
"id": 123, |
| 1378 |
"name": "dogs", |
| 1379 |
}, |
| 1380 |
"photoUrls": []string{"https://example.com"}, |
| 1381 |
} |
| 1382 |
|
| 1383 |
// marshal the body into bytes. |
| 1384 |
bodyBytes, _ := json.Marshal([]interface{}{body}) // operation returns an array of pets |
| 1385 |
|
| 1386 |
// create a new put request |
| 1387 |
request, _ := http.NewRequest(http.MethodGet, |
| 1388 |
"https://hyperspace-superherbs.com/pet/findByTags?tags=fuzzy,wuzzy", nil) |
| 1389 |
request.Header.Set("Content-Type", "application/json") |
| 1390 |
|
| 1391 |
// simulate a request/response |
| 1392 |
res := httptest.NewRecorder() |
| 1393 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1394 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1395 |
w.WriteHeader(http.StatusOK) |
| 1396 |
_, _ = w.Write(bodyBytes) |
| 1397 |
} |
| 1398 |
|
| 1399 |
// fire the request |
| 1400 |
handler(res, request) |
| 1401 |
|
| 1402 |
// validate the response |
| 1403 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1404 |
|
| 1405 |
// will fail. |
| 1406 |
assert.False(t, valid) |
| 1407 |
assert.Len(t, errors, 2) // will fire allow reserved error, and explode error. |
| 1408 |
} |
| 1409 |
|
| 1410 |
func TestNewValidator_PetStore_PetGet200_Valid(t *testing.T) { |
| 1411 |
// create a new document from the petstore spec |
| 1412 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1413 |
|
| 1414 |
// create a doc |
| 1415 |
v, _ := NewValidator(doc) |
| 1416 |
|
| 1417 |
// create a pet |
| 1418 |
body := map[string]interface{}{ |
| 1419 |
"id": 123, |
| 1420 |
"name": "cotton", |
| 1421 |
"category": map[string]interface{}{ |
| 1422 |
"id": 123, |
| 1423 |
"name": "dogs", |
| 1424 |
}, |
| 1425 |
"photoUrls": []string{"https://example.com"}, |
| 1426 |
} |
| 1427 |
|
| 1428 |
// marshal the body into bytes. |
| 1429 |
bodyBytes, _ := json.Marshal(body) // operation returns pet |
| 1430 |
|
| 1431 |
// create a new put request |
| 1432 |
request, _ := http.NewRequest(http.MethodGet, |
| 1433 |
"https://hyperspace-superherbs.com/pet/12345", nil) |
| 1434 |
request.Header.Set("Content-Type", "application/json") |
| 1435 |
request.Header.Set("api_key", "12345") |
| 1436 |
|
| 1437 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1438 |
res := httptest.NewRecorder() |
| 1439 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1440 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1441 |
w.WriteHeader(http.StatusOK) |
| 1442 |
_, _ = w.Write(bodyBytes) |
| 1443 |
} |
| 1444 |
|
| 1445 |
// fire the request |
| 1446 |
handler(res, request) |
| 1447 |
|
| 1448 |
// validate the response |
| 1449 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1450 |
|
| 1451 |
assert.True(t, valid) |
| 1452 |
assert.Len(t, errors, 0) |
| 1453 |
} |
| 1454 |
|
| 1455 |
func TestNewValidator_PetStore_PetGet200_PathNotFound(t *testing.T) { |
| 1456 |
// create a new document from the petstore spec |
| 1457 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1458 |
|
| 1459 |
// create a doc |
| 1460 |
v, _ := NewValidator(doc) |
| 1461 |
|
| 1462 |
// create a pet |
| 1463 |
body := map[string]interface{}{ |
| 1464 |
"id": 123, |
| 1465 |
"name": "cotton", |
| 1466 |
"category": map[string]interface{}{ |
| 1467 |
"id": 123, |
| 1468 |
"name": "dogs", |
| 1469 |
}, |
| 1470 |
"photoUrls": []string{"https://example.com"}, |
| 1471 |
} |
| 1472 |
|
| 1473 |
// marshal the body into bytes. |
| 1474 |
bodyBytes, _ := json.Marshal(body) // operation returns pet |
| 1475 |
|
| 1476 |
// create a new put request |
| 1477 |
request, _ := http.NewRequest(http.MethodGet, |
| 1478 |
"https://hyperspace-superherbs.com/pet/IamNotANumber", nil) |
| 1479 |
request.Header.Set("Content-Type", "application/json") |
| 1480 |
|
| 1481 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1482 |
res := httptest.NewRecorder() |
| 1483 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1484 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1485 |
w.WriteHeader(http.StatusOK) |
| 1486 |
_, _ = w.Write(bodyBytes) |
| 1487 |
} |
| 1488 |
|
| 1489 |
// fire the request |
| 1490 |
handler(res, request) |
| 1491 |
|
| 1492 |
// validate the response |
| 1493 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1494 |
|
| 1495 |
assert.False(t, valid) |
| 1496 |
// Note: /pet/{petId} allows api_key OR petstore_auth (OAuth2). Since OAuth2 is not validated, |
| 1497 |
// security passes. Only the path parameter validation fails. |
| 1498 |
assert.Len(t, errors, 1) |
| 1499 |
assert.Equal(t, "Path parameter 'petId' is not a valid integer", errors[0].Message) |
| 1500 |
} |
| 1501 |
|
| 1502 |
func TestNewValidator_PetStore_PetGet200(t *testing.T) { |
| 1503 |
// create a new document from the petstore spec |
| 1504 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1505 |
|
| 1506 |
// create a doc |
| 1507 |
v, _ := NewValidator(doc) |
| 1508 |
|
| 1509 |
// create a new put request |
| 1510 |
request, _ := http.NewRequest(http.MethodGet, |
| 1511 |
"https://hyperspace-superherbs.com/pet/112233", nil) |
| 1512 |
request.Header.Set("Content-Type", "application/json") |
| 1513 |
request.Header.Set("api_key", "12345") |
| 1514 |
|
| 1515 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1516 |
res := httptest.NewRecorder() |
| 1517 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1518 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1519 |
w.WriteHeader(http.StatusOK) |
| 1520 |
|
| 1521 |
// create a pet |
| 1522 |
body := map[string]interface{}{ |
| 1523 |
"id": 123, |
| 1524 |
"name": "cotton", |
| 1525 |
"category": map[string]interface{}{ |
| 1526 |
"id": 123, |
| 1527 |
"name": "dogs", |
| 1528 |
}, |
| 1529 |
"photoUrls": []string{"https://example.com"}, |
| 1530 |
} |
| 1531 |
|
| 1532 |
// marshal the body into bytes. |
| 1533 |
bodyBytes, _ := json.Marshal(body) // operation returns pet |
| 1534 |
|
| 1535 |
_, _ = w.Write(bodyBytes) |
| 1536 |
} |
| 1537 |
|
| 1538 |
// fire the request |
| 1539 |
handler(res, request) |
| 1540 |
|
| 1541 |
// validate the response |
| 1542 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1543 |
|
| 1544 |
assert.True(t, valid) |
| 1545 |
assert.Len(t, errors, 0) |
| 1546 |
} |
| 1547 |
|
| 1548 |
func TestNewValidator_PetStore_PetGet200_ServerBadMediaType(t *testing.T) { |
| 1549 |
// create a new document from the petstore spec |
| 1550 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1551 |
|
| 1552 |
// create a doc |
| 1553 |
v, _ := NewValidator(doc) |
| 1554 |
|
| 1555 |
// create a new put request |
| 1556 |
request, _ := http.NewRequest(http.MethodGet, |
| 1557 |
"https://hyperspace-superherbs.com/pet/112233", nil) |
| 1558 |
request.Header.Set("Content-Type", "application/json") |
| 1559 |
request.Header.Set("api_key", "12345") |
| 1560 |
|
| 1561 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1562 |
res := httptest.NewRecorder() |
| 1563 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1564 |
w.Header().Set(helpers.ContentTypeHeader, "hot-diggity/coffee; charset=cakes") // wut? |
| 1565 |
w.WriteHeader(http.StatusOK) |
| 1566 |
|
| 1567 |
// create a pet |
| 1568 |
body := map[string]interface{}{ |
| 1569 |
"id": 123, |
| 1570 |
"name": "cotton", |
| 1571 |
|
| 1572 |
"category": map[string]interface{}{ |
| 1573 |
"id": 123, |
| 1574 |
"name": "dogs", |
| 1575 |
}, |
| 1576 |
"photoUrls": []string{"https://example.com"}, |
| 1577 |
} |
| 1578 |
|
| 1579 |
// marshal the body into bytes. |
| 1580 |
bodyBytes, _ := json.Marshal(body) // operation returns pet |
| 1581 |
|
| 1582 |
_, _ = w.Write(bodyBytes) |
| 1583 |
} |
| 1584 |
|
| 1585 |
// fire the request |
| 1586 |
handler(res, request) |
| 1587 |
|
| 1588 |
// validate the response |
| 1589 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1590 |
|
| 1591 |
assert.False(t, valid) |
| 1592 |
assert.Len(t, errors, 1) |
| 1593 |
assert.Equal(t, "GET / 200 operation response content type 'hot-diggity/coffee' does not exist", errors[0].Message) |
| 1594 |
} |
| 1595 |
|
| 1596 |
func TestNewValidator_PetStore_PetWithIdPost200_Missing200(t *testing.T) { |
| 1597 |
// create a new document from the petstore spec |
| 1598 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1599 |
|
| 1600 |
// create a doc |
| 1601 |
v, _ := NewValidator(doc) |
| 1602 |
|
| 1603 |
// create a new put request |
| 1604 |
request, _ := http.NewRequest(http.MethodPost, |
| 1605 |
"https://hyperspace-superherbs.com/pet/112233?name=peter&query=thing", nil) |
| 1606 |
request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1607 |
|
| 1608 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1609 |
res := httptest.NewRecorder() |
| 1610 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1611 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1612 |
w.WriteHeader(http.StatusOK) |
| 1613 |
} |
| 1614 |
|
| 1615 |
// fire the request |
| 1616 |
handler(res, request) |
| 1617 |
|
| 1618 |
// validate the response |
| 1619 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1620 |
|
| 1621 |
assert.False(t, valid) |
| 1622 |
assert.Len(t, errors, 1) |
| 1623 |
assert.Equal(t, "POST operation request response code '200' does not exist", errors[0].Message) |
| 1624 |
} |
| 1625 |
|
| 1626 |
func TestNewValidator_PetStore_UploadImage200_InvalidRequestBodyType(t *testing.T) { |
| 1627 |
// create a new document from the petstore spec |
| 1628 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1629 |
|
| 1630 |
// create a doc |
| 1631 |
v, _ := NewValidator(doc) |
| 1632 |
|
| 1633 |
// create a new put request |
| 1634 |
request, _ := http.NewRequest(http.MethodPost, |
| 1635 |
"https://hyperspace-superherbs.com/pet/112233/uploadImage?additionalMetadata=blem", nil) |
| 1636 |
request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1637 |
|
| 1638 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1639 |
res := httptest.NewRecorder() |
| 1640 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1641 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1642 |
w.WriteHeader(http.StatusOK) |
| 1643 |
// forget to write an API response |
| 1644 |
} |
| 1645 |
|
| 1646 |
// fire the request |
| 1647 |
handler(res, request) |
| 1648 |
|
| 1649 |
// validate the response |
| 1650 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1651 |
|
| 1652 |
assert.False(t, valid) |
| 1653 |
assert.Len(t, errors, 1) |
| 1654 |
} |
| 1655 |
|
| 1656 |
func TestNewValidator_PetStore_UploadImage200_Valid(t *testing.T) { |
| 1657 |
// create a new document from the petstore spec |
| 1658 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1659 |
|
| 1660 |
// create a doc |
| 1661 |
v, _ := NewValidator(doc) |
| 1662 |
|
| 1663 |
// create a new put request |
| 1664 |
request, _ := http.NewRequest(http.MethodPost, |
| 1665 |
"https://hyperspace-superherbs.com/pet/112233/uploadImage?additionalMetadata=blem", nil) |
| 1666 |
request.Header.Set(helpers.ContentTypeHeader, "application/octet-stream") |
| 1667 |
|
| 1668 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1669 |
res := httptest.NewRecorder() |
| 1670 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1671 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1672 |
w.WriteHeader(http.StatusOK) |
| 1673 |
|
| 1674 |
// create an API response |
| 1675 |
body := map[string]interface{}{ |
| 1676 |
"code": 200, |
| 1677 |
"type": "herbs", |
| 1678 |
"message": "smoke them every day.", |
| 1679 |
} |
| 1680 |
|
| 1681 |
// marshal the body into bytes. |
| 1682 |
bodyBytes, _ := json.Marshal(body) // operation returns APIResponse |
| 1683 |
|
| 1684 |
_, _ = w.Write(bodyBytes) |
| 1685 |
} |
| 1686 |
|
| 1687 |
// fire the request |
| 1688 |
handler(res, request) |
| 1689 |
|
| 1690 |
// validate the response |
| 1691 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1692 |
|
| 1693 |
assert.True(t, valid) |
| 1694 |
assert.Len(t, errors, 0) |
| 1695 |
} |
| 1696 |
|
| 1697 |
func TestNewValidator_PetStore_UploadImage200_InvalidAPIResponse(t *testing.T) { |
| 1698 |
// create a new document from the petstore spec |
| 1699 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1700 |
|
| 1701 |
// create a doc |
| 1702 |
v, _ := NewValidator(doc) |
| 1703 |
|
| 1704 |
// create a new put request |
| 1705 |
request, _ := http.NewRequest(http.MethodPost, |
| 1706 |
"https://hyperspace-superherbs.com/pet/112233/uploadImage?additionalMetadata=blem", nil) |
| 1707 |
request.Header.Set(helpers.ContentTypeHeader, "application/octet-stream") |
| 1708 |
|
| 1709 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1710 |
res := httptest.NewRecorder() |
| 1711 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1712 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1713 |
w.WriteHeader(http.StatusOK) |
| 1714 |
|
| 1715 |
// create an API response |
| 1716 |
body := map[string]interface{}{ |
| 1717 |
"code": 200, |
| 1718 |
"type": false, |
| 1719 |
"message": "smoke them every day.", |
| 1720 |
} |
| 1721 |
|
| 1722 |
// marshal the body into bytes. |
| 1723 |
bodyBytes, _ := json.Marshal(body) // operation returns APIResponse |
| 1724 |
|
| 1725 |
_, _ = w.Write(bodyBytes) |
| 1726 |
} |
| 1727 |
|
| 1728 |
// fire the request |
| 1729 |
handler(res, request) |
| 1730 |
|
| 1731 |
// validate the response |
| 1732 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1733 |
|
| 1734 |
assert.False(t, valid) |
| 1735 |
assert.Len(t, errors, 1) |
| 1736 |
assert.Equal(t, "200 response body for '/pet/112233/uploadImage' failed to validate schema", errors[0].Message) |
| 1737 |
} |
| 1738 |
|
| 1739 |
func TestNewValidator_CareRequest_WrongContentType(t *testing.T) { |
| 1740 |
careRequestBytes, _ := os.ReadFile("test_specs/care_request.yaml") |
| 1741 |
doc, _ := libopenapi.NewDocument(careRequestBytes) |
| 1742 |
|
| 1743 |
// create a doc |
| 1744 |
v, _ := NewValidator(doc) |
| 1745 |
|
| 1746 |
// create a new put request |
| 1747 |
request, _ := http.NewRequest(http.MethodGet, |
| 1748 |
"https://hyperspace-superherbs.com/requests/d4bc1a0c-c4ee-4be5-9281-26b1a041634d", nil) |
| 1749 |
request.Header.Set("Content-Type", "application/json") |
| 1750 |
|
| 1751 |
// simulate a request/response, |
| 1752 |
res := httptest.NewRecorder() |
| 1753 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1754 |
w.Header().Set(helpers.ContentTypeHeader, "application/not-json") |
| 1755 |
w.WriteHeader(http.StatusOK) |
| 1756 |
|
| 1757 |
// create a CareRequest |
| 1758 |
body := map[string]interface{}{ |
| 1759 |
"id": "d4bc1a0c-c4ee-4be5-9281-26b1a041634d", |
| 1760 |
"status": "active", |
| 1761 |
} |
| 1762 |
|
| 1763 |
// marshal the body into bytes. |
| 1764 |
bodyBytes, _ := json.Marshal(body) |
| 1765 |
|
| 1766 |
_, _ = w.Write(bodyBytes) |
| 1767 |
} |
| 1768 |
|
| 1769 |
// fire the request |
| 1770 |
handler(res, request) |
| 1771 |
|
| 1772 |
// validate the response |
| 1773 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1774 |
|
| 1775 |
assert.False(t, valid) |
| 1776 |
assert.Len(t, errors, 1) |
| 1777 |
assert.Equal(t, "GET / 200 operation response content type 'application/not-json' does not exist", |
| 1778 |
errors[0].Message) |
| 1779 |
|
| 1780 |
assert.Equal(t, "The content type 'application/not-json' "+ |
| 1781 |
"of the GET response received has not been defined, it's an unknown type", |
| 1782 |
errors[0].Reason) |
| 1783 |
} |
| 1784 |
|
| 1785 |
func TestNewValidator_PetStore_InvalidPath_Response(t *testing.T) { |
| 1786 |
// create a new document from the petstore spec |
| 1787 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1788 |
|
| 1789 |
// create a doc |
| 1790 |
v, _ := NewValidator(doc) |
| 1791 |
|
| 1792 |
// create a new put request |
| 1793 |
request, _ := http.NewRequest(http.MethodPost, |
| 1794 |
"https://hyperspace-superherbs.com/missing", nil) |
| 1795 |
request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1796 |
|
| 1797 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1798 |
res := httptest.NewRecorder() |
| 1799 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1800 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1801 |
w.WriteHeader(http.StatusOK) |
| 1802 |
} |
| 1803 |
|
| 1804 |
// fire the request |
| 1805 |
handler(res, request) |
| 1806 |
|
| 1807 |
// validate the response |
| 1808 |
valid, errors := v.ValidateHttpResponse(request, res.Result()) |
| 1809 |
|
| 1810 |
assert.False(t, valid) |
| 1811 |
assert.Len(t, errors, 1) |
| 1812 |
assert.Equal(t, "POST Path '/missing' not found", errors[0].Message) |
| 1813 |
} |
| 1814 |
|
| 1815 |
func TestNewValidator_PetStore_InvalidPath_RequestResponse(t *testing.T) { |
| 1816 |
// create a new document from the petstore spec |
| 1817 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1818 |
|
| 1819 |
// create a doc |
| 1820 |
v, _ := NewValidator(doc) |
| 1821 |
|
| 1822 |
// create a new put request with an invalid path |
| 1823 |
request, _ := http.NewRequest(http.MethodPost, |
| 1824 |
"https://hyperspace-superherbs.com/nonexistent", nil) |
| 1825 |
request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1826 |
|
| 1827 |
// simulate a request/response |
| 1828 |
res := httptest.NewRecorder() |
| 1829 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1830 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1831 |
w.WriteHeader(http.StatusOK) |
| 1832 |
} |
| 1833 |
|
| 1834 |
// fire the request |
| 1835 |
handler(res, request) |
| 1836 |
|
| 1837 |
// validate both request and response - should fail because path not found |
| 1838 |
valid, errors := v.ValidateHttpRequestResponse(request, res.Result()) |
| 1839 |
|
| 1840 |
assert.False(t, valid) |
| 1841 |
assert.Len(t, errors, 1) |
| 1842 |
assert.Equal(t, "POST Path '/nonexistent' not found", errors[0].Message) |
| 1843 |
} |
| 1844 |
|
| 1845 |
func TestNewValidator_PetStore_PetFindByStatusGet200_Valid_responseOnly(t *testing.T) { |
| 1846 |
// create a new document from the petstore spec |
| 1847 |
doc, _ := libopenapi.NewDocument(petstoreBytes) |
| 1848 |
|
| 1849 |
// create a doc |
| 1850 |
v, _ := NewValidator(doc) |
| 1851 |
|
| 1852 |
// create a pet |
| 1853 |
body := map[string]interface{}{ |
| 1854 |
"id": 123, |
| 1855 |
"name": "cotton", |
| 1856 |
"category": map[string]interface{}{ |
| 1857 |
"id": 123, |
| 1858 |
"name": "dogs", |
| 1859 |
}, |
| 1860 |
"photoUrls": []string{"https://example.com"}, |
| 1861 |
} |
| 1862 |
|
| 1863 |
// marshal the body into bytes. |
| 1864 |
bodyBytes, _ := json.Marshal([]interface{}{body}) // operation returns an array of pets |
| 1865 |
|
| 1866 |
// create a new put request |
| 1867 |
request, _ := http.NewRequest(http.MethodGet, |
| 1868 |
"https://hyperspace-superherbs.com/pet/findByStatus?status=sold", nil) |
| 1869 |
request.Header.Set("Content-Type", "application/json") |
| 1870 |
|
| 1871 |
// simulate a request/response, in this case the contract returns a 200 with the pet we just created. |
| 1872 |
res := httptest.NewRecorder() |
| 1873 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 1874 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 1875 |
w.WriteHeader(http.StatusOK) |
| 1876 |
_, _ = w.Write(bodyBytes) |
| 1877 |
} |
| 1878 |
|
| 1879 |
// fire the request |
| 1880 |
handler(res, request) |
| 1881 |
|
| 1882 |
// validate the response (should be clean) |
| 1883 |
valid, errors := v.ValidateHttpResponse(request, res.Result()) |
| 1884 |
|
| 1885 |
// should all be perfectly valid. |
| 1886 |
assert.True(t, valid) |
| 1887 |
assert.Len(t, errors, 0) |
| 1888 |
} |
| 1889 |
|
| 1890 |
func TestNewValidator_ValidateHttpResponse_RangeResponseCode(t *testing.T) { |
| 1891 |
spec := `openapi: 3.1.0 |
| 1892 |
paths: |
| 1893 |
/burgers: |
| 1894 |
get: |
| 1895 |
responses: |
| 1896 |
'200': |
| 1897 |
description: OK |
| 1898 |
content: |
| 1899 |
application/json: |
| 1900 |
schema: |
| 1901 |
type: array |
| 1902 |
items: |
| 1903 |
type: object |
| 1904 |
properties: |
| 1905 |
name: |
| 1906 |
type: string |
| 1907 |
patties: |
| 1908 |
type: integer |
| 1909 |
vegetarian: |
| 1910 |
type: boolean |
| 1911 |
'4XX': |
| 1912 |
description: Bad request |
| 1913 |
'5XX': |
| 1914 |
description: Server error` |
| 1915 |
|
| 1916 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 1917 |
|
| 1918 |
v, _ := NewValidator(doc) |
| 1919 |
|
| 1920 |
request, _ := http.NewRequest(http.MethodGet, "https://things.com/burgers", nil) |
| 1921 |
request.Header.Set("Content-Type", "application/json") |
| 1922 |
response := &http.Response{ |
| 1923 |
StatusCode: 400, |
| 1924 |
Header: http.Header{"Content-Type": []string{"application/json"}}, |
| 1925 |
} |
| 1926 |
valid, errors := v.ValidateHttpResponse(request, response) |
| 1927 |
|
| 1928 |
assert.True(t, valid) |
| 1929 |
assert.Len(t, errors, 0) |
| 1930 |
} |
| 1931 |
|
| 1932 |
// https://github.com/pb33f/libopenapi-validator/issues/107 |
| 1933 |
// https://github.com/pb33f/libopenapi-validator/issues/103 |
| 1934 |
func TestNewValidator_TestCircularRefsInValidation_Request(t *testing.T) { |
| 1935 |
spec := `openapi: 3.1.0 |
| 1936 |
info: |
| 1937 |
title: Panic at response validation |
| 1938 |
version: 1.0.0 |
| 1939 |
paths: |
| 1940 |
/operations: |
| 1941 |
delete: |
| 1942 |
description: Delete operations |
| 1943 |
responses: |
| 1944 |
default: |
| 1945 |
description: Any response |
| 1946 |
content: |
| 1947 |
application/json: |
| 1948 |
schema: |
| 1949 |
$ref: '#/components/schemas/Error' |
| 1950 |
|
| 1951 |
components: |
| 1952 |
schemas: |
| 1953 |
Error: |
| 1954 |
type: object |
| 1955 |
properties: |
| 1956 |
code: |
| 1957 |
type: string |
| 1958 |
details: |
| 1959 |
type: array |
| 1960 |
items: |
| 1961 |
$ref: '#/components/schemas/Error'` |
| 1962 |
|
| 1963 |
document, err := libopenapi.NewDocument([]byte(spec)) |
| 1964 |
if err != nil { |
| 1965 |
panic(fmt.Sprintf("failed to create new document: %v\n", err)) |
| 1966 |
} |
| 1967 |
|
| 1968 |
model, errs := document.BuildV3Model() |
| 1969 |
circ := model.Index.GetCircularReferences() |
| 1970 |
fmt.Println("Circular references: ", len(circ)) |
| 1971 |
|
| 1972 |
if errs != nil { |
| 1973 |
panic(fmt.Sprintf("failed to create v3 model from document: %e", errs)) |
| 1974 |
} |
| 1975 |
|
| 1976 |
fmt.Println("Successfully parsed OpenAPI spec") |
| 1977 |
|
| 1978 |
oapiValidator, merrs := NewValidator(document) |
| 1979 |
if merrs != nil { |
| 1980 |
panic(fmt.Sprintf("failed to create validator: %v", merrs)) |
| 1981 |
} |
| 1982 |
if ok, merrs := oapiValidator.ValidateDocument(); !ok { |
| 1983 |
panic(fmt.Sprintf("document validation errors: %v", merrs)) |
| 1984 |
} |
| 1985 |
|
| 1986 |
req := &http.Request{ |
| 1987 |
Method: http.MethodDelete, |
| 1988 |
URL: &url.URL{ |
| 1989 |
Path: "/operations", |
| 1990 |
}, |
| 1991 |
} |
| 1992 |
res := &http.Response{ |
| 1993 |
StatusCode: http.StatusOK, |
| 1994 |
Header: map[string][]string{ |
| 1995 |
"Content-Type": {"application/json"}, |
| 1996 |
}, |
| 1997 |
Body: io.NopCloser(strings.NewReader(`{"code":"abc","details":[{"code":"def"}]}`)), |
| 1998 |
} |
| 1999 |
if ok, errs := oapiValidator.ValidateHttpResponse(req, res); !ok { |
| 2000 |
assert.Equal(t, 1, len(errs)) |
| 2001 |
// Error message can vary depending on whether schema was cached during warming or not: |
| 2002 |
// - "schema render failure, circular reference" (if caught during validation) |
| 2003 |
// - "JSON schema compile failed: json-pointer...not found" (if schema was pre-warmed but has circular refs) |
| 2004 |
// Both indicate the same underlying issue - circular reference in the schema |
| 2005 |
assert.True(t, |
| 2006 |
strings.Contains(errs[0].Reason, "circular reference") || |
| 2007 |
strings.Contains(errs[0].Reason, "json-pointer") || |
| 2008 |
strings.Contains(errs[0].Reason, "not found"), |
| 2009 |
"Expected error about circular reference or compilation failure, got: %s", errs[0].Reason) |
| 2010 |
} |
| 2011 |
} |
| 2012 |
|
| 2013 |
// https://github.com/pb33f/libopenapi-validator/issues/107 |
| 2014 |
// https://github.com/pb33f/libopenapi-validator/issues/103 |
| 2015 |
func TestNewValidator_TestCircularRefsInValidation_Response(t *testing.T) { |
| 2016 |
spec := `openapi: 3.1.0 |
| 2017 |
info: |
| 2018 |
title: Panic at response validation |
| 2019 |
version: 1.0.0 |
| 2020 |
paths: |
| 2021 |
/operations: |
| 2022 |
delete: |
| 2023 |
description: Delete operations |
| 2024 |
responses: |
| 2025 |
default: |
| 2026 |
description: Any response |
| 2027 |
content: |
| 2028 |
application/json: |
| 2029 |
schema: |
| 2030 |
$ref: '#/components/schemas/Error' |
| 2031 |
|
| 2032 |
components: |
| 2033 |
schemas: |
| 2034 |
Error: |
| 2035 |
type: object |
| 2036 |
properties: |
| 2037 |
code: |
| 2038 |
type: string |
| 2039 |
details: |
| 2040 |
type: array |
| 2041 |
items: |
| 2042 |
$ref: '#/components/schemas/Error'` |
| 2043 |
|
| 2044 |
document, err := libopenapi.NewDocument([]byte(spec)) |
| 2045 |
if err != nil { |
| 2046 |
panic(fmt.Sprintf("failed to create new document: %v\n", err)) |
| 2047 |
} |
| 2048 |
|
| 2049 |
model, errs := document.BuildV3Model() |
| 2050 |
circ := model.Index.GetCircularReferences() |
| 2051 |
fmt.Println("Circular references: ", len(circ)) |
| 2052 |
|
| 2053 |
if errs != nil { |
| 2054 |
panic(fmt.Sprintf("failed to create v3 model from document: %e", errs)) |
| 2055 |
} |
| 2056 |
|
| 2057 |
fmt.Println("Successfully parsed OpenAPI spec") |
| 2058 |
|
| 2059 |
oapiValidator, merrs := NewValidator(document) |
| 2060 |
if merrs != nil { |
| 2061 |
panic(fmt.Sprintf("failed to create validator: %v", merrs)) |
| 2062 |
} |
| 2063 |
if ok, merrs := oapiValidator.ValidateDocument(); !ok { |
| 2064 |
panic(fmt.Sprintf("document validation errors: %v", merrs)) |
| 2065 |
} |
| 2066 |
|
| 2067 |
req := &http.Request{ |
| 2068 |
Method: http.MethodDelete, |
| 2069 |
URL: &url.URL{ |
| 2070 |
Path: "/operations", |
| 2071 |
}, |
| 2072 |
} |
| 2073 |
if ok, errs := oapiValidator.ValidateHttpRequest(req); !ok { |
| 2074 |
assert.Equal(t, 1, len(errs)) |
| 2075 |
assert.Equal(t, "cannot render circular reference: #/components/schemas/Error", errs[0].Reason) |
| 2076 |
|
| 2077 |
} |
| 2078 |
} |
| 2079 |
|
| 2080 |
// https://github.com/pb33f/libopenapi-validator/issues/86 |
| 2081 |
func TestNewValidator_HaveYourModelAndEatIt(t *testing.T) { |
| 2082 |
spec := `openapi: 3.1.0 |
| 2083 |
info: |
| 2084 |
title: Panic at response validation |
| 2085 |
version: 1.0.0 |
| 2086 |
paths: |
| 2087 |
/operations: |
| 2088 |
delete: |
| 2089 |
description: Delete operations |
| 2090 |
responses: |
| 2091 |
default: |
| 2092 |
description: Any response |
| 2093 |
content: |
| 2094 |
application/json: |
| 2095 |
schema: |
| 2096 |
$ref: '#/components/schemas/Error' |
| 2097 |
|
| 2098 |
components: |
| 2099 |
schemas: |
| 2100 |
Error: |
| 2101 |
type: object |
| 2102 |
properties: |
| 2103 |
code: |
| 2104 |
type: string |
| 2105 |
details: |
| 2106 |
type: array |
| 2107 |
items: |
| 2108 |
$ref: '#/components/schemas/Error'` |
| 2109 |
|
| 2110 |
document, err := libopenapi.NewDocument([]byte(spec)) |
| 2111 |
if err != nil { |
| 2112 |
panic(fmt.Sprintf("failed to create new document: %v\n", err)) |
| 2113 |
} |
| 2114 |
|
| 2115 |
model, errs := document.BuildV3Model() |
| 2116 |
|
| 2117 |
if errs != nil { |
| 2118 |
panic(fmt.Sprintf("failed to create v3 model from document: %e", errs)) |
| 2119 |
} |
| 2120 |
|
| 2121 |
v := NewValidatorFromV3Model(&model.Model) |
| 2122 |
|
| 2123 |
valid, vErrs := v.ValidateDocument() |
| 2124 |
assert.False(t, valid) |
| 2125 |
assert.Len(t, vErrs, 1) |
| 2126 |
assert.Equal(t, "The document cannot be validated as it is not set", vErrs[0].Reason) |
| 2127 |
|
| 2128 |
v.SetDocument(document) |
| 2129 |
|
| 2130 |
valid, vErrs = v.ValidateDocument() |
| 2131 |
assert.True(t, valid) |
| 2132 |
assert.Len(t, vErrs, 0) |
| 2133 |
} |
| 2134 |
|
| 2135 |
func TestCacheWarming_PopulatesCache(t *testing.T) { |
| 2136 |
spec, err := os.ReadFile("test_specs/petstorev3.json") |
| 2137 |
require.NoError(t, err) |
| 2138 |
|
| 2139 |
doc, err := libopenapi.NewDocument(spec) |
| 2140 |
require.NoError(t, err) |
| 2141 |
|
| 2142 |
v, errs := NewValidator(doc) |
| 2143 |
require.Nil(t, errs) |
| 2144 |
|
| 2145 |
validator := v.(*validator) |
| 2146 |
|
| 2147 |
// Check that caches were populated |
| 2148 |
// Access cache directly from validator options |
| 2149 |
require.NotNil(t, validator.options) |
| 2150 |
require.NotNil(t, validator.options.SchemaCache) |
| 2151 |
|
| 2152 |
count := 0 |
| 2153 |
validator.options.SchemaCache.Range(func(key uint64, value *cache.SchemaCacheEntry) bool { |
| 2154 |
count++ |
| 2155 |
assert.NotNil(t, value.CompiledSchema, "Cache entry should have compiled schema") |
| 2156 |
assert.NotEmpty(t, value.ReferenceSchema, "Cache entry should have pre-converted ReferenceSchema string") |
| 2157 |
assert.Equal(t, string(value.RenderedInline), value.ReferenceSchema, "ReferenceSchema should match string conversion of RenderedInline") |
| 2158 |
return true |
| 2159 |
}) |
| 2160 |
assert.Greater(t, count, 0, "Schema cache should have entries from request and response bodies") |
| 2161 |
} |
| 2162 |
|
| 2163 |
func TestCacheWarming_EdgeCases(t *testing.T) { |
| 2164 |
// Test nil document |
| 2165 |
warmSchemaCaches(nil, nil) |
| 2166 |
|
| 2167 |
// Test empty document |
| 2168 |
doc := &v3.Document{} |
| 2169 |
warmSchemaCaches(doc, nil) |
| 2170 |
|
| 2171 |
// Test document with nil PathItems |
| 2172 |
doc = &v3.Document{Paths: &v3.Paths{}} |
| 2173 |
warmSchemaCaches(doc, nil) |
| 2174 |
} |
| 2175 |
|
| 2176 |
func TestCacheWarming_NilOperations(t *testing.T) { |
| 2177 |
spec := `openapi: 3.1.0 |
| 2178 |
paths: |
| 2179 |
/test: |
| 2180 |
get: |
| 2181 |
responses: |
| 2182 |
'200': |
| 2183 |
description: OK |
| 2184 |
content: |
| 2185 |
application/json: |
| 2186 |
schema: |
| 2187 |
type: object` |
| 2188 |
|
| 2189 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2190 |
require.NoError(t, err) |
| 2191 |
|
| 2192 |
m, _ := doc.BuildV3Model() |
| 2193 |
|
| 2194 |
// Manually set operations to nil to test edge cases |
| 2195 |
for pair := m.Model.Paths.PathItems.First(); pair != nil; pair = pair.Next() { |
| 2196 |
pathItem := pair.Value() |
| 2197 |
// Force GetOperations to return something with nil operation |
| 2198 |
pathItem.Post = nil |
| 2199 |
pathItem.Put = nil |
| 2200 |
pathItem.Delete = nil |
| 2201 |
pathItem.Patch = nil |
| 2202 |
pathItem.Head = nil |
| 2203 |
pathItem.Options = nil |
| 2204 |
pathItem.Trace = nil |
| 2205 |
pathItem.Query = nil |
| 2206 |
pathItem.AdditionalOperations = nil |
| 2207 |
} |
| 2208 |
|
| 2209 |
// This should not panic even with nil operations |
| 2210 |
v := NewValidatorFromV3Model(&m.Model) |
| 2211 |
assert.NotNil(t, v) |
| 2212 |
} |
| 2213 |
|
| 2214 |
func TestCacheWarming_NilSchema(t *testing.T) { |
| 2215 |
spec := `openapi: 3.1.0 |
| 2216 |
paths: |
| 2217 |
/test: |
| 2218 |
post: |
| 2219 |
requestBody: |
| 2220 |
content: |
| 2221 |
application/json: |
| 2222 |
schema: |
| 2223 |
type: object |
| 2224 |
properties: |
| 2225 |
name: |
| 2226 |
type: string |
| 2227 |
responses: |
| 2228 |
'200': |
| 2229 |
description: OK |
| 2230 |
content: |
| 2231 |
application/json: |
| 2232 |
schema: |
| 2233 |
type: object` |
| 2234 |
|
| 2235 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2236 |
require.NoError(t, err) |
| 2237 |
|
| 2238 |
m, _ := doc.BuildV3Model() |
| 2239 |
|
| 2240 |
// Manually set schema to nil to test edge case in warmMediaTypeSchema |
| 2241 |
for pathPair := m.Model.Paths.PathItems.First(); pathPair != nil; pathPair = pathPair.Next() { |
| 2242 |
pathItem := pathPair.Value() |
| 2243 |
if pathItem.Post != nil && pathItem.Post.RequestBody != nil && pathItem.Post.RequestBody.Content != nil { |
| 2244 |
for contentPair := pathItem.Post.RequestBody.Content.First(); contentPair != nil; contentPair = contentPair.Next() { |
| 2245 |
mediaType := contentPair.Value() |
| 2246 |
// Set schema to nil to trigger the schema == nil check |
| 2247 |
mediaType.Schema = nil |
| 2248 |
} |
| 2249 |
} |
| 2250 |
} |
| 2251 |
|
| 2252 |
// This should not panic even with nil schemas |
| 2253 |
v := NewValidatorFromV3Model(&m.Model) |
| 2254 |
assert.NotNil(t, v) |
| 2255 |
} |
| 2256 |
|
| 2257 |
func TestCacheWarming_DefaultResponse(t *testing.T) { |
| 2258 |
spec := `openapi: 3.1.0 |
| 2259 |
paths: |
| 2260 |
/test: |
| 2261 |
get: |
| 2262 |
responses: |
| 2263 |
default: |
| 2264 |
description: Default response |
| 2265 |
content: |
| 2266 |
application/json: |
| 2267 |
schema: |
| 2268 |
type: object |
| 2269 |
properties: |
| 2270 |
message: |
| 2271 |
type: string` |
| 2272 |
|
| 2273 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2274 |
require.NoError(t, err) |
| 2275 |
|
| 2276 |
v, errs := NewValidator(doc) |
| 2277 |
require.Nil(t, errs) |
| 2278 |
|
| 2279 |
validator := v.(*validator) |
| 2280 |
|
| 2281 |
// Check that response cache was populated with default response schema |
| 2282 |
require.NotNil(t, validator.options) |
| 2283 |
require.NotNil(t, validator.options.SchemaCache) |
| 2284 |
|
| 2285 |
count := 0 |
| 2286 |
validator.options.SchemaCache.Range(func(key uint64, value *cache.SchemaCacheEntry) bool { |
| 2287 |
count++ |
| 2288 |
return true |
| 2289 |
}) |
| 2290 |
assert.Greater(t, count, 0, "Schema cache should have entries from default response") |
| 2291 |
} |
| 2292 |
|
| 2293 |
// TestCacheWarming_InvalidSchema tests cache warming gracefully skips invalid schemas |
| 2294 |
func TestCacheWarming_InvalidSchema(t *testing.T) { |
| 2295 |
// This spec intentionally has an invalid schema that will fail to compile |
| 2296 |
spec := `openapi: 3.1.0 |
| 2297 |
paths: |
| 2298 |
/test: |
| 2299 |
post: |
| 2300 |
requestBody: |
| 2301 |
content: |
| 2302 |
application/json: |
| 2303 |
schema: |
| 2304 |
type: invalid-type-that-does-not-exist |
| 2305 |
responses: |
| 2306 |
'200': |
| 2307 |
description: Success |
| 2308 |
content: |
| 2309 |
application/json: |
| 2310 |
schema: |
| 2311 |
type: object` |
| 2312 |
|
| 2313 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2314 |
require.NoError(t, err) |
| 2315 |
|
| 2316 |
// Should not panic even with invalid schema |
| 2317 |
v, errs := NewValidator(doc) |
| 2318 |
require.Nil(t, errs) |
| 2319 |
assert.NotNil(t, v) |
| 2320 |
} |
| 2321 |
|
| 2322 |
// TestCacheWarming_ParameterWithContent tests cache warming for parameters with content property |
| 2323 |
func TestCacheWarming_ParameterWithContent(t *testing.T) { |
| 2324 |
spec := `openapi: 3.1.0 |
| 2325 |
paths: |
| 2326 |
/test: |
| 2327 |
get: |
| 2328 |
parameters: |
| 2329 |
- name: filter |
| 2330 |
in: query |
| 2331 |
content: |
| 2332 |
application/json: |
| 2333 |
schema: |
| 2334 |
type: object |
| 2335 |
properties: |
| 2336 |
value: |
| 2337 |
type: string |
| 2338 |
responses: |
| 2339 |
'200': |
| 2340 |
description: Success` |
| 2341 |
|
| 2342 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2343 |
require.NoError(t, err) |
| 2344 |
|
| 2345 |
v, errs := NewValidator(doc) |
| 2346 |
require.Nil(t, errs) |
| 2347 |
|
| 2348 |
validator := v.(*validator) |
| 2349 |
|
| 2350 |
// Check that parameter cache was populated with content schema |
| 2351 |
require.NotNil(t, validator.options) |
| 2352 |
require.NotNil(t, validator.options.SchemaCache) |
| 2353 |
|
| 2354 |
count := 0 |
| 2355 |
validator.options.SchemaCache.Range(func(key uint64, value *cache.SchemaCacheEntry) bool { |
| 2356 |
count++ |
| 2357 |
return true |
| 2358 |
}) |
| 2359 |
assert.Greater(t, count, 0, "Schema cache should have entries from parameter content property") |
| 2360 |
} |
| 2361 |
|
| 2362 |
// TestCacheWarming_PathLevelParameters tests cache warming for path-level parameters |
| 2363 |
func TestCacheWarming_PathLevelParameters(t *testing.T) { |
| 2364 |
spec := `openapi: 3.1.0 |
| 2365 |
paths: |
| 2366 |
/test/{id}: |
| 2367 |
parameters: |
| 2368 |
- name: id |
| 2369 |
in: path |
| 2370 |
required: true |
| 2371 |
schema: |
| 2372 |
type: string |
| 2373 |
pattern: "^[0-9]+$" |
| 2374 |
get: |
| 2375 |
responses: |
| 2376 |
'200': |
| 2377 |
description: Success` |
| 2378 |
|
| 2379 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2380 |
require.NoError(t, err) |
| 2381 |
|
| 2382 |
v, errs := NewValidator(doc) |
| 2383 |
require.Nil(t, errs) |
| 2384 |
|
| 2385 |
validator := v.(*validator) |
| 2386 |
|
| 2387 |
// Check that parameter cache was populated with path-level parameter |
| 2388 |
require.NotNil(t, validator.options) |
| 2389 |
require.NotNil(t, validator.options.SchemaCache) |
| 2390 |
|
| 2391 |
count := 0 |
| 2392 |
validator.options.SchemaCache.Range(func(key uint64, value *cache.SchemaCacheEntry) bool { |
| 2393 |
count++ |
| 2394 |
return true |
| 2395 |
}) |
| 2396 |
assert.Greater(t, count, 0, "Schema cache should have entries from path-level parameters") |
| 2397 |
} |
| 2398 |
|
| 2399 |
// TestSortValidationErrors tests that validation errors are sorted deterministically |
| 2400 |
func TestSortValidationErrors(t *testing.T) { |
| 2401 |
// Create errors in random order |
| 2402 |
errs := []*errors.ValidationError{ |
| 2403 |
{ValidationType: helpers.SecurityValidation, Message: "API Key missing"}, |
| 2404 |
{ValidationType: helpers.ParameterValidation, Message: "Path param invalid"}, |
| 2405 |
{ValidationType: helpers.RequestValidation, Message: "Body invalid"}, |
| 2406 |
{ValidationType: helpers.ParameterValidation, Message: "Header missing"}, |
| 2407 |
{ValidationType: helpers.SecurityValidation, Message: "Auth header missing"}, |
| 2408 |
} |
| 2409 |
|
| 2410 |
sortValidationErrors(errs) |
| 2411 |
|
| 2412 |
// Verify sorted by validation type first, then by message |
| 2413 |
assert.Equal(t, helpers.ParameterValidation, errs[0].ValidationType) |
| 2414 |
assert.Equal(t, "Header missing", errs[0].Message) |
| 2415 |
assert.Equal(t, helpers.ParameterValidation, errs[1].ValidationType) |
| 2416 |
assert.Equal(t, "Path param invalid", errs[1].Message) |
| 2417 |
assert.Equal(t, helpers.RequestValidation, errs[2].ValidationType) |
| 2418 |
assert.Equal(t, "Body invalid", errs[2].Message) |
| 2419 |
assert.Equal(t, helpers.SecurityValidation, errs[3].ValidationType) |
| 2420 |
assert.Equal(t, "API Key missing", errs[3].Message) |
| 2421 |
assert.Equal(t, helpers.SecurityValidation, errs[4].ValidationType) |
| 2422 |
assert.Equal(t, "Auth header missing", errs[4].Message) |
| 2423 |
} |
| 2424 |
|
| 2425 |
// TestSortValidationErrors_Empty tests sorting empty slice |
| 2426 |
func TestSortValidationErrors_Empty(t *testing.T) { |
| 2427 |
errs := []*errors.ValidationError{} |
| 2428 |
sortValidationErrors(errs) |
| 2429 |
assert.Empty(t, errs) |
| 2430 |
} |
| 2431 |
|
| 2432 |
// TestSortValidationErrors_SingleElement tests sorting single element slice |
| 2433 |
func TestSortValidationErrors_SingleElement(t *testing.T) { |
| 2434 |
errs := []*errors.ValidationError{ |
| 2435 |
{ValidationType: helpers.ParameterValidation, Message: "Invalid value"}, |
| 2436 |
} |
| 2437 |
sortValidationErrors(errs) |
| 2438 |
assert.Len(t, errs, 1) |
| 2439 |
assert.Equal(t, helpers.ParameterValidation, errs[0].ValidationType) |
| 2440 |
} |
| 2441 |
|
| 2442 |
func TestHEAD_ExplicitOperation_ResponseValidation(t *testing.T) { |
| 2443 |
spec := `openapi: 3.1.0 |
| 2444 |
paths: |
| 2445 |
/resource: |
| 2446 |
head: |
| 2447 |
responses: |
| 2448 |
"200": |
| 2449 |
description: ok |
| 2450 |
content: |
| 2451 |
application/json: |
| 2452 |
schema: |
| 2453 |
type: object |
| 2454 |
properties: |
| 2455 |
ok: |
| 2456 |
type: boolean |
| 2457 |
` |
| 2458 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2459 |
require.NoError(t, err) |
| 2460 |
|
| 2461 |
v, errs := NewValidator(doc) |
| 2462 |
require.Empty(t, errs) |
| 2463 |
|
| 2464 |
// create a HEAD request |
| 2465 |
request, _ := http.NewRequest(http.MethodHead, "https://example.com/resource", nil) |
| 2466 |
|
| 2467 |
// simulate a server response that includes a JSON body matching the schema |
| 2468 |
bodyBytes, _ := json.Marshal(map[string]bool{"ok": true}) |
| 2469 |
response := &http.Response{ |
| 2470 |
StatusCode: 200, |
| 2471 |
Header: http.Header{"Content-Type": []string{"application/json"}}, |
| 2472 |
Body: io.NopCloser(bytes.NewBuffer(bodyBytes)), |
| 2473 |
} |
| 2474 |
|
| 2475 |
valid, valErrs := v.ValidateHttpResponse(request, response) |
| 2476 |
assert.False(t, valid) |
| 2477 |
assert.Len(t, valErrs, 1) |
| 2478 |
|
| 2479 |
// Also validate a response without a body (common for HEAD) |
| 2480 |
responseNoBody := &http.Response{ |
| 2481 |
StatusCode: 200, |
| 2482 |
Header: http.Header{"Content-Type": []string{"application/json"}}, |
| 2483 |
Body: http.NoBody, |
| 2484 |
} |
| 2485 |
|
| 2486 |
validNoBody, valErrsNoBody := v.ValidateHttpResponse(request, responseNoBody) |
| 2487 |
assert.True(t, validNoBody) |
| 2488 |
assert.Len(t, valErrsNoBody, 0) |
| 2489 |
} |
| 2490 |
|
| 2491 |
func TestHEAD_ImplicitViaGET_ResponseValidation(t *testing.T) { |
| 2492 |
// This spec defines only GET for /resource. Ensure a HEAD request that returns the same body |
| 2493 |
// as GET will still validate against the documented GET response. |
| 2494 |
spec := `openapi: 3.1.0 |
| 2495 |
paths: |
| 2496 |
/resource: |
| 2497 |
get: |
| 2498 |
responses: |
| 2499 |
"200": |
| 2500 |
description: ok |
| 2501 |
content: |
| 2502 |
application/json: |
| 2503 |
schema: |
| 2504 |
type: object |
| 2505 |
properties: |
| 2506 |
ok: |
| 2507 |
type: boolean |
| 2508 |
` |
| 2509 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2510 |
require.NoError(t, err) |
| 2511 |
|
| 2512 |
v, errs := NewValidator(doc) |
| 2513 |
require.Empty(t, errs) |
| 2514 |
|
| 2515 |
// create a HEAD request (no explicit HEAD operation in the spec) |
| 2516 |
request, _ := http.NewRequest(http.MethodHead, "https://example.com/resource", nil) |
| 2517 |
|
| 2518 |
// simulate a server response that includes a JSON body like the GET response would. |
| 2519 |
bodyBytes, _ := json.Marshal(map[string]bool{"ok": true}) |
| 2520 |
response := &http.Response{ |
| 2521 |
StatusCode: 200, |
| 2522 |
Header: http.Header{"Content-Type": []string{"application/json"}}, |
| 2523 |
Body: io.NopCloser(bytes.NewBuffer(bodyBytes)), |
| 2524 |
} |
| 2525 |
|
| 2526 |
valid, valErrs := v.ValidateHttpResponse(request, response) |
| 2527 |
// Expect validation to succeed when HEAD responses are validated against GET response definitions. |
| 2528 |
assert.False(t, valid) |
| 2529 |
assert.Len(t, valErrs, 1) |
| 2530 |
|
| 2531 |
responseNoBody := &http.Response{ |
| 2532 |
StatusCode: 200, |
| 2533 |
Header: http.Header{"Content-Type": []string{"application/json"}}, |
| 2534 |
Body: http.NoBody, |
| 2535 |
} |
| 2536 |
|
| 2537 |
validNoBody, valErrsNoBody := v.ValidateHttpResponse(request, responseNoBody) |
| 2538 |
// Expect validation to succeed when HEAD responses are validated against GET response definitions. |
| 2539 |
assert.True(t, validNoBody) |
| 2540 |
assert.Len(t, valErrsNoBody, 0) |
| 2541 |
} |
| 2542 |
|
| 2543 |
func TestHEAD_BothGETAndHEAD_SameSchema_Valid(t *testing.T) { |
| 2544 |
spec := `openapi: 3.1.0 |
| 2545 |
paths: |
| 2546 |
/resource: |
| 2547 |
get: |
| 2548 |
responses: |
| 2549 |
"200": |
| 2550 |
description: ok |
| 2551 |
content: |
| 2552 |
application/json: |
| 2553 |
schema: |
| 2554 |
type: object |
| 2555 |
properties: |
| 2556 |
ok: |
| 2557 |
type: boolean |
| 2558 |
head: |
| 2559 |
responses: |
| 2560 |
"200": |
| 2561 |
description: ok |
| 2562 |
content: |
| 2563 |
application/json: |
| 2564 |
schema: |
| 2565 |
type: object |
| 2566 |
properties: |
| 2567 |
ok: |
| 2568 |
type: boolean |
| 2569 |
` |
| 2570 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2571 |
require.NoError(t, err) |
| 2572 |
|
| 2573 |
v, errs := NewValidator(doc) |
| 2574 |
require.Empty(t, errs) |
| 2575 |
|
| 2576 |
// HEAD request to /resource |
| 2577 |
request, _ := http.NewRequest(http.MethodHead, "https://example.com/resource", nil) |
| 2578 |
|
| 2579 |
// server returns a JSON body that matches the schema |
| 2580 |
bodyBytes, _ := json.Marshal(map[string]bool{"ok": true}) |
| 2581 |
response := &http.Response{ |
| 2582 |
StatusCode: 200, |
| 2583 |
Header: http.Header{helpers.ContentTypeHeader: []string{"application/json"}}, |
| 2584 |
Body: io.NopCloser(bytes.NewBuffer(bodyBytes)), |
| 2585 |
} |
| 2586 |
|
| 2587 |
valid, valErrs := v.ValidateHttpResponse(request, response) |
| 2588 |
assert.False(t, valid) |
| 2589 |
assert.Len(t, valErrs, 1) |
| 2590 |
|
| 2591 |
responseNoBody := &http.Response{ |
| 2592 |
StatusCode: 200, |
| 2593 |
Header: http.Header{"Content-Type": []string{"application/json"}}, |
| 2594 |
Body: http.NoBody, |
| 2595 |
} |
| 2596 |
|
| 2597 |
validNoBody, valErrsNoBody := v.ValidateHttpResponse(request, responseNoBody) |
| 2598 |
// Expect validation to succeed when HEAD responses are validated against GET response definitions. |
| 2599 |
assert.True(t, validNoBody) |
| 2600 |
assert.Len(t, valErrsNoBody, 0) |
| 2601 |
} |
| 2602 |
|
| 2603 |
func TestHEAD_BothGETAndHEAD_DifferentSchemas_HeadPreferred(t *testing.T) { |
| 2604 |
spec := `openapi: 3.1.0 |
| 2605 |
paths: |
| 2606 |
/resource: |
| 2607 |
get: |
| 2608 |
responses: |
| 2609 |
"200": |
| 2610 |
description: get schema |
| 2611 |
content: |
| 2612 |
application/json: |
| 2613 |
schema: |
| 2614 |
type: object |
| 2615 |
required: ["g"] |
| 2616 |
properties: |
| 2617 |
g: |
| 2618 |
type: string |
| 2619 |
head: |
| 2620 |
responses: |
| 2621 |
"200": |
| 2622 |
description: head schema |
| 2623 |
headers: |
| 2624 |
content-length: |
| 2625 |
description: size of the file |
| 2626 |
schema: |
| 2627 |
type: integer |
| 2628 |
` |
| 2629 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2630 |
require.NoError(t, err) |
| 2631 |
|
| 2632 |
v, errs := NewValidator(doc) |
| 2633 |
require.Empty(t, errs) |
| 2634 |
|
| 2635 |
// Case A: response matches HEAD schema has content-length header but response contains content-type |
| 2636 |
reqA, _ := http.NewRequest(http.MethodHead, "https://example.com/resource", nil) |
| 2637 |
respA := &http.Response{ |
| 2638 |
StatusCode: 200, |
| 2639 |
Header: http.Header{helpers.ContentTypeHeader: []string{"application/json"}}, |
| 2640 |
Body: http.NoBody, |
| 2641 |
} |
| 2642 |
// No support for response headers validation. |
| 2643 |
// Only validates response content-type: json |
| 2644 |
validA, errsA := v.ValidateHttpResponse(reqA, respA) |
| 2645 |
assert.True(t, validA) |
| 2646 |
assert.Len(t, errsA, 0) |
| 2647 |
|
| 2648 |
// Case B: response matches GET schema (has "g") but not HEAD (missing required "h") -> should fail |
| 2649 |
reqB, _ := http.NewRequest(http.MethodGet, "https://example.com/resource", nil) |
| 2650 |
bodyB, _ := json.Marshal(map[string]string{"g": "get-value"}) |
| 2651 |
respB := &http.Response{ |
| 2652 |
StatusCode: 200, |
| 2653 |
Header: http.Header{helpers.ContentTypeHeader: []string{"application/json"}}, |
| 2654 |
Body: io.NopCloser(bytes.NewBuffer(bodyB)), |
| 2655 |
} |
| 2656 |
validB, errsB := v.ValidateHttpResponse(reqB, respB) |
| 2657 |
assert.True(t, validB) |
| 2658 |
assert.Len(t, errsB, 0) |
| 2659 |
} |
| 2660 |
|
| 2661 |
// TestValidateHttpResponse_DiscriminatorOneOf tests that response validation works correctly |
| 2662 |
// when the response schema uses oneOf with a discriminator and $ref to component schemas. |
| 2663 |
// This is a regression test for https://github.com/pb33f/libopenapi-validator/issues/247 |
| 2664 |
// where the validator would fail with "json-pointer not found" because discriminator refs |
| 2665 |
// were preserved (Bundle mode) instead of fully inlined (Validation mode). |
| 2666 |
func TestValidateHttpResponse_DiscriminatorOneOf(t *testing.T) { |
| 2667 |
spec := `openapi: 3.1.0 |
| 2668 |
info: |
| 2669 |
title: Discriminator OneOf Response Test |
| 2670 |
version: 1.0.0 |
| 2671 |
paths: |
| 2672 |
/fields: |
| 2673 |
get: |
| 2674 |
responses: |
| 2675 |
'200': |
| 2676 |
description: OK |
| 2677 |
content: |
| 2678 |
application/json: |
| 2679 |
schema: |
| 2680 |
$ref: '#/components/schemas/Field' |
| 2681 |
post: |
| 2682 |
requestBody: |
| 2683 |
required: true |
| 2684 |
content: |
| 2685 |
application/json: |
| 2686 |
schema: |
| 2687 |
$ref: '#/components/schemas/Field' |
| 2688 |
responses: |
| 2689 |
'201': |
| 2690 |
description: Created |
| 2691 |
components: |
| 2692 |
schemas: |
| 2693 |
BooleanField: |
| 2694 |
type: object |
| 2695 |
required: |
| 2696 |
- field_type |
| 2697 |
- default_value |
| 2698 |
properties: |
| 2699 |
field_type: |
| 2700 |
type: string |
| 2701 |
const: boolean |
| 2702 |
default_value: |
| 2703 |
type: boolean |
| 2704 |
StringField: |
| 2705 |
type: object |
| 2706 |
required: |
| 2707 |
- field_type |
| 2708 |
- max_length |
| 2709 |
properties: |
| 2710 |
field_type: |
| 2711 |
type: string |
| 2712 |
const: string |
| 2713 |
max_length: |
| 2714 |
type: integer |
| 2715 |
minimum: 1 |
| 2716 |
Field: |
| 2717 |
oneOf: |
| 2718 |
- $ref: '#/components/schemas/BooleanField' |
| 2719 |
- $ref: '#/components/schemas/StringField' |
| 2720 |
discriminator: |
| 2721 |
propertyName: field_type` |
| 2722 |
|
| 2723 |
// Subtest with cache enabled (exercises cache-warming paths in validator.go) |
| 2724 |
t.Run("cached", func(t *testing.T) { |
| 2725 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2726 |
require.NoError(t, err) |
| 2727 |
|
| 2728 |
v, errs := NewValidator(doc) |
| 2729 |
require.Empty(t, errs) |
| 2730 |
|
| 2731 |
body, _ := json.Marshal(map[string]interface{}{ |
| 2732 |
"field_type": "boolean", |
| 2733 |
"default_value": true, |
| 2734 |
}) |
| 2735 |
request, _ := http.NewRequest(http.MethodGet, "https://example.com/fields", nil) |
| 2736 |
response := &http.Response{ |
| 2737 |
StatusCode: 200, |
| 2738 |
Header: http.Header{"Content-Type": []string{"application/json"}}, |
| 2739 |
Body: io.NopCloser(bytes.NewBuffer(body)), |
| 2740 |
} |
| 2741 |
|
| 2742 |
valid, validationErrors := v.ValidateHttpResponse(request, response) |
| 2743 |
assert.True(t, valid, "response validation should pass for valid discriminator oneOf payload") |
| 2744 |
assert.Empty(t, validationErrors, "no validation errors expected") |
| 2745 |
}) |
| 2746 |
|
| 2747 |
// Subtest with cache disabled (exercises uncached compile paths in |
| 2748 |
// validate_response.go, validate_request.go) |
| 2749 |
t.Run("uncached", func(t *testing.T) { |
| 2750 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2751 |
require.NoError(t, err) |
| 2752 |
|
| 2753 |
v, errs := NewValidator(doc, config.WithSchemaCache(nil)) |
| 2754 |
require.Empty(t, errs) |
| 2755 |
|
| 2756 |
// Response validation (validate_response.go cache-miss path) |
| 2757 |
body, _ := json.Marshal(map[string]interface{}{ |
| 2758 |
"field_type": "string", |
| 2759 |
"max_length": 255, |
| 2760 |
}) |
| 2761 |
request, _ := http.NewRequest(http.MethodGet, "https://example.com/fields", nil) |
| 2762 |
response := &http.Response{ |
| 2763 |
StatusCode: 200, |
| 2764 |
Header: http.Header{"Content-Type": []string{"application/json"}}, |
| 2765 |
Body: io.NopCloser(bytes.NewBuffer(body)), |
| 2766 |
} |
| 2767 |
|
| 2768 |
valid, validationErrors := v.ValidateHttpResponse(request, response) |
| 2769 |
assert.True(t, valid, "uncached response validation should pass") |
| 2770 |
assert.Empty(t, validationErrors, "no validation errors expected (uncached response)") |
| 2771 |
|
| 2772 |
// Request validation (validate_request.go cache-miss path) |
| 2773 |
reqBody, _ := json.Marshal(map[string]interface{}{ |
| 2774 |
"field_type": "boolean", |
| 2775 |
"default_value": false, |
| 2776 |
}) |
| 2777 |
postReq, _ := http.NewRequest(http.MethodPost, "https://example.com/fields", |
| 2778 |
bytes.NewBuffer(reqBody)) |
| 2779 |
postReq.Header.Set("Content-Type", "application/json") |
| 2780 |
|
| 2781 |
validReq, reqErrors := v.ValidateHttpRequest(postReq) |
| 2782 |
assert.True(t, validReq, "uncached request validation should pass") |
| 2783 |
assert.Empty(t, reqErrors, "no validation errors expected (uncached request)") |
| 2784 |
}) |
| 2785 |
} |
| 2786 |
|
| 2787 |
func TestStrictMode_RejectReadOnly_RequestIntegration(t *testing.T) { |
| 2788 |
spec := `openapi: 3.1.0 |
| 2789 |
paths: |
| 2790 |
/users: |
| 2791 |
post: |
| 2792 |
requestBody: |
| 2793 |
required: true |
| 2794 |
content: |
| 2795 |
application/json: |
| 2796 |
schema: |
| 2797 |
type: object |
| 2798 |
properties: |
| 2799 |
id: |
| 2800 |
type: string |
| 2801 |
readOnly: true |
| 2802 |
name: |
| 2803 |
type: string |
| 2804 |
responses: |
| 2805 |
"201": |
| 2806 |
description: created` |
| 2807 |
|
| 2808 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2809 |
require.NoError(t, err) |
| 2810 |
|
| 2811 |
v, errs := NewValidator(doc, config.WithStrictMode(), config.WithStrictRejectReadOnly()) |
| 2812 |
require.Empty(t, errs) |
| 2813 |
|
| 2814 |
body := map[string]any{ |
| 2815 |
"id": "user-123", |
| 2816 |
"name": "John", |
| 2817 |
} |
| 2818 |
bodyBytes, _ := json.Marshal(body) |
| 2819 |
|
| 2820 |
request, _ := http.NewRequest(http.MethodPost, "https://example.com/users", bytes.NewBuffer(bodyBytes)) |
| 2821 |
request.Header.Set("Content-Type", "application/json") |
| 2822 |
|
| 2823 |
valid, valErrs := v.ValidateHttpRequest(request) |
| 2824 |
assert.False(t, valid) |
| 2825 |
|
| 2826 |
foundReadOnly := false |
| 2827 |
for _, vErr := range valErrs { |
| 2828 |
if vErr.ValidationType == errors.StrictValidationType && |
| 2829 |
vErr.ValidationSubType == errors.StrictSubTypeReadOnlyProperty { |
| 2830 |
foundReadOnly = true |
| 2831 |
break |
| 2832 |
} |
| 2833 |
} |
| 2834 |
assert.True(t, foundReadOnly, "should report readOnly violation") |
| 2835 |
} |
| 2836 |
|
| 2837 |
func TestStrictMode_RejectWriteOnly_ResponseIntegration(t *testing.T) { |
| 2838 |
spec := `openapi: 3.1.0 |
| 2839 |
paths: |
| 2840 |
/users/{id}: |
| 2841 |
get: |
| 2842 |
parameters: |
| 2843 |
- in: path |
| 2844 |
name: id |
| 2845 |
required: true |
| 2846 |
schema: |
| 2847 |
type: string |
| 2848 |
responses: |
| 2849 |
"200": |
| 2850 |
description: ok |
| 2851 |
content: |
| 2852 |
application/json: |
| 2853 |
schema: |
| 2854 |
type: object |
| 2855 |
properties: |
| 2856 |
name: |
| 2857 |
type: string |
| 2858 |
password: |
| 2859 |
type: string |
| 2860 |
writeOnly: true` |
| 2861 |
|
| 2862 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 2863 |
require.NoError(t, err) |
| 2864 |
|
| 2865 |
v, errs := NewValidator(doc, config.WithStrictMode(), config.WithStrictRejectWriteOnly()) |
| 2866 |
require.Empty(t, errs) |
| 2867 |
|
| 2868 |
request, _ := http.NewRequest(http.MethodGet, "https://example.com/users/123", http.NoBody) |
| 2869 |
|
| 2870 |
body := map[string]any{ |
| 2871 |
"name": "John", |
| 2872 |
"password": "secret", |
| 2873 |
} |
| 2874 |
bodyBytes, _ := json.Marshal(body) |
| 2875 |
|
| 2876 |
response := &http.Response{ |
| 2877 |
StatusCode: 200, |
| 2878 |
Header: http.Header{ |
| 2879 |
"Content-Type": {"application/json"}, |
| 2880 |
}, |
| 2881 |
Body: io.NopCloser(bytes.NewBuffer(bodyBytes)), |
| 2882 |
} |
| 2883 |
|
| 2884 |
valid, valErrs := v.ValidateHttpResponse(request, response) |
| 2885 |
assert.False(t, valid) |
| 2886 |
|
| 2887 |
foundWriteOnly := false |
| 2888 |
for _, vErr := range valErrs { |
| 2889 |
if vErr.ValidationType == errors.StrictValidationType && |
| 2890 |
vErr.ValidationSubType == errors.StrictSubTypeWriteOnlyProperty { |
| 2891 |
foundWriteOnly = true |
| 2892 |
break |
| 2893 |
} |
| 2894 |
} |
| 2895 |
assert.True(t, foundWriteOnly, "should report writeOnly violation") |
| 2896 |
} |