[BUG] Nested struct with required field is not failing on decode
gaaral opened this issue · 1 comments
gaaral commented
Is there an existing issue for this?
- I have searched the existing issues
Current Behavior
The decoder doesn't fail if a required property of the nested struct is not populated.
Expected Behavior
The decoder should throw an error if a required field is missing in the nested struct.
Steps To Reproduce
Test
func TestDecoder(t *testing.T) {
type Bar struct {
Baz string `json:"baz,required"`
Qux string `json:"qux"`
}
type Foo struct {
Field string `json:"field,required"`
Bars []Bar `json:"bars"`
}
t.Run("should test nested struct", func(t *testing.T) {
payload := map[string][]string{
"field": {"foo"},
"bars.0.baz": {"baz"},
}
d := schema.NewDecoder()
d.SetAliasTag("json")
var foo Foo
err := d.Decode(&foo, payload)
assert.Nil(t, err)
})
t.Run("should fail on bars.0.baz", func(t *testing.T) {
payload := map[string][]string{
"field": {"foo"},
"bars.0.qux": {"qux"},
}
d := schema.NewDecoder()
d.SetAliasTag("json")
var foo Foo
err := d.Decode(&foo, payload)
assert.Error(t, err, "bars.0.baz is empty")
assert.NotNil(t, err)
})
t.Run("should fail for field", func(t *testing.T) {
payload := map[string][]string{
"bars.0.baz": {"baz"},
}
d := schema.NewDecoder()
d.SetAliasTag("json")
var foo Foo
err := d.Decode(&foo, payload)
assert.Error(t, err, "field is empty")
assert.NotNil(t, err)
})
}
Result
=== RUN TestDecoder
=== RUN TestDecoder/should_test_nested_struct
=== RUN TestDecoder/should_fail_on_bars.0.baz
api_test.go:291:
Error Trace:
Error: An error is expected but got nil.
Test: TestDecoder/should_fail_on_bars.0.baz
Messages: bars.0.baz is empty
api_test.go:292:
Error Trace:
Error: Expected value not to be nil.
Test: TestDecoder/should_fail_on_bars.0.baz
=== RUN TestDecoder/should_fail_for_field
--- FAIL: TestDecoder (0.00s)
--- PASS: TestDecoder/should_test_nested_struct (0.00s)
--- FAIL: TestDecoder/should_fail_on_bars.0.baz (0.00s)
--- PASS: TestDecoder/should_fail_for_field (0.00s)
FAIL
Anything else?
No response