github.com/cloudwego/hertz@v0.9.3/pkg/app/server/binding/reflect_test.go (about) 1 /* 2 * Copyright 2023 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package binding 18 19 import ( 20 "reflect" 21 "testing" 22 23 "github.com/cloudwego/hertz/pkg/common/test/assert" 24 ) 25 26 type foo struct { 27 f1 string 28 } 29 30 func TestReflect_TypeID(t *testing.T) { 31 _, intType := valueAndTypeID(int(1)) 32 _, uintType := valueAndTypeID(uint(1)) 33 _, shouldBeIntType := valueAndTypeID(int(1)) 34 assert.DeepEqual(t, intType, shouldBeIntType) 35 assert.NotEqual(t, intType, uintType) 36 37 foo1 := foo{f1: "1"} 38 foo2 := foo{f1: "2"} 39 _, foo1Type := valueAndTypeID(foo1) 40 _, foo2Type := valueAndTypeID(foo2) 41 _, foo2PointerType := valueAndTypeID(&foo2) 42 _, foo1PointerType := valueAndTypeID(&foo1) 43 assert.DeepEqual(t, foo1Type, foo2Type) 44 assert.NotEqual(t, foo1Type, foo2PointerType) 45 assert.DeepEqual(t, foo1PointerType, foo2PointerType) 46 } 47 48 func TestReflect_CheckPointer(t *testing.T) { 49 foo1 := foo{} 50 foo1Val := reflect.ValueOf(foo1) 51 err := checkPointer(foo1Val) 52 if err == nil { 53 t.Errorf("expect an err, but get nil") 54 } 55 56 foo2 := &foo{} 57 foo2Val := reflect.ValueOf(foo2) 58 err = checkPointer(foo2Val) 59 if err != nil { 60 t.Error(err) 61 } 62 63 foo3 := (*foo)(nil) 64 foo3Val := reflect.ValueOf(foo3) 65 err = checkPointer(foo3Val) 66 if err == nil { 67 t.Errorf("expect an err, but get nil") 68 } 69 } 70 71 func TestReflect_DereferPointer(t *testing.T) { 72 var foo1 ****foo 73 foo1Val := reflect.ValueOf(foo1) 74 rt := dereferPointer(foo1Val) 75 if rt.Kind() == reflect.Ptr { 76 t.Errorf("expect non-pointer type, but get pointer") 77 } 78 assert.DeepEqual(t, "foo", rt.Name()) 79 80 var foo2 foo 81 foo2Val := reflect.ValueOf(foo2) 82 rt2 := dereferPointer(foo2Val) 83 if rt2.Kind() == reflect.Ptr { 84 t.Errorf("expect non-pointer type, but get pointer") 85 } 86 assert.DeepEqual(t, "foo", rt2.Name()) 87 }