Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate default values against schema #610

Merged
merged 1 commit into from Sep 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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