gorilla / schema

Package gorilla/schema fills a struct with form values.
https://gorilla.github.io
BSD 3-Clause "New" or "Revised" License
1.39k stars 231 forks source link

[BUG] Nested struct with required field is not failing on decode #204

Open gaaral opened 1 year ago

gaaral commented 1 year ago

Is there an existing issue for this?

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

jaitaiwan commented 5 months ago

Really appreciate being given tests to add to the repo. I'm concerned that in fixing it, it might break existing user's implementations so the fix for this will probably have to be done in a major version