Skip to content

Commit

Permalink
Validate default values against schema (#610)
Browse files Browse the repository at this point in the history
  • Loading branch information
fenollp committed Sep 21, 2022
1 parent a8f69f4 commit e03b5a8
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
@@ -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
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 e03b5a8

Please sign in to comment.