Debian Codegraph @

pkg/apis/meta/v1/unstructured/helpers_test.go

raw
1 /*
2 Copyright 2017 The Kubernetes 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 unstructured
18
19 import (
20 "io/ioutil"
21 "math"
22 "reflect"
23 "strings"
24 "sync"
25 "testing"
26
27 runtimetesting "k8s.io/apimachinery/pkg/runtime/testing"
28
29 "github.com/stretchr/testify/assert"
30 )
31
32 // TestCodecOfUnstructuredList tests that there are no data races in Encode().
33 // i.e. that it does not mutate the object being encoded.
34 func TestCodecOfUnstructuredList(t *testing.T) {
35 var wg sync.WaitGroup
36 concurrency := 10
37 list := UnstructuredList{
38 Object: map[string]interface{}{},
39 }
40 wg.Add(concurrency)
41 for i := 0; i < concurrency; i++ {
42 go func() {
43 defer wg.Done()
44 assert.NoError(t, UnstructuredJSONScheme.Encode(&list, ioutil.Discard))
45 }()
46 }
47 wg.Wait()
48 }
49
50 func TestRemoveNestedField(t *testing.T) {
51 obj := map[string]interface{}{
52 "x": map[string]interface{}{
53 "y": 1,
54 "a": "foo",
55 },
56 }
57 RemoveNestedField(obj, "x", "a")
58 assert.Len(t, obj["x"], 1)
59 RemoveNestedField(obj, "x", "y")
60 assert.Empty(t, obj["x"])
61 RemoveNestedField(obj, "x")
62 assert.Empty(t, obj)
63 RemoveNestedField(obj, "x") // Remove of a non-existent field
64 assert.Empty(t, obj)
65 }
66
67 func TestNestedFieldNoCopy(t *testing.T) {
68 target := map[string]interface{}{"foo": "bar"}
69
70 obj := map[string]interface{}{
71 "a": map[string]interface{}{
72 "b": target,
73 "c": nil,
74 "d": []interface{}{"foo"},
75 "e": []interface{}{
76 map[string]interface{}{
77 "f": "bar",
78 },
79 },
80 },
81 }
82
83 // case 1: field exists and is non-nil
84 res, exists, err := NestedFieldNoCopy(obj, "a", "b")
85 assert.True(t, exists)
86 assert.NoError(t, err)
87 assert.Equal(t, target, res)
88 target["foo"] = "baz"
89 assert.Equal(t, target["foo"], res.(map[string]interface{})["foo"], "result should be a reference to the expected item")
90
91 // case 2: field exists and is nil
92 res, exists, err = NestedFieldNoCopy(obj, "a", "c")
93 assert.True(t, exists)
94 assert.NoError(t, err)
95 assert.Nil(t, res)
96
97 // case 3: error traversing obj
98 res, exists, err = NestedFieldNoCopy(obj, "a", "d", "foo")
99 assert.False(t, exists)
100 assert.Error(t, err)
101 assert.Nil(t, res)
102
103 // case 4: field does not exist
104 res, exists, err = NestedFieldNoCopy(obj, "a", "g")
105 assert.False(t, exists)
106 assert.NoError(t, err)
107 assert.Nil(t, res)
108
109 // case 5: intermediate field does not exist
110 res, exists, err = NestedFieldNoCopy(obj, "a", "g", "f")
111 assert.False(t, exists)
112 assert.NoError(t, err)
113 assert.Nil(t, res)
114
115 // case 6: intermediate field is null
116 // (background: happens easily in YAML)
117 res, exists, err = NestedFieldNoCopy(obj, "a", "c", "f")
118 assert.False(t, exists)
119 assert.NoError(t, err)
120 assert.Nil(t, res)
121
122 // case 7: array/slice syntax is not supported
123 // (background: users may expect this to be supported)
124 res, exists, err = NestedFieldNoCopy(obj, "a", "e[0]")
125 assert.False(t, exists)
126 assert.NoError(t, err)
127 assert.Nil(t, res)
128 }
129
130 func TestNestedFieldCopy(t *testing.T) {
131 target := map[string]interface{}{"foo": "bar"}
132
133 obj := map[string]interface{}{
134 "a": map[string]interface{}{
135 "b": target,
136 "c": nil,
137 "d": []interface{}{"foo"},
138 },
139 }
140
141 // case 1: field exists and is non-nil
142 res, exists, err := NestedFieldCopy(obj, "a", "b")
143 assert.True(t, exists)
144 assert.NoError(t, err)
145 assert.Equal(t, target, res)
146 target["foo"] = "baz"
147 assert.NotEqual(t, target["foo"], res.(map[string]interface{})["foo"], "result should be a copy of the expected item")
148
149 // case 2: field exists and is nil
150 res, exists, err = NestedFieldCopy(obj, "a", "c")
151 assert.True(t, exists)
152 assert.NoError(t, err)
153 assert.Nil(t, res)
154
155 // case 3: error traversing obj
156 res, exists, err = NestedFieldCopy(obj, "a", "d", "foo")
157 assert.False(t, exists)
158 assert.Error(t, err)
159 assert.Nil(t, res)
160
161 // case 4: field does not exist
162 res, exists, err = NestedFieldCopy(obj, "a", "e")
163 assert.False(t, exists)
164 assert.NoError(t, err)
165 assert.Nil(t, res)
166 }
167
168 func TestCacheableObject(t *testing.T) {
169 runtimetesting.CacheableObjectTest(t, UnstructuredJSONScheme)
170 }
171
172 func TestSetNestedStringSlice(t *testing.T) {
173 obj := map[string]interface{}{
174 "x": map[string]interface{}{
175 "y": 1,
176 "a": "foo",
177 },
178 }
179
180 err := SetNestedStringSlice(obj, []string{"bar"}, "x", "z")
181 assert.NoError(t, err)
182 assert.Len(t, obj["x"], 3)
183 assert.Len(t, obj["x"].(map[string]interface{})["z"], 1)
184 assert.Equal(t, "bar", obj["x"].(map[string]interface{})["z"].([]interface{})[0])
185 }
186
187 func TestSetNestedSlice(t *testing.T) {
188 obj := map[string]interface{}{
189 "x": map[string]interface{}{
190 "y": 1,
191 "a": "foo",
192 },
193 }
194
195 err := SetNestedSlice(obj, []interface{}{"bar"}, "x", "z")
196 assert.NoError(t, err)
197 assert.Len(t, obj["x"], 3)
198 assert.Len(t, obj["x"].(map[string]interface{})["z"], 1)
199 assert.Equal(t, "bar", obj["x"].(map[string]interface{})["z"].([]interface{})[0])
200 }
201
202 func TestSetNestedStringMap(t *testing.T) {
203 obj := map[string]interface{}{
204 "x": map[string]interface{}{
205 "y": 1,
206 "a": "foo",
207 },
208 }
209
210 err := SetNestedStringMap(obj, map[string]string{"b": "bar"}, "x", "z")
211 assert.NoError(t, err)
212 assert.Len(t, obj["x"], 3)
213 assert.Len(t, obj["x"].(map[string]interface{})["z"], 1)
214 assert.Equal(t, "bar", obj["x"].(map[string]interface{})["z"].(map[string]interface{})["b"])
215 }
216
217 func TestSetNestedMap(t *testing.T) {
218 obj := map[string]interface{}{
219 "x": map[string]interface{}{
220 "y": 1,
221 "a": "foo",
222 },
223 }
224
225 err := SetNestedMap(obj, map[string]interface{}{"b": "bar"}, "x", "z")
226 assert.NoError(t, err)
227 assert.Len(t, obj["x"], 3)
228 assert.Len(t, obj["x"].(map[string]interface{})["z"], 1)
229 assert.Equal(t, "bar", obj["x"].(map[string]interface{})["z"].(map[string]interface{})["b"])
230 }
231
232 func TestNestedNumberAsFloat64(t *testing.T) {
233 for _, tc := range []struct {
234 name string
235 obj map[string]interface{}
236 path []string
237 wantFloat64 float64
238 wantBool bool
239 wantErrMessage string
240 }{
241 {
242 name: "not found",
243 obj: nil,
244 path: []string{"missing"},
245 wantFloat64: 0,
246 wantBool: false,
247 wantErrMessage: "",
248 },
249 {
250 name: "found float64",
251 obj: map[string]interface{}{"value": float64(42)},
252 path: []string{"value"},
253 wantFloat64: 42,
254 wantBool: true,
255 wantErrMessage: "",
256 },
257 {
258 name: "found unexpected type bool",
259 obj: map[string]interface{}{"value": true},
260 path: []string{"value"},
261 wantFloat64: 0,
262 wantBool: false,
263 wantErrMessage: ".value accessor error: true is of the type bool, expected float64 or int64",
264 },
265 {
266 name: "found int64",
267 obj: map[string]interface{}{"value": int64(42)},
268 path: []string{"value"},
269 wantFloat64: 42,
270 wantBool: true,
271 wantErrMessage: "",
272 },
273 {
274 name: "found int64 not representable as float64",
275 obj: map[string]interface{}{"value": int64(math.MaxInt64)},
276 path: []string{"value"},
277 wantFloat64: 0,
278 wantBool: false,
279 wantErrMessage: ".value accessor error: int64 value 9223372036854775807 cannot be losslessly converted to float64",
280 },
281 } {
282 t.Run(tc.name, func(t *testing.T) {
283 gotFloat64, gotBool, gotErr := NestedNumberAsFloat64(tc.obj, tc.path...)
284 if gotFloat64 != tc.wantFloat64 {
285 t.Errorf("got %v, wanted %v", gotFloat64, tc.wantFloat64)
286 }
287 if gotBool != tc.wantBool {
288 t.Errorf("got %t, wanted %t", gotBool, tc.wantBool)
289 }
290 if tc.wantErrMessage != "" {
291 if gotErr == nil {
292 t.Errorf("got nil error, wanted %s", tc.wantErrMessage)
293 } else if gotErrMessage := gotErr.Error(); gotErrMessage != tc.wantErrMessage {
294 t.Errorf("wanted error %q, got: %v", gotErrMessage, tc.wantErrMessage)
295 }
296 } else if gotErr != nil {
297 t.Errorf("wanted nil error, got %v", gotErr)
298 }
299 })
300 }
301 }
302
303 func TestNestedNullCoercingStringMap(t *testing.T) {
304 for _, tc := range []struct {
305 name string
306 obj map[string]interface{}
307 path []string
308 wantObj map[string]string
309 wantFound bool
310 wantErrMessage string
311 }{
312 {
313 name: "missing map",
314 obj: nil,
315 path: []string{"path"},
316 wantObj: nil,
317 wantFound: false,
318 wantErrMessage: "",
319 },
320 {
321 name: "null map",
322 obj: map[string]interface{}{"path": nil},
323 path: []string{"path"},
324 wantObj: nil,
325 wantFound: true,
326 wantErrMessage: "",
327 },
328 {
329 name: "non map",
330 obj: map[string]interface{}{"path": 0},
331 path: []string{"path"},
332 wantObj: nil,
333 wantFound: false,
334 wantErrMessage: "type int",
335 },
336 {
337 name: "empty map",
338 obj: map[string]interface{}{"path": map[string]interface{}{}},
339 path: []string{"path"},
340 wantObj: map[string]string{},
341 wantFound: true,
342 wantErrMessage: "",
343 },
344 {
345 name: "string value",
346 obj: map[string]interface{}{"path": map[string]interface{}{"a": "1", "b": "2"}},
347 path: []string{"path"},
348 wantObj: map[string]string{"a": "1", "b": "2"},
349 wantFound: true,
350 wantErrMessage: "",
351 },
352 {
353 name: "null value",
354 obj: map[string]interface{}{"path": map[string]interface{}{"a": "1", "b": nil}},
355 path: []string{"path"},
356 wantObj: map[string]string{"a": "1", "b": ""},
357 wantFound: true,
358 wantErrMessage: "",
359 },
360 {
361 name: "invalid value",
362 obj: map[string]interface{}{"path": map[string]interface{}{"a": "1", "b": nil, "c": 0}},
363 path: []string{"path"},
364 wantObj: nil,
365 wantFound: false,
366 wantErrMessage: `key "c": 0`,
367 },
368 } {
369 t.Run(tc.name, func(t *testing.T) {
370 gotObj, gotFound, gotErr := NestedNullCoercingStringMap(tc.obj, tc.path...)
371 if !reflect.DeepEqual(gotObj, tc.wantObj) {
372 t.Errorf("got %#v, wanted %#v", gotObj, tc.wantObj)
373 }
374 if gotFound != tc.wantFound {
375 t.Errorf("got %v, wanted %v", gotFound, tc.wantFound)
376 }
377 if tc.wantErrMessage != "" {
378 if gotErr == nil {
379 t.Errorf("got nil error, wanted %s", tc.wantErrMessage)
380 } else if gotErrMessage := gotErr.Error(); !strings.Contains(gotErrMessage, tc.wantErrMessage) {
381 t.Errorf("wanted error %q, got: %v", gotErrMessage, tc.wantErrMessage)
382 }
383 } else if gotErr != nil {
384 t.Errorf("wanted nil error, got %v", gotErr)
385 }
386 })
387 }
388 }