github.com/bobyang007/helper@v1.1.3/reflecth/convert_test.go (about) 1 package reflecth 2 3 import ( 4 "reflect" 5 "testing" 6 ) 7 8 func TestConvert(t *testing.T) { 9 type testElement struct { 10 x interface{} 11 t reflect.Type 12 ok bool 13 r interface{} 14 } 15 16 tests := []testElement{ 17 {int(0), TypeFloat32(), true, float32(0)}, 18 {float32(0), TypeString(), false, nil}, 19 } 20 21 for i, test := range tests { 22 if ok := ConvertibleTo(reflect.ValueOf(test.x), test.t); ok != test.ok { 23 t.Errorf("#%v expect %v, got %v", i, test.ok, ok) 24 continue 25 } 26 if r, ok := Convert(reflect.ValueOf(test.x), test.t); ok != test.ok || (ok && r.Interface() != test.r) { 27 t.Errorf("#%v expect %v %v, got %v %v", i, test.r, test.ok, r, ok) 28 continue 29 } 30 if !test.ok { // Check panic in separately 31 continue 32 } 33 if r := MustConvert(reflect.ValueOf(test.x), test.t); r.Interface() != test.r { 34 t.Errorf("#%v expect %v, got %v", i, test.r, r) 35 continue 36 } 37 } 38 } 39 40 func TestMustConvert(t *testing.T) { 41 defer func() { 42 _ = recover() 43 }() 44 _ = MustConvert(reflect.ValueOf("string"), TypeInt()) 45 t.Error("panic expected") 46 } 47 48 func TestAssign(t *testing.T) { 49 type testElement struct { 50 x interface{} 51 t reflect.Type 52 ok bool 53 r interface{} 54 } 55 56 type myType struct { 57 x int 58 } 59 60 tests := []testElement{ 61 {struct{ x int }{1}, reflect.TypeOf(myType{}), true, myType{1}}, 62 {float32(0), TypeString(), false, nil}, 63 } 64 65 for i, test := range tests { 66 if ok := AssignableTo(reflect.ValueOf(test.x), test.t); ok != test.ok { 67 t.Errorf("#%v expect %v, got %v", i, test.ok, ok) 68 continue 69 } 70 if r, ok := Assign(reflect.ValueOf(test.x), test.t); ok != test.ok || (ok && r.Interface() != test.r) { 71 t.Errorf("#%v expect %v %v, got %v %v", i, test.r, test.ok, r, ok) 72 continue 73 } 74 if !test.ok { // Check panic in separately 75 continue 76 } 77 if r := MustAssign(reflect.ValueOf(test.x), test.t); r.Interface() != test.r { 78 t.Errorf("#%v expect %v, got %v", i, test.r, r) 79 continue 80 } 81 } 82 } 83 84 func TestMustAssign(t *testing.T) { 85 defer func() { 86 _ = recover() 87 }() 88 _ = MustAssign(reflect.ValueOf("string"), TypeInt()) 89 t.Error("panic expected") 90 }