Skip to content

Commit

Permalink
Improve error message for undefined arrays of objects (#1923)
Browse files Browse the repository at this point in the history
  • Loading branch information
jsoriano authored Jun 26, 2024
1 parent c076063 commit 74d96b7
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions internal/fields/testdata/fields/fields.yml
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,5 @@
type: keyword
normalize:
- array
- name: user.group.id
type: keyword
12 changes: 12 additions & 0 deletions internal/fields/testdata/undefined-array-of-objects.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"user": {
"group": [
{
"id": "42"
},
{
"id": "0"
}
]
}
}
7 changes: 6 additions & 1 deletion internal/fields/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,12 @@ func (v *Validator) validateScalarElement(key string, val interface{}, doc commo
}

if definition == nil {
return fmt.Errorf(`field "%s" is undefined`, key)
switch val.(type) {
case []any, []map[string]interface{}:
return fmt.Errorf(`field "%s" is used as array of objects, expected explicit definition with type group or nested`, key)
default:
return fmt.Errorf(`field "%s" is undefined`, key)
}
}

// Convert numeric keyword fields to string for validation.
Expand Down
11 changes: 11 additions & 0 deletions internal/fields/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,17 @@ func TestValidate_ipAddress(t *testing.T) {
require.Empty(t, errs)
}

func TestValidate_undefinedArrayOfObjects(t *testing.T) {
validator, err := CreateValidatorForDirectory("testdata", WithSpecVersion("2.0.0"), WithDisabledDependencyManagement())
require.NoError(t, err)
require.NotNil(t, validator)

e := readSampleEvent(t, "testdata/undefined-array-of-objects.json")
errs := validator.ValidateDocumentBody(e)
require.Len(t, errs, 1)
require.Contains(t, errs[0].Error(), `field "user.group" is used as array of objects, expected explicit definition with type group or nested`)
}

func TestValidate_WithSpecVersion(t *testing.T) {
validator, err := CreateValidatorForDirectory("testdata", WithSpecVersion("2.0.0"), WithDisabledDependencyManagement())
require.NoError(t, err)
Expand Down

0 comments on commit 74d96b7

Please sign in to comment.