github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/ptr/primitive_test.go (about) 1 package ptr 2 3 import ( 4 "fmt" 5 "math" 6 "testing" 7 ) 8 9 func TestString(t *testing.T) { 10 type SomeString string 11 12 want := "123" 13 got := []*string{ 14 String("123"), 15 String(SomeString("123")), 16 String(123), 17 String(int32(123)), 18 String(int64(123)), 19 } 20 for _, x := range got { 21 if *x != want { 22 t.Fatalf("want string %q, got %+v", want, x) 23 } 24 } 25 26 want2 := fmt.Sprint(uint64(math.MaxUint64)) 27 got2 := String(uint64(math.MaxUint64)) 28 if *got2 != want2 { 29 t.Fatalf("want string %q, got %+v", want2, got2) 30 } 31 } 32 33 func TestInt(t *testing.T) { 34 want := 123 35 got := []*int{ 36 Int(int8(123)), 37 Int(int16(123)), 38 Int(int64(123)), 39 Int(uint8(123)), 40 Int(uintptr(123)), 41 } 42 for _, x := range got { 43 if *x != want { 44 t.Fatalf("want int %d, got %+v", want, x) 45 } 46 } 47 } 48 49 func TestFloat64(t *testing.T) { 50 want := float64(123) 51 got := []*float64{ 52 Float64(int8(123)), 53 Float64(uint8(123)), 54 Float64(int(123)), 55 Float64(float32(123)), 56 Float64(float64(123)), 57 } 58 for _, x := range got { 59 if *x != want { 60 t.Fatalf("want float64 %f, got %+v", want, x) 61 } 62 } 63 } 64 65 func TestDerefString(t *testing.T) { 66 type SomeString string 67 68 testCases := []*struct { 69 want string 70 got string 71 }{ 72 {"", DerefString((*string)(nil))}, 73 {"1234", DerefString(String("1234"))}, 74 {"", DerefString((*SomeString)(nil))}, 75 {"1234", DerefString(Ptr(SomeString("1234")))}, 76 } 77 for _, tc := range testCases { 78 if tc.got != tc.want { 79 t.Fatalf("want string %q, got %+v", tc.want, tc.got) 80 } 81 } 82 } 83 84 func TestDerefFloat32(t *testing.T) { 85 var x *int 86 got1 := DerefFloat32(x) 87 if got1 != float32(0) { 88 t.Fatalf("want float32 zero, but got %+v", got1) 89 } 90 91 want := float32(123) 92 got2 := []float32{ 93 DerefFloat32(Ptr(int8(123))), 94 DerefFloat32(Ptr(uint16(123))), 95 DerefFloat32(Ptr(float32(123))), 96 DerefFloat32(Ptr(float64(123))), 97 } 98 for _, x := range got2 { 99 if x != want { 100 t.Fatalf("want float32 %f, got %+v", want, x) 101 } 102 } 103 }