Unmarshal should report a type mismatch as an error (#196)

Fixes #186
This commit is contained in:
Kazuyoshi Kato
2017-10-21 15:29:03 -07:00
committed by Thomas Pelletier
parent 19ece5dc77
commit 878c11e70e
2 changed files with 30 additions and 8 deletions
+18 -5
View File
@@ -344,13 +344,26 @@ func valueFromToml(mtype reflect.Type, tval interface{}) (reflect.Value, error)
if mtype.Kind() == reflect.Ptr { if mtype.Kind() == reflect.Ptr {
return unwrapPointer(mtype, tval) return unwrapPointer(mtype, tval)
} }
switch {
case isTree(mtype): switch tval.(type) {
case *Tree:
if isTree(mtype) {
return valueFromTree(mtype, tval.(*Tree)) return valueFromTree(mtype, tval.(*Tree))
case isTreeSlice(mtype): } else {
return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to a tree", tval, tval)
}
case []*Tree:
if isTreeSlice(mtype) {
return valueFromTreeSlice(mtype, tval.([]*Tree)) return valueFromTreeSlice(mtype, tval.([]*Tree))
case isOtherSlice(mtype): } else {
return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to trees", tval, tval)
}
case []interface{}:
if isOtherSlice(mtype) {
return valueFromOtherSlice(mtype, tval.([]interface{})) return valueFromOtherSlice(mtype, tval.([]interface{}))
} else {
return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to a slice", tval, tval)
}
default: default:
switch mtype.Kind() { switch mtype.Kind() {
case reflect.Bool: case reflect.Bool:
@@ -444,7 +457,7 @@ func valueFromToml(mtype reflect.Type, tval interface{}) (reflect.Value, error)
} }
return reflect.ValueOf(val), nil return reflect.ValueOf(val), nil
default: default:
return reflect.ValueOf(nil), fmt.Errorf("Unmarshal can't handle %v(%v)", mtype, mtype.Kind()) return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to %v(%v)", tval, tval, mtype, mtype.Kind())
} }
} }
} }
+9
View File
@@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"reflect" "reflect"
"strings"
"testing" "testing"
"time" "time"
) )
@@ -508,6 +509,14 @@ func TestPointerUnmarshal(t *testing.T) {
} }
} }
func TestUnmarshalTypeMismatch(t *testing.T) {
result := pointerMarshalTestStruct{}
err := Unmarshal([]byte("List = 123"), &result)
if !strings.HasPrefix(err.Error(), "(1, 1): Can't convert 123(int64) to []string(slice)") {
t.Errorf("Type mismatch must be reported: got %v", err.Error())
}
}
type nestedMarshalTestStruct struct { type nestedMarshalTestStruct struct {
String [][]string String [][]string
//Struct [][]basicMarshalTestSubStruct //Struct [][]basicMarshalTestSubStruct