refactor, consistency, add test to ensure we don't need additional type check

This commit is contained in:
Sam Woodard 2018-10-05 08:57:33 -07:00
parent d05fcd97df
commit ed08d4f02a
2 changed files with 37 additions and 8 deletions

View File

@ -253,11 +253,7 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
break break
} }
// As a final catch-all, ensure types line up to avoid a runtime panic. assign(fieldValue, value)
if fieldValue.Kind() != value.Kind() {
return ErrInvalidType
}
assignValue(fieldValue, value)
} else if annotation == annotationRelation { } else if annotation == annotationRelation {
isSlice := fieldValue.Type().Kind() == reflect.Slice isSlice := fieldValue.Type().Kind() == reflect.Slice
@ -355,10 +351,11 @@ func assign(field, value reflect.Value) {
// initialize pointer so it's value // initialize pointer so it's value
// can be set by assignValue // can be set by assignValue
field.Set(reflect.New(field.Type().Elem())) field.Set(reflect.New(field.Type().Elem()))
assignValue(field.Elem(), value) field = field.Elem()
} else {
assignValue(field, value)
} }
assignValue(field, value)
} }
// assign assigns the specified value to the field, // assign assigns the specified value to the field,

View File

@ -822,6 +822,38 @@ func TestUnmarshalCustomTypeAttributes(t *testing.T) {
} }
} }
func TestUnmarshalCustomTypeAttributes_ErrInvalidType(t *testing.T) {
data := map[string]interface{}{
"data": map[string]interface{}{
"type": "customtypes",
"id": "1",
"attributes": map[string]interface{}{
"int": "bad",
"intptr": 5,
"intptrnull": nil,
"float": 1.5,
"string": "Test",
},
},
}
payload, err := json.Marshal(data)
if err != nil {
t.Fatal(err)
}
// Parse JSON API payload
customAttributeTypes := new(CustomAttributeTypes)
err = UnmarshalPayload(bytes.NewReader(payload), customAttributeTypes)
if err == nil {
t.Fatal("Expected an error unmarshalling the payload due to type mismatch, got none")
}
if err != ErrInvalidType {
t.Fatalf("Expected error to be %v, was %v", ErrInvalidType, err)
}
}
func samplePayloadWithoutIncluded() map[string]interface{} { func samplePayloadWithoutIncluded() map[string]interface{} {
return map[string]interface{}{ return map[string]interface{}{
"data": map[string]interface{}{ "data": map[string]interface{}{