Skip to content

Commit

Permalink
Merge branch 'master' into development
Browse files Browse the repository at this point in the history
  • Loading branch information
stanislas-m committed Feb 14, 2019
2 parents 891bf42 + ea82301 commit 053f085
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 3 deletions.
14 changes: 11 additions & 3 deletions nulls/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
62 changes: 62 additions & 0 deletions nulls/int_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 053f085

Please sign in to comment.