Debian Codegraph @

api/resource/factory_test.go

raw
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package resource_test
5
6 import (
7 "fmt"
8 "strings"
9 "testing"
10
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 "sigs.k8s.io/kustomize/api/internal/loader"
14 . "sigs.k8s.io/kustomize/api/resource"
15 "sigs.k8s.io/kustomize/api/types"
16 "sigs.k8s.io/kustomize/kyaml/filesys"
17 "sigs.k8s.io/kustomize/kyaml/kio"
18 )
19
20 func TestRNodesFromBytes(t *testing.T) {
21 type testCase struct {
22 input string
23 expected []string
24 }
25 testCases := map[string]testCase{
26 "empty1": {
27 input: "",
28 expected: []string{},
29 },
30 "empty2": {
31 input: `
32 ---
33 ---
34 `,
35 expected: []string{},
36 },
37 "deployment1": {
38 input: `
39 apiVersion: apps/v1
40 kind: Deployment
41 metadata:
42 name: pooh
43 ---
44 `,
45 expected: []string{
46 `apiVersion: apps/v1
47 kind: Deployment
48 metadata:
49 name: pooh
50 `,
51 },
52 },
53 "deployment2": {
54 input: `
55 apiVersion: apps/v1
56 kind: Deployment
57 metadata:
58 annotations:
59 baseAnno: This is a base annotation
60 labels:
61 app: mungebot
62 foo: bar
63 name: baseprefix-mungebot
64 spec:
65 replicas: 1
66 selector:
67 matchLabels:
68 foo: bar
69 template:
70 metadata:
71 annotations:
72 baseAnno: This is a base annotation
73 labels:
74 app: mungebot
75 foo: bar
76 spec:
77 containers:
78 - env:
79 - name: foo
80 value: bar
81 image: nginx
82 name: nginx
83 ports:
84 - containerPort: 80
85 ---
86 apiVersion: v1
87 kind: Service
88 metadata:
89 annotations:
90 baseAnno: This is a base annotation
91 labels:
92 app: mungebot
93 foo: bar
94 name: baseprefix-mungebot-service
95 spec:
96 ports:
97 - port: 7002
98 selector:
99 app: mungebot
100 foo: bar
101 `,
102 expected: []string{
103 `apiVersion: apps/v1
104 kind: Deployment
105 metadata:
106 annotations:
107 baseAnno: This is a base annotation
108 labels:
109 app: mungebot
110 foo: bar
111 name: baseprefix-mungebot
112 spec:
113 replicas: 1
114 selector:
115 matchLabels:
116 foo: bar
117 template:
118 metadata:
119 annotations:
120 baseAnno: This is a base annotation
121 labels:
122 app: mungebot
123 foo: bar
124 spec:
125 containers:
126 - env:
127 - name: foo
128 value: bar
129 image: nginx
130 name: nginx
131 ports:
132 - containerPort: 80
133 `,
134 `apiVersion: v1
135 kind: Service
136 metadata:
137 annotations:
138 baseAnno: This is a base annotation
139 labels:
140 app: mungebot
141 foo: bar
142 name: baseprefix-mungebot-service
143 spec:
144 ports:
145 - port: 7002
146 selector:
147 app: mungebot
148 foo: bar
149 `,
150 },
151 },
152 }
153
154 for name := range testCases {
155 tc := testCases[name]
156 t.Run(name, func(t *testing.T) {
157 result, err := factory.RNodesFromBytes([]byte(tc.input))
158 if err != nil {
159 t.Fatalf("%v: fails with err: %v", name, err)
160 }
161 if len(result) != len(tc.expected) {
162 for i := range result {
163 str, err := result[i].String()
164 if err != nil {
165 t.Fatalf("%v: result to YAML fails with err: %v", name, err)
166 }
167 t.Logf("--- %d:\n%s", i, str)
168 }
169 t.Fatalf(
170 "%v: actual len %d != expected len %d",
171 name, len(result), len(tc.expected))
172 }
173 for i := range tc.expected {
174 str, err := result[i].String()
175 if err != nil {
176 t.Fatalf("%v: result to YAML fails with err: %v", name, err)
177 }
178 if str != tc.expected[i] {
179 t.Fatalf(
180 "%v: string mismatch in item %d\n"+
181 "actual:\n-----\n%s\n-----\n"+
182 "expected:\n-----\n%s\n-----\n",
183 name, i, str, tc.expected[i])
184 }
185 }
186 })
187 }
188 }
189
190 func TestSliceFromPatches(t *testing.T) {
191 patchGood1 := types.PatchStrategicMerge("patch1.yaml")
192 patch1 := `
193 apiVersion: apps/v1
194 kind: Deployment
195 metadata:
196 name: pooh
197 `
198 patchGood2 := types.PatchStrategicMerge("patch2.yaml")
199 patch2 := `
200 apiVersion: v1
201 kind: ConfigMap
202 metadata:
203 name: winnie
204 namespace: hundred-acre-wood
205 ---
206 # some comment
207 ---
208 ---
209 `
210 patchBad := types.PatchStrategicMerge("patch3.yaml")
211 patch3 := `
212 WOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOT: woot
213 `
214 patchList := types.PatchStrategicMerge("patch4.yaml")
215 patch4 := `
216 apiVersion: v1
217 kind: List
218 items:
219 - apiVersion: apps/v1
220 kind: Deployment
221 metadata:
222 name: pooh
223 - apiVersion: v1
224 kind: ConfigMap
225 metadata:
226 name: winnie
227 namespace: hundred-acre-wood
228 `
229 patchList2 := types.PatchStrategicMerge("patch5.yaml")
230 patch5 := `
231 apiVersion: v1
232 kind: DeploymentList
233 items:
234 - apiVersion: apps/v1
235 kind: Deployment
236 metadata:
237 name: deployment-a
238 spec: &hostAliases
239 template:
240 spec:
241 hostAliases:
242 - hostnames:
243 - a.example.com
244 ip: 8.8.8.8
245 - apiVersion: apps/v1
246 kind: Deployment
247 metadata:
248 name: deployment-b
249 spec:
250 <<: *hostAliases
251 `
252 patchList3 := types.PatchStrategicMerge("patch6.yaml")
253 patch6 := `
254 apiVersion: v1
255 kind: List
256 items:
257 `
258 patchList4 := types.PatchStrategicMerge("patch7.yaml")
259 patch7 := `
260 apiVersion: v1
261 kind: List
262 `
263 testDeploymentSpec := map[string]interface{}{
264 "template": map[string]interface{}{
265 "spec": map[string]interface{}{
266 "hostAliases": []interface{}{
267 map[string]interface{}{
268 "hostnames": []interface{}{
269 "a.example.com",
270 },
271 "ip": "8.8.8.8",
272 },
273 },
274 },
275 },
276 }
277 deploymentA := "deployment-a"
278 testDeploymentA, errA := factory.FromMap(
279 map[string]interface{}{
280 "apiVersion": "apps/v1",
281 "kind": "Deployment",
282 "metadata": map[string]interface{}{
283 "name": deploymentA,
284 },
285 "spec": testDeploymentSpec,
286 })
287 if errA != nil {
288 t.Fatalf("failed to create new instance with %v: %v", deploymentA, errA)
289 }
290 deploymentB := "deployment-b"
291 testDeploymentB, errB := factory.FromMap(
292 map[string]interface{}{
293 "apiVersion": "apps/v1",
294 "kind": "Deployment",
295 "metadata": map[string]interface{}{
296 "name": deploymentB,
297 },
298 "spec": testDeploymentSpec,
299 })
300 if errB != nil {
301 t.Fatalf("failed to create new instance with %v: %v", deploymentB, errB)
302 }
303
304 deploymentNoItems := "deployment-no-items"
305 testDeploymentNoItems, errNoItems := factory.FromMap(
306 map[string]interface{}{
307 "apiVersion": "v1",
308 "kind": "List",
309 },
310 )
311 if errNoItems != nil {
312 t.Fatalf("failed to create new instance with %v: %v", deploymentNoItems, testDeploymentNoItems)
313 }
314
315 fSys := filesys.MakeFsInMemory()
316 fSys.WriteFile(string(patchGood1), []byte(patch1))
317 fSys.WriteFile(string(patchGood2), []byte(patch2))
318 fSys.WriteFile(string(patchBad), []byte(patch3))
319 fSys.WriteFile(string(patchList), []byte(patch4))
320 fSys.WriteFile(string(patchList2), []byte(patch5))
321 fSys.WriteFile(string(patchList3), []byte(patch6))
322 fSys.WriteFile(string(patchList4), []byte(patch7))
323
324 ldr, err := loader.NewLoader(
325 loader.RestrictionRootOnly, filesys.Separator, fSys)
326 if err != nil {
327 t.Fatal(err)
328 }
329
330 td, err := createTestDeployment()
331 if err != nil {
332 t.Fatalf("failed to create test deployment: %v", err)
333 }
334
335 tc, err := createTestConfigMap()
336 if err != nil {
337 t.Fatalf("failed to create test config: %v", err)
338 }
339
340 tests := map[string]struct {
341 input []types.PatchStrategicMerge
342 expectedOut []*Resource
343 expectedErr bool
344 }{
345 "happy": {
346 input: []types.PatchStrategicMerge{patchGood1, patchGood2},
347 expectedOut: []*Resource{td, tc},
348 expectedErr: false,
349 },
350 "badFileName": {
351 input: []types.PatchStrategicMerge{patchGood1, "doesNotExist"},
352 expectedOut: []*Resource{},
353 expectedErr: true,
354 },
355 "badData": {
356 input: []types.PatchStrategicMerge{patchGood1, patchBad},
357 expectedOut: []*Resource{},
358 expectedErr: true,
359 },
360 "listOfPatches": {
361 input: []types.PatchStrategicMerge{patchList},
362 expectedOut: []*Resource{td, tc},
363 expectedErr: false,
364 },
365 "listWithAnchorReference": {
366 input: []types.PatchStrategicMerge{patchList2},
367 expectedOut: []*Resource{testDeploymentA, testDeploymentB},
368 expectedErr: false,
369 },
370 "listWithNoEntries": {
371 input: []types.PatchStrategicMerge{patchList3},
372 expectedOut: []*Resource{},
373 expectedErr: false,
374 },
375 "listWithNoItems": {
376 input: []types.PatchStrategicMerge{patchList4},
377 expectedOut: []*Resource{testDeploymentNoItems},
378 expectedErr: false,
379 },
380 }
381 for n, test := range tests {
382 t.Run(n, func(t *testing.T) {
383 rs, err := factory.SliceFromPatches(ldr, test.input)
384 if err != nil {
385 assert.True(t, test.expectedErr,
386 fmt.Sprintf("in test %s, got unexpected error: %v", n, err))
387 return
388 }
389 assert.False(t, test.expectedErr, "expected no error in "+n)
390 assert.Equal(t, len(test.expectedOut), len(rs))
391 for i := range rs {
392 expYaml, err := test.expectedOut[i].AsYAML()
393 require.NoError(t, err)
394 actYaml, err := rs[i].AsYAML()
395 require.NoError(t, err)
396 assert.Equal(t, expYaml, actYaml)
397 }
398 })
399 }
400 }
401
402 func TestHash(t *testing.T) {
403 input := `
404 apiVersion: v1
405 kind: ConfigMap
406 metadata:
407 name: foo
408 data:
409 one: ""
410 binaryData:
411 two: ""
412 `
413 expect := "698h7c7t9m"
414 k, err := factory.SliceFromBytes([]byte(input))
415 if err != nil {
416 t.Fatal(err)
417 }
418 result, err := k[0].Hash(factory.Hasher())
419 if err != nil {
420 t.Fatal(err)
421 }
422 if result != expect {
423 t.Fatalf("expect %s but got %s", expect, result)
424 }
425 }
426
427 func TestMoreRNodesFromBytes(t *testing.T) {
428 type expected struct {
429 out []string
430 isErr bool
431 }
432 testCases := map[string]struct {
433 input []byte
434 exp expected
435 }{
436 "garbage": {
437 input: []byte("garbageIn: garbageOut"),
438 exp: expected{
439 isErr: true,
440 },
441 },
442 "noBytes": {
443 input: []byte{},
444 exp: expected{},
445 },
446 "goodJson": {
447 input: []byte(`
448 {"apiVersion":"v1","kind":"ConfigMap","metadata":{"name":"winnie"}}
449 `),
450 exp: expected{
451 out: []string{
452 `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "winnie"}}`,
453 },
454 },
455 },
456 "goodYaml1": {
457 input: []byte(`
458 apiVersion: v1
459 kind: ConfigMap
460 metadata:
461 name: winnie
462 `),
463 exp: expected{
464 out: []string{`
465 apiVersion: v1
466 kind: ConfigMap
467 metadata:
468 name: winnie
469 `},
470 },
471 },
472 "goodYaml2": {
473 input: []byte(`
474 apiVersion: v1
475 kind: ConfigMap
476 metadata:
477 name: winnie
478 ---
479 apiVersion: v1
480 kind: ConfigMap
481 metadata:
482 name: winnie
483 `),
484 exp: expected{
485 out: []string{`
486 apiVersion: v1
487 kind: ConfigMap
488 metadata:
489 name: winnie
490 `, `
491 apiVersion: v1
492 kind: ConfigMap
493 metadata:
494 name: winnie
495 `},
496 },
497 },
498 "garbageInOneOfTwoObjects": {
499 input: []byte(`
500 apiVersion: v1
501 kind: ConfigMap
502 metadata:
503 name: winnie
504 ---
505 WOOOOOOOOOOOOOOOOOOOOOOOOT: woot
506 `),
507 exp: expected{
508 isErr: true,
509 },
510 },
511 "emptyObjects": {
512 input: []byte(`
513 ---
514 #a comment
515
516 ---
517
518 `),
519 exp: expected{
520 out: []string{},
521 },
522 },
523 "Missing .metadata.name in object": {
524 input: []byte(`
525 apiVersion: v1
526 kind: Namespace
527 metadata:
528 annotations:
529 foo: bar
530 `),
531 exp: expected{
532 isErr: true,
533 },
534 },
535 "nil value in list": {
536 input: []byte(`
537 apiVersion: builtin
538 kind: ConfigMapGenerator
539 metadata:
540 name: kube100-site
541 labels:
542 app: web
543 testList:
544 - testA
545 -
546 `),
547 exp: expected{
548 isErr: true,
549 },
550 },
551 "List": {
552 input: []byte(`
553 apiVersion: v1
554 kind: List
555 items:
556 - apiVersion: v1
557 kind: ConfigMap
558 metadata:
559 name: winnie
560 - apiVersion: v1
561 kind: ConfigMap
562 metadata:
563 name: winnie
564 `),
565 exp: expected{
566 out: []string{`
567 apiVersion: v1
568 kind: ConfigMap
569 metadata:
570 name: winnie
571 `, `
572 apiVersion: v1
573 kind: ConfigMap
574 metadata:
575 name: winnie
576 `,
577 },
578 },
579 },
580 "ConfigMapList": {
581 input: []byte(`
582 apiVersion: v1
583 kind: ConfigMapList
584 items:
585 - apiVersion: v1
586 kind: ConfigMap
587 metadata:
588 name: winnie
589 - apiVersion: v1
590 kind: ConfigMap
591 metadata:
592 name: winnie
593 `),
594 exp: expected{
595 out: []string{
596 `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "winnie"}}`,
597 `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "winnie"}}`,
598 },
599 },
600 },
601 "listWithAnchors": {
602 input: []byte(`
603 apiVersion: v1
604 kind: DeploymentList
605 items:
606 - apiVersion: apps/v1
607 kind: Deployment
608 metadata:
609 name: deployment-a
610 spec: &foo
611 template:
612 spec:
613 hostAliases:
614 - hostnames:
615 - a.example.com
616 ip: 8.8.8.8
617 - apiVersion: apps/v1
618 kind: Deployment
619 metadata:
620 name: deployment-b
621 spec:
622 *foo
623 `),
624 exp: expected{
625 out: []string{
626 `{"apiVersion": "apps/v1", "kind": "Deployment", "metadata": {"name": "deployment-a"}, ` +
627 `"spec": {"template": {"spec": {"hostAliases": [{"hostnames": ["a.example.com"], "ip": "8.8.8.8"}]}}}}`,
628 `{"apiVersion": "apps/v1", "kind": "Deployment", "metadata": {"name": "deployment-b"}, ` +
629 `"spec": {"template": {"spec": {"hostAliases": [{"hostnames": ["a.example.com"], "ip": "8.8.8.8"}]}}}}`},
630 },
631 },
632 "simpleAnchor": {
633 input: []byte(`
634 apiVersion: v1
635 kind: ConfigMap
636 metadata:
637 name: wildcard
638 data:
639 color: &color-used blue
640 feeling: *color-used
641 `),
642 exp: expected{
643 out: []string{`
644 apiVersion: v1
645 kind: ConfigMap
646 metadata:
647 name: wildcard
648 data:
649 color: blue
650 feeling: blue
651 `},
652 },
653 },
654 }
655 for n := range testCases {
656 tc := testCases[n]
657 t.Run(n, func(t *testing.T) {
658 rs, err := factory.RNodesFromBytes(tc.input)
659 if err != nil {
660 assert.True(t, tc.exp.isErr)
661 return
662 }
663 assert.False(t, tc.exp.isErr)
664 assert.Equal(t, len(tc.exp.out), len(rs))
665 for i := range rs {
666 actual, err := rs[i].String()
667 require.NoError(t, err)
668 assert.Equal(
669 t, strings.TrimSpace(tc.exp.out[i]), strings.TrimSpace(actual))
670 }
671 })
672 }
673 }
674
675 func TestDropLocalNodes(t *testing.T) {
676 testCases := map[string]struct {
677 input []byte
678 expected []byte
679 }{
680 "localConfigUnset": {
681 input: []byte(`apiVersion: v1
682 kind: ConfigMap
683 metadata:
684 name: winnie
685 `),
686 expected: []byte(`apiVersion: v1
687 kind: ConfigMap
688 metadata:
689 name: winnie
690 `),
691 },
692 "localConfigSet": {
693 input: []byte(`apiVersion: v1
694 kind: ConfigMap
695 metadata:
696 name: winnie-skip
697 annotations:
698 # this annotation causes the Resource to be ignored by kustomize
699 config.kubernetes.io/local-config: ""
700 `),
701 expected: nil,
702 },
703 "localConfigSetToTrue": {
704 input: []byte(`apiVersion: v1
705 kind: ConfigMap
706 metadata:
707 name: winnie-skip
708 annotations:
709 config.kubernetes.io/local-config: "true"
710 `),
711 expected: nil,
712 },
713 "localConfigSetToFalse": {
714 input: []byte(`apiVersion: v1
715 kind: ConfigMap
716 metadata:
717 name: winnie
718 annotations:
719 config.kubernetes.io/local-config: "false"
720 `),
721 expected: []byte(`apiVersion: v1
722 kind: ConfigMap
723 metadata:
724 annotations:
725 config.kubernetes.io/local-config: "false"
726 name: winnie
727 `),
728 },
729 "localConfigMultiInput": {
730 input: []byte(`apiVersion: v1
731 kind: ConfigMap
732 metadata:
733 name: winnie
734 ---
735 apiVersion: v1
736 kind: ConfigMap
737 metadata:
738 name: winnie-skip
739 annotations:
740 config.kubernetes.io/local-config: "true"
741 `),
742 expected: []byte(`apiVersion: v1
743 kind: ConfigMap
744 metadata:
745 name: winnie
746 `),
747 },
748 }
749 for n := range testCases {
750 tc := testCases[n]
751 t.Run(n, func(t *testing.T) {
752 nin, _ := kio.FromBytes(tc.input)
753 res, err := factory.DropLocalNodes(nin)
754 require.NoError(t, err)
755 if tc.expected == nil {
756 assert.Equal(t, 0, len(res))
757 } else {
758 actual, _ := res[0].AsYAML()
759 assert.Equal(t, tc.expected, actual)
760 }
761 })
762 }
763 }