Skip to content

Commit

Permalink
fix: errors in oneOf not contain path (#676) (#677)
Browse files Browse the repository at this point in the history
  • Loading branch information
micronull authored Nov 29, 2022
1 parent df9133b commit c793660
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 11 deletions.
18 changes: 7 additions & 11 deletions openapi3/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -1679,6 +1679,12 @@ type SchemaError struct {
var _ interface{ Unwrap() error } = SchemaError{}

func markSchemaErrorKey(err error, key string) error {
var me multiErrorForOneOf

if errors.As(err, &me) {
err = me.Unwrap()
}

if v, ok := err.(*SchemaError); ok {
v.reversePath = append(v.reversePath, key)
return v
Expand All @@ -1693,17 +1699,7 @@ func markSchemaErrorKey(err error, key string) error {
}

func markSchemaErrorIndex(err error, index int) error {
if v, ok := err.(*SchemaError); ok {
v.reversePath = append(v.reversePath, strconv.FormatInt(int64(index), 10))
return v
}
if v, ok := err.(MultiError); ok {
for _, e := range v {
_ = markSchemaErrorIndex(e, index)
}
return v
}
return err
return markSchemaErrorKey(err, strconv.FormatInt(int64(index), 10))
}

func (err *SchemaError) JSONPointer() []string {
Expand Down
48 changes: 48 additions & 0 deletions openapi3/schema_oneOf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package openapi3
import (
"testing"

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

Expand Down Expand Up @@ -134,3 +135,50 @@ func TestVisitJSON_OneOf_BadDescriminatorType(t *testing.T) {
})
require.EqualError(t, err, "descriminator value is not a string")
}

func TestVisitJSON_OneOf_Path(t *testing.T) {
t.Parallel()

loader := NewLoader()
spc := `
components:
schemas:
Something:
type: object
properties:
first:
type: object
properties:
second:
type: object
properties:
third:
oneOf:
- title: First rule
type: string
minLength: 5
maxLength: 5
- title: Second rule
type: string
minLength: 10
maxLength: 10
`[1:]

doc, err := loader.LoadFromData([]byte(spc))
require.NoError(t, err)

err = doc.Components.Schemas["Something"].Value.VisitJSON(map[string]interface{}{
"first": map[string]interface{}{
"second": map[string]interface{}{
"third": "123456789",
},
},
})

assert.Contains(t, err.Error(), `Error at "/first/second/third"`)

var sErr *SchemaError

assert.ErrorAs(t, err, &sErr)
assert.Equal(t, []string{"first", "second", "third"}, sErr.JSONPointer())
}

0 comments on commit c793660

Please sign in to comment.