package xmlrpc import ( "reflect" "testing" "time" ) type book struct { Title string Amount int } type bookUnexported struct { title string amount int } var unmarshalTests = []struct { value interface{} ptr interface{} xml string }{ {100, new(*int), "100"}, {"Once upon a time", new(*string), "Once upon a time"}, {"Mike & Mick ", new(*string), "Mike & Mick <London, UK>"}, {"Once upon a time", new(*string), "Once upon a time"}, {"T25jZSB1cG9uIGEgdGltZQ==", new(*string), "T25jZSB1cG9uIGEgdGltZQ=="}, {true, new(*bool), "1"}, {false, new(*bool), "0"}, {12.134, new(*float32), "12.134"}, {-12.134, new(*float32), "-12.134"}, {time.Unix(1386622812, 0).UTC(), new(*time.Time), "20131209T21:00:12"}, {[]int{1, 5, 7}, new(*[]int), "157"}, {book{"War and Piece", 20}, new(*book), "TitleWar and PieceAmount20"}, {bookUnexported{}, new(*bookUnexported), "titleWar and Pieceamount20"}, {0, new(*int), ""}, {[]interface{}{"A", "5"}, new(interface{}), "A5"}, //{map[string]interface{}{"Name": "John Smith", // "Age": 6, // "Wight": []interface{}{66.67, 100.5}}, // new(interface{}), "NameJohn SmithAge6Wight66.67100.5"}, {map[string]interface{}{"Name": "John Smith"}, new(interface{}), "NameJohn Smith"}, } func Test_unmarshal(t *testing.T) { for _, tt := range unmarshalTests { v := reflect.New(reflect.TypeOf(tt.value)) if err := unmarshal([]byte(tt.xml), v.Interface()); err != nil { t.Fatalf("unmarshal error: %v", err) } v = v.Elem() if v.Kind() == reflect.Slice { vv := reflect.ValueOf(tt.value) if vv.Len() != v.Len() { t.Fatalf("unmarshal error:\nexpected: %v\n got: %v", tt.value, v.Interface()) } for i := 0; i < v.Len(); i++ { if v.Index(i).Interface() != vv.Index(i).Interface() { t.Fatalf("unmarshal error:\nexpected: %v\n got: %v", tt.value, v.Interface()) } } } else { a1 := v.Interface() a2 := interface{}(tt.value) if !reflect.DeepEqual(a1, a2) { t.Fatalf("unmarshal error:\nexpected: %v\n got: %v", tt.value, v.Interface()) } } } } func Test_unmarshalToNil(t *testing.T) { for _, tt := range unmarshalTests { if err := unmarshal([]byte(tt.xml), tt.ptr); err != nil { t.Fatalf("unmarshal error: %v", err) } } } func Test_typeMismatchError(t *testing.T) { var s string tt := unmarshalTests[0] var err error if err = unmarshal([]byte(tt.xml), &s); err == nil { t.Fatal("unmarshal error: expected error, but didn't get it") } if _, ok := err.(TypeMismatchError); !ok { t.Fatal("unmarshal error: expected type mistmatch error, but didn't get it") } } func Test_unmarshalEmptyValueTag(t *testing.T) { var v int if err := unmarshal([]byte(""), &v); err != nil { t.Fatalf("unmarshal error: %v", err) } }