diff --git a/nulls/int.go b/nulls/int.go index 5afe5349..3c406136 100644 --- a/nulls/int.go +++ b/nulls/int.go @@ -57,10 +57,18 @@ func (ns Int) MarshalJSON() ([]byte, error) { // UnmarshalJSON will unmarshal a JSON value into // the propert representation of that value. func (ns *Int) UnmarshalJSON(text []byte) error { - if i, err := strconv.ParseInt(string(text), 10, strconv.IntSize); err == nil { - ns.Valid = true - ns.Int = int(i) + txt := string(text) + ns.Valid = true + if txt == "null" { + ns.Valid = false + return nil + } + i, err := strconv.ParseInt(txt, 10, strconv.IntSize) + if err != nil { + ns.Valid = false + return err } + ns.Int = int(i) return nil } diff --git a/nulls/int_test.go b/nulls/int_test.go new file mode 100644 index 00000000..b68563c7 --- /dev/null +++ b/nulls/int_test.go @@ -0,0 +1,62 @@ +package nulls_test + +import ( + "testing" + + "github.com/gobuffalo/pop/nulls" + "github.com/stretchr/testify/require" +) + +func Test_IntUnmarshalJSON(t *testing.T) { + r := require.New(t) + cases := []struct { + Input []byte + Value int + Valid bool + }{ + { + Input: []byte{'0'}, + Value: 0, + Valid: true, + }, + { + Input: []byte{'4', '2'}, + Value: 42, + Valid: true, + }, + { + Input: []byte{'n', 'u', 'l', 'l'}, + Value: 0, + Valid: false, + }, + } + + for _, c := range cases { + i := nulls.Int{} + r.NoError(i.UnmarshalJSON(c.Input)) + r.Equal(c.Value, i.Int) + r.Equal(c.Valid, i.Valid) + } +} + +func Test_IntUnmarshalJSON_Errors(t *testing.T) { + r := require.New(t) + + cases := []struct { + Input []byte + }{ + { + Input: []byte{'a'}, + }, + { + Input: []byte{}, + }, + } + + for _, c := range cases { + i := nulls.Int{} + r.Error(i.UnmarshalJSON(c.Input)) + r.Equal(0, i.Int) + r.False(i.Valid) + } +}