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

Improve error message for undefined arrays of objects #1923

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