Skip to content

Commit

Permalink
Merge pull request #10 from tfrench-uber/testerrors
Browse files Browse the repository at this point in the history
validate input and output before unmarshal
  • Loading branch information
m7shapan authored Dec 31, 2021
2 parents 52c13ef + d7a0d20 commit 17c64e3
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 1 deletion.
10 changes: 9 additions & 1 deletion unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ var jsonNumberType = reflect.TypeOf(json.Number(""))

// Unmarshal used to unmarshal nested json using "njson" tag
func Unmarshal(data []byte, v interface{}) (err error) {
if !gjson.ValidBytes(data) {
return fmt.Errorf("invalid json: %v", string(data))
}

// catch code panic and return error message
defer func() {
if r := recover(); r != nil {
Expand All @@ -33,7 +37,11 @@ func Unmarshal(data []byte, v interface{}) (err error) {
}
}()

elem := reflect.ValueOf(v).Elem()
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return fmt.Errorf("can't unmarshal to invalid type %v", reflect.TypeOf(v))
}
elem := rv.Elem()
typeOfT := elem.Type()
for i := 0; i < elem.NumField(); i++ {
field := elem.Field(i)
Expand Down
71 changes: 71 additions & 0 deletions unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,77 @@ import (
"github.com/google/go-cmp/cmp"
)

func TestUnmarshalInvalidJson(t *testing.T) {
json := `
BAD JSON %% @
##
}`

type Name struct {
First string `njson:"first"`
Last string `njson:"last"`
}

type User struct {
Name Name `njson:"name"`
Age int `njson:"age"`
Friends []Name `njson:"friends"`
}

actual := User{}

if err := Unmarshal([]byte(json), &actual); err == nil {
t.Error("error should not be nil")
}
}

func TestUnmarshalError(t *testing.T) {
json := `
{
"name": {"first": "Mohamed", "last": "Shapan"},
"age": 26,
"friends": [
{"first": "Asma", "age": 26},
{"first": "Ahmed", "age": 25},
{"first": "Mahmoud", "age": 30}
]
}`

if err := Unmarshal([]byte(json), nil); err == nil {
t.Error("error should not be nil")
}
}

func TestUnmarshalByValueError(t *testing.T) {
json := `
{
"name": {"first": "Mohamed", "last": "Shapan"},
"age": 26,
"friends": [
{"first": "Asma", "age": 26},
{"first": "Ahmed", "age": 25},
{"first": "Mahmoud", "age": 30}
]
}`

type Name struct {
First string `njson:"first"`
Last string `njson:"last"`
}

type User struct {
Name Name `njson:"name"`
Age int `njson:"age"`
Friends []Name `njson:"friends"`
}

actual := User{}

if err := Unmarshal([]byte(json), actual); err == nil {
t.Error("error should not be nil")
}
}

func TestUnmarshalSmall(t *testing.T) {
json := `
{
Expand Down

0 comments on commit 17c64e3

Please sign in to comment.