| 1 |
// Copyright 2023-2025 Princess Beef Heavy Industries, LLC / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
package schema_validation |
| 5 |
|
| 6 |
import ( |
| 7 |
"fmt" |
| 8 |
"os" |
| 9 |
"testing" |
| 10 |
|
| 11 |
"github.com/pb33f/libopenapi" |
| 12 |
"github.com/stretchr/testify/assert" |
| 13 |
"go.yaml.in/yaml/v4" |
| 14 |
|
| 15 |
"github.com/pb33f/libopenapi-validator/config" |
| 16 |
liberrors "github.com/pb33f/libopenapi-validator/errors" |
| 17 |
"github.com/pb33f/libopenapi-validator/helpers" |
| 18 |
) |
| 19 |
|
| 20 |
func TestValidateDocument(t *testing.T) { |
| 21 |
petstore, _ := os.ReadFile("../test_specs/petstorev3.json") |
| 22 |
|
| 23 |
doc, _ := libopenapi.NewDocument(petstore) |
| 24 |
|
| 25 |
// validate! |
| 26 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 27 |
|
| 28 |
assert.True(t, valid) |
| 29 |
assert.Len(t, errors, 0) |
| 30 |
} |
| 31 |
|
| 32 |
func TestValidateDocument_31(t *testing.T) { |
| 33 |
petstore, _ := os.ReadFile("../test_specs/valid_31.yaml") |
| 34 |
|
| 35 |
doc, _ := libopenapi.NewDocument(petstore) |
| 36 |
|
| 37 |
// validate! |
| 38 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 39 |
|
| 40 |
assert.True(t, valid) |
| 41 |
assert.Len(t, errors, 0) |
| 42 |
} |
| 43 |
|
| 44 |
func TestValidateDocument_Invalid31(t *testing.T) { |
| 45 |
petstore, _ := os.ReadFile("../test_specs/invalid_31.yaml") |
| 46 |
|
| 47 |
doc, _ := libopenapi.NewDocument(petstore) |
| 48 |
|
| 49 |
// validate! |
| 50 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 51 |
|
| 52 |
assert.False(t, valid) |
| 53 |
assert.Len(t, errors, 1) |
| 54 |
assert.Len(t, errors[0].SchemaValidationErrors, 6) |
| 55 |
} |
| 56 |
|
| 57 |
func TestValidateDocument_UnquotedIntegerResponseCodeHelpfulError(t *testing.T) { |
| 58 |
spec := `openapi: 3.1.0 |
| 59 |
info: |
| 60 |
title: Test |
| 61 |
version: 1.0.0 |
| 62 |
paths: |
| 63 |
/test: |
| 64 |
get: |
| 65 |
responses: |
| 66 |
200: |
| 67 |
description: OK` |
| 68 |
|
| 69 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 70 |
|
| 71 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 72 |
|
| 73 |
assert.False(t, valid) |
| 74 |
assert.Len(t, errors, 1) |
| 75 |
assert.Equal(t, "OpenAPI document validation failed", errors[0].Message) |
| 76 |
assert.Contains(t, errors[0].Reason, "Response status code keys must be strings") |
| 77 |
assert.Contains(t, errors[0].Reason, `quote 200 as "200"`) |
| 78 |
assert.Contains(t, errors[0].Reason, "/paths/~1test/get/responses/200") |
| 79 |
assert.NotContains(t, errors[0].Reason, "got null, want object") |
| 80 |
assert.Contains(t, errors[0].HowToFix, `"200"`) |
| 81 |
assert.Equal(t, 9, errors[0].SpecLine) |
| 82 |
assert.Equal(t, 9, errors[0].SpecCol) |
| 83 |
assert.Empty(t, errors[0].SchemaValidationErrors) |
| 84 |
} |
| 85 |
|
| 86 |
func TestValidateDocument_QuotedResponseCodeValid(t *testing.T) { |
| 87 |
spec := `openapi: 3.1.0 |
| 88 |
info: |
| 89 |
title: Test |
| 90 |
version: 1.0.0 |
| 91 |
paths: |
| 92 |
/test: |
| 93 |
get: |
| 94 |
responses: |
| 95 |
"200": |
| 96 |
description: OK` |
| 97 |
|
| 98 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 99 |
|
| 100 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 101 |
|
| 102 |
assert.True(t, valid) |
| 103 |
assert.Empty(t, errors) |
| 104 |
} |
| 105 |
|
| 106 |
func TestValidateDocument_YAMLMergeKeyValid(t *testing.T) { |
| 107 |
spec := `openapi: 3.1.0 |
| 108 |
info: |
| 109 |
title: Test |
| 110 |
version: 1.0.0 |
| 111 |
x-base-response: &baseResponse |
| 112 |
description: OK |
| 113 |
paths: |
| 114 |
/test: |
| 115 |
get: |
| 116 |
responses: |
| 117 |
"200": |
| 118 |
<<: *baseResponse` |
| 119 |
|
| 120 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 121 |
|
| 122 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 123 |
|
| 124 |
assert.True(t, valid) |
| 125 |
assert.Empty(t, errors) |
| 126 |
} |
| 127 |
|
| 128 |
func TestValidateDocument_YAMLMergeKeyDoesNotHideInvalidResponseCode(t *testing.T) { |
| 129 |
spec := `openapi: 3.1.0 |
| 130 |
info: |
| 131 |
title: Test |
| 132 |
version: 1.0.0 |
| 133 |
x-base-responses: &baseResponses |
| 134 |
default: |
| 135 |
description: Default |
| 136 |
paths: |
| 137 |
/test: |
| 138 |
get: |
| 139 |
responses: |
| 140 |
<<: *baseResponses |
| 141 |
200: |
| 142 |
description: OK` |
| 143 |
|
| 144 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 145 |
|
| 146 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 147 |
|
| 148 |
assert.False(t, valid) |
| 149 |
assert.Len(t, errors, 1) |
| 150 |
assert.Contains(t, errors[0].Reason, "Response status code keys must be strings") |
| 151 |
assert.Contains(t, errors[0].Reason, `quote 200 as "200"`) |
| 152 |
assert.NotContains(t, errors[0].Reason, `merge key "<<"`) |
| 153 |
assert.Equal(t, 13, errors[0].SpecLine) |
| 154 |
assert.Empty(t, errors[0].SchemaValidationErrors) |
| 155 |
} |
| 156 |
|
| 157 |
func TestValidateDocument_GenericNonStringMappingKeyHelpfulError(t *testing.T) { |
| 158 |
spec := `openapi: 3.1.0 |
| 159 |
info: |
| 160 |
title: Test |
| 161 |
version: 1.0.0 |
| 162 |
paths: {} |
| 163 |
x-values: |
| 164 |
1: one` |
| 165 |
|
| 166 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 167 |
|
| 168 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 169 |
|
| 170 |
assert.False(t, valid) |
| 171 |
assert.Len(t, errors, 1) |
| 172 |
assert.Equal(t, "OpenAPI document validation failed", errors[0].Message) |
| 173 |
assert.Contains(t, errors[0].Reason, "OpenAPI documents require string mapping keys") |
| 174 |
assert.Contains(t, errors[0].Reason, `int key "1"`) |
| 175 |
assert.Contains(t, errors[0].Reason, "/x-values/1") |
| 176 |
assert.NotContains(t, errors[0].Reason, "got null, want object") |
| 177 |
assert.Contains(t, errors[0].HowToFix, "Quote YAML mapping keys") |
| 178 |
assert.Equal(t, 7, errors[0].SpecLine) |
| 179 |
assert.Equal(t, 3, errors[0].SpecCol) |
| 180 |
assert.Empty(t, errors[0].SchemaValidationErrors) |
| 181 |
} |
| 182 |
|
| 183 |
func TestNormalizeJSON_ReturnsMarshalError(t *testing.T) { |
| 184 |
payload := map[string]interface{}{ |
| 185 |
"openapi": "3.1.0", |
| 186 |
"invalid": map[interface{}]interface{}{ |
| 187 |
1: "one", |
| 188 |
}, |
| 189 |
} |
| 190 |
|
| 191 |
normalized, err := normalizeJSON(payload) |
| 192 |
|
| 193 |
assert.Nil(t, normalized) |
| 194 |
assert.Error(t, err) |
| 195 |
assert.Contains(t, err.Error(), "unsupported type: map[interface {}]interface {}") |
| 196 |
} |
| 197 |
|
| 198 |
func TestValidateDocument_NormalizationErrorDoesNotValidateNil(t *testing.T) { |
| 199 |
spec := `openapi: 3.1.0 |
| 200 |
info: |
| 201 |
title: Test |
| 202 |
version: 1.0.0 |
| 203 |
paths: {}` |
| 204 |
|
| 205 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 206 |
badSpecJSON := map[string]interface{}{ |
| 207 |
"openapi": "3.1.0", |
| 208 |
"invalid": map[interface{}]interface{}{ |
| 209 |
1: "one", |
| 210 |
}, |
| 211 |
} |
| 212 |
info := doc.GetSpecInfo() |
| 213 |
info.SpecJSON = &badSpecJSON |
| 214 |
info.SpecJSONBytes = nil |
| 215 |
|
| 216 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 217 |
|
| 218 |
assert.False(t, valid) |
| 219 |
assert.Len(t, errors, 1) |
| 220 |
assert.Equal(t, "OpenAPI document validation failed", errors[0].Message) |
| 221 |
assert.Contains(t, errors[0].Reason, "cannot be converted to JSON") |
| 222 |
assert.Contains(t, errors[0].Reason, "unsupported type: map[interface {}]interface {}") |
| 223 |
assert.NotContains(t, errors[0].Reason, "got null, want object") |
| 224 |
assert.Empty(t, errors[0].SchemaValidationErrors) |
| 225 |
} |
| 226 |
|
| 227 |
func TestValidateDocument_CorruptSpecJSONBytesFallbackNormalizationError(t *testing.T) { |
| 228 |
spec := `openapi: 3.1.0 |
| 229 |
info: |
| 230 |
title: Test |
| 231 |
version: 1.0.0 |
| 232 |
paths: {}` |
| 233 |
|
| 234 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 235 |
badSpecJSON := map[string]interface{}{ |
| 236 |
"openapi": "3.1.0", |
| 237 |
"invalid": map[interface{}]interface{}{ |
| 238 |
1: "one", |
| 239 |
}, |
| 240 |
} |
| 241 |
corrupt := []byte(`{not valid json!!!}`) |
| 242 |
info := doc.GetSpecInfo() |
| 243 |
info.SpecJSON = &badSpecJSON |
| 244 |
info.SpecJSONBytes = &corrupt |
| 245 |
|
| 246 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 247 |
|
| 248 |
assert.False(t, valid) |
| 249 |
assert.Len(t, errors, 1) |
| 250 |
assert.Contains(t, errors[0].Reason, "cannot be converted to JSON") |
| 251 |
assert.NotContains(t, errors[0].Reason, "got null, want object") |
| 252 |
assert.Empty(t, errors[0].SchemaValidationErrors) |
| 253 |
} |
| 254 |
|
| 255 |
func TestValidateDocumentHelpers_DefensiveBranches(t *testing.T) { |
| 256 |
assert.Nil(t, findNonStringMappingKey(nil)) |
| 257 |
assert.Nil(t, findNonStringMappingKeyInNode(nil, nil)) |
| 258 |
assert.Nil(t, findNonStringMappingKeyInMergeValue(nil, nil)) |
| 259 |
assert.False(t, isStringMappingKey(nil)) |
| 260 |
assert.False(t, isMergeMappingKey(nil)) |
| 261 |
assert.Equal(t, "", buildJSONPointer(nil)) |
| 262 |
assert.Equal(t, "non-string", yamlKeyType(nil)) |
| 263 |
assert.False(t, isOperationResponseStatusCodeKey([]string{"paths", "/test", "parameters", "responses", "200"})) |
| 264 |
|
| 265 |
sequenceKey := &nonStringMappingKey{Sequence: true} |
| 266 |
assert.Equal(t, "sequence", yamlKeyType(sequenceKey)) |
| 267 |
|
| 268 |
mergeKey := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!merge", Value: "<<"} |
| 269 |
assert.True(t, isMergeMappingKey(mergeKey)) |
| 270 |
|
| 271 |
intKey := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: "1", Line: 2, Column: 5} |
| 272 |
value := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "one"} |
| 273 |
mapping := &yaml.Node{ |
| 274 |
Kind: yaml.MappingNode, |
| 275 |
Content: []*yaml.Node{intKey, value}, |
| 276 |
} |
| 277 |
sequence := &yaml.Node{ |
| 278 |
Kind: yaml.SequenceNode, |
| 279 |
Content: []*yaml.Node{mapping}, |
| 280 |
} |
| 281 |
|
| 282 |
found := findNonStringMappingKeyInNode(sequence, []string{"items"}) |
| 283 |
assert.NotNil(t, found) |
| 284 |
assert.Equal(t, []string{"items", "0", "1"}, found.Path) |
| 285 |
assert.Equal(t, "1", found.Value) |
| 286 |
|
| 287 |
found = findNonStringMappingKeyInMergeValue(&yaml.Node{Kind: yaml.AliasNode, Alias: mapping}, []string{"merged"}) |
| 288 |
assert.NotNil(t, found) |
| 289 |
assert.Equal(t, []string{"merged", "1"}, found.Path) |
| 290 |
|
| 291 |
mergeMapping := &yaml.Node{ |
| 292 |
Kind: yaml.MappingNode, |
| 293 |
Content: []*yaml.Node{mergeKey, mapping}, |
| 294 |
} |
| 295 |
found = findNonStringMappingKeyInNode(mergeMapping, []string{"mergeTarget"}) |
| 296 |
assert.NotNil(t, found) |
| 297 |
assert.Equal(t, []string{"mergeTarget", "1"}, found.Path) |
| 298 |
|
| 299 |
mergeSequence := &yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{mapping}} |
| 300 |
found = findNonStringMappingKeyInMergeValue(mergeSequence, []string{"mergedSequence"}) |
| 301 |
assert.NotNil(t, found) |
| 302 |
assert.Equal(t, []string{"mergedSequence", "1"}, found.Path) |
| 303 |
|
| 304 |
assert.Nil(t, findNonStringMappingKeyInMergeValue(&yaml.Node{Kind: yaml.SequenceNode}, []string{"empty"})) |
| 305 |
assert.Nil(t, findNonStringMappingKeyInMergeValue(&yaml.Node{Kind: yaml.AliasNode}, []string{"merged"})) |
| 306 |
} |
| 307 |
|
| 308 |
// Helper function to test the validation logic directly |
| 309 |
func validateOpenAPIDocumentWithMalformedSchema(loadedSchema string, decodedDocument map[string]interface{}) (bool, []*liberrors.ValidationError) { |
| 310 |
options := config.NewValidationOptions() |
| 311 |
var validationErrors []*liberrors.ValidationError |
| 312 |
|
| 313 |
// This replicates the exact logic from validate_document.go:40-127 |
| 314 |
_, err := helpers.NewCompiledSchema("schema", []byte(loadedSchema), options) |
| 315 |
if err != nil { |
| 316 |
// schema compilation failed, return validation error instead of panicking |
| 317 |
// NO SchemaValidationFailure for pre-validation errors like compilation failures |
| 318 |
validationErrors = append(validationErrors, &liberrors.ValidationError{ |
| 319 |
ValidationType: helpers.Schema, |
| 320 |
ValidationSubType: "compilation", |
| 321 |
Message: "OpenAPI document schema compilation failed", |
| 322 |
Reason: fmt.Sprintf("The OpenAPI schema failed to compile: %s", err.Error()), |
| 323 |
SpecLine: 1, |
| 324 |
SpecCol: 0, |
| 325 |
HowToFix: "check the OpenAPI schema for invalid JSON Schema syntax, complex regex patterns, or unsupported schema constructs", |
| 326 |
Context: loadedSchema, |
| 327 |
}) |
| 328 |
return false, validationErrors |
| 329 |
} |
| 330 |
|
| 331 |
// If compilation succeeded, continue with normal validation logic |
| 332 |
// (This would be the rest of the validate_document.go logic) |
| 333 |
return true, nil |
| 334 |
} |
| 335 |
|
| 336 |
func TestValidateDocument_SchemaCompilationFailure(t *testing.T) { |
| 337 |
// Test the schema compilation error handling by providing invalid JSON schema |
| 338 |
malformedSchema := `{"type": "object", "properties": {"test": invalid_json_here}}` |
| 339 |
decodedDocument := map[string]interface{}{ |
| 340 |
"openapi": "3.1.0", |
| 341 |
"info": map[string]interface{}{ |
| 342 |
"title": "Test API", |
| 343 |
"version": "1.0.0", |
| 344 |
}, |
| 345 |
} |
| 346 |
|
| 347 |
// Call our helper function which replicates the exact logic from validate_document.go |
| 348 |
valid, errors := validateOpenAPIDocumentWithMalformedSchema(malformedSchema, decodedDocument) |
| 349 |
|
| 350 |
// Should fail validation due to schema compilation error |
| 351 |
assert.False(t, valid) |
| 352 |
assert.NotEmpty(t, errors) |
| 353 |
|
| 354 |
// Verify we got a schema compilation error with the exact same structure |
| 355 |
validationError := errors[0] |
| 356 |
assert.Equal(t, helpers.Schema, validationError.ValidationType) |
| 357 |
assert.Equal(t, "compilation", validationError.ValidationSubType) |
| 358 |
assert.Equal(t, "OpenAPI document schema compilation failed", validationError.Message) |
| 359 |
assert.Contains(t, validationError.Reason, "The OpenAPI schema failed to compile") |
| 360 |
assert.Contains(t, validationError.HowToFix, "complex regex patterns") |
| 361 |
assert.Equal(t, malformedSchema, validationError.Context) |
| 362 |
assert.Equal(t, 1, validationError.SpecLine) |
| 363 |
assert.Equal(t, 0, validationError.SpecCol) |
| 364 |
|
| 365 |
// Schema compilation errors don't have SchemaValidationFailure objects |
| 366 |
assert.Empty(t, validationError.SchemaValidationErrors) |
| 367 |
} |
| 368 |
|
| 369 |
// TestValidateDocument_CompilationFailure tests the actual ValidateOpenAPIDocument function |
| 370 |
// with a corrupted document that causes schema compilation to fail |
| 371 |
func TestValidateDocument_CompilationFailure(t *testing.T) { |
| 372 |
doc, _ := libopenapi.NewDocumentWithTypeCheck([]byte(`{}`), true) |
| 373 |
doc.GetSpecInfo().APISchema = `{"type": "object", "properties": {"test": :bad"": JSON: } here.}}` |
| 374 |
// validate! |
| 375 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 376 |
assert.False(t, valid) |
| 377 |
assert.Len(t, errors, 1) |
| 378 |
assert.Contains(t, errors[0].Reason, "The OpenAPI schema failed to compile") |
| 379 |
assert.Nil(t, errors[0].SchemaValidationErrors, "Compilation errors should not have SchemaValidationErrors") |
| 380 |
} |
| 381 |
|
| 382 |
func TestValidateSchema_ValidateLicenseIdentifier(t *testing.T) { |
| 383 |
spec := `openapi: 3.1.0 |
| 384 |
info: |
| 385 |
version: 1.0.0 |
| 386 |
title: Test |
| 387 |
license: |
| 388 |
name: Apache 2.0 |
| 389 |
url: https://opensource.org/licenses/Apache-2.0 |
| 390 |
identifier: Apache-2.0 |
| 391 |
components: |
| 392 |
schemas: |
| 393 |
Pet: |
| 394 |
type: string` |
| 395 |
|
| 396 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 397 |
|
| 398 |
// validate! |
| 399 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 400 |
|
| 401 |
assert.False(t, valid) |
| 402 |
assert.Len(t, errors, 1) |
| 403 |
assert.Len(t, errors[0].SchemaValidationErrors, 1) |
| 404 |
} |
| 405 |
|
| 406 |
func TestValidateSchema_GeneratePointlessValidation(t *testing.T) { |
| 407 |
spec := `openapi: 3.1.0 |
| 408 |
info: |
| 409 |
version: 1 |
| 410 |
` |
| 411 |
|
| 412 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 413 |
|
| 414 |
// validate! |
| 415 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 416 |
|
| 417 |
assert.False(t, valid) |
| 418 |
assert.Len(t, errors, 1) |
| 419 |
assert.Len(t, errors[0].SchemaValidationErrors, 6) |
| 420 |
} |
| 421 |
|
| 422 |
func TestValidateDocument_NilSpecJSON(t *testing.T) { |
| 423 |
// Create a document with minimal valid OpenAPI content |
| 424 |
spec := `openapi: 3.1.0 |
| 425 |
info: |
| 426 |
version: 1.0.0 |
| 427 |
title: Test |
| 428 |
` |
| 429 |
|
| 430 |
doc, _ := libopenapi.NewDocument([]byte(spec)) |
| 431 |
|
| 432 |
// Simulate the nil SpecJSON scenario by setting both to nil |
| 433 |
info := doc.GetSpecInfo() |
| 434 |
info.SpecJSON = nil |
| 435 |
info.SpecJSONBytes = nil |
| 436 |
|
| 437 |
// validate! |
| 438 |
valid, errors := ValidateOpenAPIDocument(doc) |
| 439 |
|
| 440 |
// Should fail validation due to nil SpecJSON |
| 441 |
assert.False(t, valid) |
| 442 |
assert.Len(t, errors, 1) |
| 443 |
|
| 444 |
// Verify error structure |
| 445 |
validationError := errors[0] |
| 446 |
assert.Equal(t, helpers.Schema, validationError.ValidationType) |
| 447 |
assert.Equal(t, "document", validationError.ValidationSubType) |
| 448 |
assert.Equal(t, "OpenAPI document validation failed", validationError.Message) |
| 449 |
assert.Contains(t, validationError.Reason, "SpecJSON is nil") |
| 450 |
assert.Contains(t, validationError.HowToFix, "ensure the OpenAPI document is valid") |
| 451 |
assert.Equal(t, 1, validationError.SpecLine) |
| 452 |
assert.Equal(t, 0, validationError.SpecCol) |
| 453 |
|
| 454 |
// Pre-validation errors should not have SchemaValidationErrors |
| 455 |
assert.Empty(t, validationError.SchemaValidationErrors) |
| 456 |
} |
| 457 |
|
| 458 |
func TestValidateDocument_WithPrecompiledSchema(t *testing.T) { |
| 459 |
petstore, _ := os.ReadFile("../test_specs/petstorev3.json") |
| 460 |
doc, _ := libopenapi.NewDocument(petstore) |
| 461 |
|
| 462 |
info := doc.GetSpecInfo() |
| 463 |
|
| 464 |
// Pre-compile the schema |
| 465 |
options := config.NewValidationOptions() |
| 466 |
compiledSchema, err := helpers.NewCompiledSchema("schema", []byte(info.APISchema), options) |
| 467 |
assert.NoError(t, err) |
| 468 |
|
| 469 |
// Validate with precompiled schema |
| 470 |
valid, errs := ValidateOpenAPIDocumentWithPrecompiled(doc, compiledSchema) |
| 471 |
assert.True(t, valid) |
| 472 |
assert.Len(t, errs, 0) |
| 473 |
|
| 474 |
// Validate without precompiled schema (should produce identical results) |
| 475 |
valid2, errs2 := ValidateOpenAPIDocument(doc) |
| 476 |
assert.True(t, valid2) |
| 477 |
assert.Len(t, errs2, 0) |
| 478 |
} |
| 479 |
|
| 480 |
func TestValidateDocument_WithPrecompiledSchema_Invalid(t *testing.T) { |
| 481 |
petstore, _ := os.ReadFile("../test_specs/invalid_31.yaml") |
| 482 |
doc, _ := libopenapi.NewDocument(petstore) |
| 483 |
|
| 484 |
info := doc.GetSpecInfo() |
| 485 |
|
| 486 |
// Pre-compile the schema |
| 487 |
options := config.NewValidationOptions() |
| 488 |
compiledSchema, err := helpers.NewCompiledSchema("schema", []byte(info.APISchema), options) |
| 489 |
assert.NoError(t, err) |
| 490 |
|
| 491 |
// Validate with precompiled schema |
| 492 |
valid, errs := ValidateOpenAPIDocumentWithPrecompiled(doc, compiledSchema) |
| 493 |
assert.False(t, valid) |
| 494 |
assert.Len(t, errs, 1) |
| 495 |
assert.Len(t, errs[0].SchemaValidationErrors, 6) |
| 496 |
|
| 497 |
// Validate without precompiled schema (should produce identical error count) |
| 498 |
valid2, errs2 := ValidateOpenAPIDocument(doc) |
| 499 |
assert.False(t, valid2) |
| 500 |
assert.Len(t, errs2, 1) |
| 501 |
assert.Len(t, errs2[0].SchemaValidationErrors, 6) |
| 502 |
} |
| 503 |
|
| 504 |
func TestValidateDocument_SpecJSONBytesPath(t *testing.T) { |
| 505 |
petstore, _ := os.ReadFile("../test_specs/petstorev3.json") |
| 506 |
doc, _ := libopenapi.NewDocument(petstore) |
| 507 |
|
| 508 |
info := doc.GetSpecInfo() |
| 509 |
|
| 510 |
// Nil out SpecJSON but leave SpecJSONBytes intact — forces the SpecJSONBytes path |
| 511 |
assert.NotNil(t, info.SpecJSONBytes, "SpecJSONBytes should be populated by libopenapi") |
| 512 |
info.SpecJSON = nil |
| 513 |
|
| 514 |
valid, errs := ValidateOpenAPIDocument(doc) |
| 515 |
assert.True(t, valid) |
| 516 |
assert.Len(t, errs, 0) |
| 517 |
} |
| 518 |
|
| 519 |
func TestValidateDocument_SpecJSONBytesCorrupt_NilSpecJSON(t *testing.T) { |
| 520 |
petstore, _ := os.ReadFile("../test_specs/petstorev3.json") |
| 521 |
doc, _ := libopenapi.NewDocument(petstore) |
| 522 |
|
| 523 |
info := doc.GetSpecInfo() |
| 524 |
|
| 525 |
// Put corrupt bytes in SpecJSONBytes so UnmarshalJSON fails, |
| 526 |
// and nil out SpecJSON so the fallback normalizeJSON path is skipped. |
| 527 |
// This exercises the nil guard on SpecJSON inside the error branch. |
| 528 |
corrupt := []byte(`{not valid json!!!}`) |
| 529 |
info.SpecJSONBytes = &corrupt |
| 530 |
info.SpecJSON = nil |
| 531 |
|
| 532 |
// Validation should fail before JSON Schema validation instead of validating nil. |
| 533 |
valid, errs := ValidateOpenAPIDocument(doc) |
| 534 |
assert.False(t, valid) |
| 535 |
assert.Len(t, errs, 1) |
| 536 |
assert.Contains(t, errs[0].Reason, "SpecJSONBytes cannot be decoded as JSON") |
| 537 |
assert.Empty(t, errs[0].SchemaValidationErrors) |
| 538 |
} |
| 539 |
|
| 540 |
func TestValidateDocument_SpecJSONBytesCorrupt_FallbackToSpecJSON(t *testing.T) { |
| 541 |
petstore, _ := os.ReadFile("../test_specs/petstorev3.json") |
| 542 |
doc, _ := libopenapi.NewDocument(petstore) |
| 543 |
|
| 544 |
info := doc.GetSpecInfo() |
| 545 |
|
| 546 |
// Put corrupt bytes in SpecJSONBytes so UnmarshalJSON fails, |
| 547 |
// but leave SpecJSON intact so the fallback to normalizeJSON executes. |
| 548 |
corrupt := []byte(`{not valid json!!!}`) |
| 549 |
info.SpecJSONBytes = &corrupt |
| 550 |
|
| 551 |
// Should still validate successfully via the SpecJSON fallback |
| 552 |
valid, errs := ValidateOpenAPIDocument(doc) |
| 553 |
assert.True(t, valid) |
| 554 |
assert.Len(t, errs, 0) |
| 555 |
} |
| 556 |
|
| 557 |
func TestValidateDocument_SpecJSONBytesPath_Invalid(t *testing.T) { |
| 558 |
petstore, _ := os.ReadFile("../test_specs/invalid_31.yaml") |
| 559 |
doc, _ := libopenapi.NewDocument(petstore) |
| 560 |
|
| 561 |
info := doc.GetSpecInfo() |
| 562 |
|
| 563 |
// Nil out SpecJSON but leave SpecJSONBytes intact |
| 564 |
assert.NotNil(t, info.SpecJSONBytes, "SpecJSONBytes should be populated by libopenapi") |
| 565 |
info.SpecJSON = nil |
| 566 |
|
| 567 |
valid, errs := ValidateOpenAPIDocument(doc) |
| 568 |
assert.False(t, valid) |
| 569 |
assert.Len(t, errs, 1) |
| 570 |
assert.NotEmpty(t, errs[0].SchemaValidationErrors) |
| 571 |
} |