github.com/bobyang007/helper@v1.1.3/reflecth/assert_test.go (about) 1 package reflecth 2 3 import ( 4 "errors" 5 "testing" 6 ) 7 8 func TestTypeAssert(t *testing.T) { 9 b := true 10 var i interface{} = b 11 // interface with bool to bool 12 if r, ok, valid := TypeAssert(ValueOfPtr(&i), TypeBool()); !valid || !ok || r.Interface() != b { 13 t.Errorf("expect %v %v %v, got %v %v %v", b, true, true, r.Interface(), ok, valid) 14 } 15 // interface with bool to int 16 if _, ok, valid := TypeAssert(ValueOfPtr(&i), TypeInt()); !valid || ok { 17 t.Errorf("expect %v %v, got %v %v", false, true, ok, valid) 18 } 19 // interface woth bool to interface 20 if r, ok, valid := TypeAssert(ValueOfPtr(&i), TypeOfPtr(&i)); !valid || !ok || r.Interface() != b { 21 t.Errorf("expect %v %v %v, got %v %v %v", b, true, true, r.Interface(), ok, valid) 22 } 23 24 e := errors.New("str") 25 i = e 26 // error interface with error to interface 27 if r, ok, valid := TypeAssert(ValueOfPtr(&e), TypeOfPtr(&i)); !valid || !ok || r.Interface() != e { 28 t.Errorf("expect %v %v %v, got %v %v %v", e, true, true, r.Interface(), ok, valid) 29 } 30 // interface with error to error interface 31 if r, ok, valid := TypeAssert(ValueOfPtr(&i), TypeOfPtr(&e)); !valid || !ok || r.Interface() != e { 32 t.Errorf("expect %v %v %v, got %v %v %v", e, true, true, r.Interface(), ok, valid) 33 } 34 // error interface with error to bool 35 if _, ok, valid := TypeAssert(ValueOfPtr(&e), TypeBool()); valid || ok { 36 t.Errorf("expect %v %v, got %v %v", false, false, ok, valid) 37 } 38 i = b 39 // interface with error to error interface 40 if _, ok, valid := TypeAssert(ValueOfPtr(&i), TypeOfPtr(&e)); !valid || ok { 41 t.Errorf("expect %v %v, got %v %v", false, true, ok, valid) 42 } 43 44 i = nil 45 // interface with nil to bool 46 if _, ok, valid := TypeAssert(ValueOfPtr(&i), TypeBool()); !valid || ok { 47 t.Errorf("expect %v %v, got %v %v", false, true, ok, valid) 48 } 49 }