1
16
17 package ptr_test
18
19 import (
20 "fmt"
21 "testing"
22
23 "k8s.io/utils/ptr"
24 )
25
26 func TestAllPtrFieldsNil(t *testing.T) {
27 testCases := []struct {
28 obj interface{}
29 expected bool
30 }{
31 {struct{}{}, true},
32 {struct{ Foo int }{12345}, true},
33 {&struct{ Foo int }{12345}, true},
34 {struct{ Foo *int }{nil}, true},
35 {&struct{ Foo *int }{nil}, true},
36 {struct {
37 Foo int
38 Bar *int
39 }{12345, nil}, true},
40 {&struct {
41 Foo int
42 Bar *int
43 }{12345, nil}, true},
44 {struct {
45 Foo *int
46 Bar *int
47 }{nil, nil}, true},
48 {&struct {
49 Foo *int
50 Bar *int
51 }{nil, nil}, true},
52 {struct{ Foo *int }{new(int)}, false},
53 {&struct{ Foo *int }{new(int)}, false},
54 {struct {
55 Foo *int
56 Bar *int
57 }{nil, new(int)}, false},
58 {&struct {
59 Foo *int
60 Bar *int
61 }{nil, new(int)}, false},
62 {(*struct{})(nil), true},
63 }
64 for i, tc := range testCases {
65 name := fmt.Sprintf("case[%d]", i)
66 t.Run(name, func(t *testing.T) {
67 if actual := ptr.AllPtrFieldsNil(tc.obj); actual != tc.expected {
68 t.Errorf("%s: expected %t, got %t", name, tc.expected, actual)
69 }
70 })
71 }
72 }
73
74 func TestRef(t *testing.T) {
75 type T int
76
77 val := T(0)
78 pointer := ptr.To(val)
79 if *pointer != val {
80 t.Errorf("expected %d, got %d", val, *pointer)
81 }
82
83 val = T(1)
84 pointer = ptr.To(val)
85 if *pointer != val {
86 t.Errorf("expected %d, got %d", val, *pointer)
87 }
88 }
89
90 func TestDeref(t *testing.T) {
91 type T int
92
93 var val, def T = 1, 0
94
95 out := ptr.Deref(&val, def)
96 if out != val {
97 t.Errorf("expected %d, got %d", val, out)
98 }
99
100 out = ptr.Deref(nil, def)
101 if out != def {
102 t.Errorf("expected %d, got %d", def, out)
103 }
104 }
105
106 func TestEqual(t *testing.T) {
107 type T int
108
109 if !ptr.Equal[T](nil, nil) {
110 t.Errorf("expected true (nil == nil)")
111 }
112 if !ptr.Equal(ptr.To(T(123)), ptr.To(T(123))) {
113 t.Errorf("expected true (val == val)")
114 }
115 if ptr.Equal(nil, ptr.To(T(123))) {
116 t.Errorf("expected false (nil != val)")
117 }
118 if ptr.Equal(ptr.To(T(123)), nil) {
119 t.Errorf("expected false (val != nil)")
120 }
121 if ptr.Equal(ptr.To(T(123)), ptr.To(T(456))) {
122 t.Errorf("expected false (val != val)")
123 }
124 }
125
View as plain text