Skip to content

Commit

Permalink
Validate default values against schema (getkin#610)
Browse files Browse the repository at this point in the history
  • Loading branch information
fenollp authored and d-sauer committed Sep 23, 2022
1 parent bbc2541 commit 29b0488
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
53 changes: 53 additions & 0 deletions openapi3/issue136_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package openapi3

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestIssue136(t *testing.T) {
specf := func(dflt string) string {
return `
openapi: 3.0.2
info:
title: "Hello World REST APIs"
version: "1.0"
paths: {}
components:
schemas:
SomeSchema:
type: string
default: ` + dflt + `
`
}

for _, testcase := range []struct {
dflt, err string
}{
{
dflt: `"foo"`,
err: "",
},
{
dflt: `1`,
err: "invalid components: invalid schema default: Field must be set to string or not be present",
},
} {
t.Run(testcase.dflt, func(t *testing.T) {
spec := specf(testcase.dflt)

sl := NewLoader()

doc, err := sl.LoadFromData([]byte(spec))
require.NoError(t, err)

err = doc.Validate(sl.Context)
if testcase.err == "" {
require.NoError(t, err)
} else {
require.Error(t, err, testcase.err)
}
})
}
}
6 changes: 6 additions & 0 deletions openapi3/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,12 @@ func (schema *Schema) validate(ctx context.Context, stack []*Schema) (err error)
}
}

if v := schema.Default; v != nil {
if err := schema.VisitJSON(v); err != nil {
return fmt.Errorf("invalid schema default: %w", err)
}
}

if x := schema.Example; x != nil && !validationOpts.ExamplesValidationDisabled {
if err := validateExampleValue(x, schema); err != nil {
return fmt.Errorf("invalid schema example: %w", err)
Expand Down

0 comments on commit 29b0488

Please sign in to comment.