Skip to content

Commit

Permalink
openapi3: keep oneOf context in markSchemaErrorKey (getkin#940)
Browse files Browse the repository at this point in the history
  • Loading branch information
jordan-wu-97 committed Apr 15, 2024
1 parent fb0a24e commit 254d19a
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
3 changes: 2 additions & 1 deletion openapi3/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -2122,7 +2122,8 @@ func markSchemaErrorKey(err error, key string) error {
var me multiErrorForOneOf

if errors.As(err, &me) {
err = me.Unwrap()
origin := me.Unwrap()
_ = markSchemaErrorKey(origin, key)
}

if v, ok := err.(*SchemaError); ok {
Expand Down
67 changes: 67 additions & 0 deletions openapi3/schema_issue940_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package openapi3

import (
"context"
"encoding/json"
"errors"
"testing"

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

func TestOneOfErrorPreserved(t *testing.T) {

SchemaErrorDetailsDisabled = true
defer func() { SchemaErrorDetailsDisabled = false }()

// language=json
raw := `
{
"foo": [ "bar" ]
}
`

// language=json
schema := `
{
"type": "object",
"properties": {
"foo": {
"oneOf": [
{
"type": "number"
},
{
"type": "string"
}
]
}
}
}
`

s := NewSchema()
err := s.UnmarshalJSON([]byte(schema))
require.NoError(t, err)
err = s.Validate(context.Background())
require.NoError(t, err)

obj := make(map[string]interface{})
err = json.Unmarshal([]byte(raw), &obj)
require.NoError(t, err)

err = s.VisitJSON(obj, MultiErrors())
require.Error(t, err)

var multiError MultiError
ok := errors.As(err, &multiError)
require.True(t, ok)
var schemaErr *SchemaError
ok = errors.As(multiError[0], &schemaErr)
require.True(t, ok)

require.Equal(t, "oneOf", schemaErr.SchemaField)
require.Equal(t, "value doesn't match any schema from \"oneOf\"", schemaErr.Reason)
require.Equal(t, "Error at \"/foo\": doesn't match schema due to: value must be a number Or value must be a string", schemaErr.Error())

}

0 comments on commit 254d19a

Please sign in to comment.