Debian Codegraph @

api/resource/resource_test.go

raw
1 // Copyright 2020 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package resource_test
5
6 import (
7 "fmt"
8 "reflect"
9 "testing"
10
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 "sigs.k8s.io/kustomize/api/internal/utils"
14 "sigs.k8s.io/kustomize/api/provider"
15 . "sigs.k8s.io/kustomize/api/resource"
16 "sigs.k8s.io/kustomize/api/types"
17 "sigs.k8s.io/kustomize/kyaml/resid"
18 kyaml "sigs.k8s.io/kustomize/kyaml/yaml"
19 )
20
21 var factory = provider.NewDefaultDepProvider().GetResourceFactory()
22
23 func createTestConfigMap() (*Resource, error) {
24 res, err := factory.FromMap(
25 map[string]interface{}{
26 "apiVersion": "v1",
27 "kind": "ConfigMap",
28 "metadata": map[string]interface{}{
29 "name": "winnie",
30 "namespace": "hundred-acre-wood",
31 },
32 })
33 if err != nil {
34 return nil, fmt.Errorf("failed to create test config: %w", err)
35 }
36 return res, nil
37 }
38
39 const configMapAsString = `{"apiVersion":"v1","kind":"ConfigMap","metadata":{"name":"winnie","namespace":"hundred-acre-wood"}}`
40
41 func createTestDeployment() (*Resource, error) {
42 res, err := factory.FromMap(
43 map[string]interface{}{
44 "apiVersion": "apps/v1",
45 "kind": "Deployment",
46 "metadata": map[string]interface{}{
47 "name": "pooh",
48 },
49 })
50 if err != nil {
51 return nil, fmt.Errorf("failed to create Deployment: %w", err)
52 }
53 return res, nil
54 }
55
56 const deploymentAsString = `{"apiVersion":"apps/v1","kind":"Deployment","metadata":{"name":"pooh"}}`
57
58 func TestAsYAML(t *testing.T) {
59 expected := `apiVersion: apps/v1
60 kind: Deployment
61 metadata:
62 name: pooh
63 `
64 td, err := createTestDeployment()
65 if err != nil {
66 t.Fatalf("failed to create test deployment: %s", err)
67 }
68 yaml, err := td.AsYAML()
69 if err != nil {
70 t.Fatalf("failed to get yaml: %s", err)
71 }
72 if string(yaml) != expected {
73 t.Fatalf("--- expected\n%s\n--- got\n%s\n", expected, string(yaml))
74 }
75 }
76
77 func TestResourceString(t *testing.T) {
78 td, err := createTestDeployment()
79 if err != nil {
80 t.Fatalf("failed to create test deployment: %v", err)
81 }
82 tc, err := createTestConfigMap()
83 if err != nil {
84 t.Fatalf("failed to create test config: %v", err)
85 }
86 tests := []struct {
87 in *Resource
88 s string
89 }{
90 {
91 in: tc,
92 s: configMapAsString,
93 },
94 {
95 in: td,
96 s: deploymentAsString,
97 },
98 }
99 for _, test := range tests {
100 assert.Equal(t, test.in.String(), test.s)
101 }
102 }
103
104 func TestResourceId(t *testing.T) {
105 td, err := createTestDeployment()
106 if err != nil {
107 t.Fatalf("failed to create test deployment: %v", err)
108 }
109 tc, err := createTestConfigMap()
110 if err != nil {
111 t.Fatalf("failed to create test config: %v", err)
112 }
113 tests := []struct {
114 in *Resource
115 id resid.ResId
116 }{
117 {
118 in: tc,
119 id: resid.NewResIdWithNamespace(
120 resid.NewGvk("", "v1", "ConfigMap"),
121 "winnie", "hundred-acre-wood"),
122 },
123 {
124 in: td,
125 id: resid.NewResId(
126 resid.NewGvk("apps", "v1", "Deployment"), "pooh"),
127 },
128 }
129 for _, test := range tests {
130 if test.in.OrgId() != test.id {
131 t.Fatalf("Expected %v, but got %v\n", test.id, test.in.OrgId())
132 }
133 }
134 }
135
136 func TestDeepCopy(t *testing.T) {
137 r, err := factory.FromMap(
138 map[string]interface{}{
139 "apiVersion": "apps/v1",
140 "kind": "Deployment",
141 "metadata": map[string]interface{}{
142 "name": "pooh",
143 },
144 })
145 if err != nil {
146 t.Fatalf("failed to create test config: %v", err)
147 }
148 r.AppendRefBy(resid.NewResId(resid.Gvk{Group: "somegroup", Kind: "MyKind"}, "random"))
149
150 var1 := types.Var{
151 Name: "SERVICE_ONE",
152 ObjRef: types.Target{
153 Gvk: resid.Gvk{Version: "v1", Kind: "Service"},
154 Name: "backendOne"},
155 }
156 r.AppendRefVarName(var1)
157
158 cr := r.DeepCopy()
159 if !reflect.DeepEqual(r, cr) {
160 t.Errorf("expected %v\nbut got%v", r, cr)
161 }
162 }
163
164 func TestApplySmPatch_1(t *testing.T) {
165 resource, err := factory.FromBytes([]byte(`
166 apiVersion: apps/v1
167 kind: Deployment
168 metadata:
169 annotations:
170 baseAnno: This is a base annotation
171 labels:
172 app: mungebot
173 foo: bar
174 name: bingo
175 spec:
176 replicas: 1
177 selector:
178 matchLabels:
179 foo: bar
180 template:
181 metadata:
182 labels:
183 app: mungebot
184 spec:
185 containers:
186 - env:
187 - name: foo
188 value: bar
189 image: nginx
190 name: nginx
191 ports:
192 - containerPort: 80
193 `))
194 require.NoError(t, err)
195 patch, err := factory.FromBytes([]byte(`
196 apiVersion: apps/v1
197 kind: Deployment
198 metadata:
199 name: baseprefix-mungebot
200 spec:
201 template:
202 spec:
203 containers:
204 - image: nginx
205 name: nginx
206 ports:
207 - containerPort: 777
208 `))
209 require.NoError(t, err)
210
211 require.NoError(t, resource.ApplySmPatch(patch))
212 bytes, err := resource.AsYAML()
213 require.NoError(t, err)
214 assert.Equal(t, `apiVersion: apps/v1
215 kind: Deployment
216 metadata:
217 annotations:
218 baseAnno: This is a base annotation
219 labels:
220 app: mungebot
221 foo: bar
222 name: bingo
223 spec:
224 replicas: 1
225 selector:
226 matchLabels:
227 foo: bar
228 template:
229 metadata:
230 labels:
231 app: mungebot
232 spec:
233 containers:
234 - env:
235 - name: foo
236 value: bar
237 image: nginx
238 name: nginx
239 ports:
240 - containerPort: 777
241 - containerPort: 80
242 `, string(bytes))
243 }
244
245 func TestApplySmPatch_2(t *testing.T) {
246 resource, err := factory.FromBytes([]byte(`
247 apiVersion: example.com/v1
248 kind: Foo
249 metadata:
250 name: my-foo
251 spec:
252 bar:
253 A: X
254 B: Y
255 `))
256 require.NoError(t, err)
257 patch, err := factory.FromBytes([]byte(`
258 apiVersion: example.com/v1
259 kind: Foo
260 metadata:
261 name: my-foo
262 spec:
263 bar:
264 B:
265 C: Z
266 D: W
267 baz:
268 hello: world
269 `))
270 require.NoError(t, err)
271 require.NoError(t, resource.ApplySmPatch(patch))
272 bytes, err := resource.AsYAML()
273 require.NoError(t, err)
274 assert.Equal(t, `apiVersion: example.com/v1
275 kind: Foo
276 metadata:
277 name: my-foo
278 spec:
279 bar:
280 A: X
281 C: Z
282 D: W
283 baz:
284 hello: world
285 `, string(bytes))
286 }
287
288 func TestApplySmPatch_3(t *testing.T) {
289 resource, err := factory.FromBytes([]byte(`
290 apiVersion: v1
291 kind: Deployment
292 metadata:
293 name: clown
294 spec:
295 numReplicas: 1
296 `))
297 require.NoError(t, err)
298 patch, err := factory.FromBytes([]byte(`
299 apiVersion: v1
300 kind: Deployment
301 metadata:
302 name: clown
303 spec:
304 numReplicas: 999
305 `))
306 require.NoError(t, err)
307 require.NoError(t, resource.ApplySmPatch(patch))
308 bytes, err := resource.AsYAML()
309 require.NoError(t, err)
310 assert.Equal(t, `apiVersion: v1
311 kind: Deployment
312 metadata:
313 name: clown
314 spec:
315 numReplicas: 999
316 `, string(bytes))
317 }
318
319 // regression test for https://github.com/kubernetes-sigs/kustomize/issues/5031
320 func TestApplySmPatch_Idempotency(t *testing.T) {
321 // an arbitrary number of times to apply the patch
322 patchApplyCount := 4
323 resourceYaml := `apiVersion: v1
324 kind: Deployment
325 metadata:
326 creationTimestamp: null
327 labels: null
328 name: my-deployment
329 `
330 resource, err := factory.FromBytes([]byte(resourceYaml))
331 require.NoError(t, err)
332
333 noOpPatch, err := factory.FromBytes([]byte(`
334 apiVersion: v1
335 kind: Deployment
336 metadata:
337 name: my-deployment
338 `))
339 require.NoError(t, err)
340
341 for i := 0; i < patchApplyCount; i++ {
342 require.NoError(t, resource.ApplySmPatch(noOpPatch))
343
344 bytes, err := resource.AsYAML()
345 require.NoError(t, err)
346
347 require.Equal(
348 t,
349 resourceYaml,
350 string(bytes),
351 "resource should be unchanged after re-application of patch",
352 )
353 }
354 }
355
356 func TestApplySmPatchShouldOutputListItemsInCorrectOrder(t *testing.T) {
357 cases := []struct {
358 name string
359 skip bool
360 patch string
361 expectedOutput string
362 }{
363 {
364 name: "Order should not change when patch has foo only",
365 patch: `apiVersion: v1
366 kind: Pod
367 metadata:
368 name: test
369 spec:
370 initContainers:
371 - name: foo
372 `,
373 expectedOutput: `apiVersion: v1
374 kind: Pod
375 metadata:
376 name: test
377 spec:
378 initContainers:
379 - name: foo
380 - name: bar
381 `,
382 },
383 {
384 name: "Order changes when patch has bar only",
385 patch: `apiVersion: v1
386 kind: Pod
387 metadata:
388 name: test
389 spec:
390 initContainers:
391 - name: bar
392 `,
393 // This test records current behavior, but this behavior might be undesirable.
394 // If so, feel free to change the test to pass with some improved algorithm.
395 expectedOutput: `apiVersion: v1
396 kind: Pod
397 metadata:
398 name: test
399 spec:
400 initContainers:
401 - name: bar
402 - name: foo
403 `,
404 },
405 {
406 name: "Order should not change and should include a new item at the beginning when patch has a new list item",
407 patch: `apiVersion: v1
408 kind: Pod
409 metadata:
410 name: test
411 spec:
412 initContainers:
413 - name: baz
414 `,
415 expectedOutput: `apiVersion: v1
416 kind: Pod
417 metadata:
418 name: test
419 spec:
420 initContainers:
421 - name: baz
422 - name: foo
423 - name: bar
424 `,
425 },
426 {
427 name: "Order should not change when patch has foo and bar in same order",
428 patch: `apiVersion: v1
429 kind: Pod
430 metadata:
431 name: test
432 spec:
433 initContainers:
434 - name: foo
435 - name: bar
436 `,
437 expectedOutput: `apiVersion: v1
438 kind: Pod
439 metadata:
440 name: test
441 spec:
442 initContainers:
443 - name: foo
444 - name: bar
445 `,
446 },
447 {
448 name: "Order should change when patch has foo and bar in different order",
449 patch: `apiVersion: v1
450 kind: Pod
451 metadata:
452 name: test
453 spec:
454 initContainers:
455 - name: bar
456 - name: foo
457 `,
458 expectedOutput: `apiVersion: v1
459 kind: Pod
460 metadata:
461 name: test
462 spec:
463 initContainers:
464 - name: bar
465 - name: foo
466 `,
467 },
468 }
469 for _, tc := range cases {
470 t.Run(tc.name, func(t *testing.T) {
471 if tc.skip {
472 t.Skip()
473 }
474
475 resource, err := factory.FromBytes([]byte(`
476 apiVersion: v1
477 kind: Pod
478 metadata:
479 name: test
480 spec:
481 initContainers:
482 - name: foo
483 - name: bar
484 `))
485 require.NoError(t, err)
486
487 patch, err := factory.FromBytes([]byte(tc.patch))
488 require.NoError(t, err)
489 require.NoError(t, resource.ApplySmPatch(patch))
490 bytes, err := resource.AsYAML()
491 require.NoError(t, err)
492 assert.Equal(t, tc.expectedOutput, string(bytes))
493 })
494 }
495 }
496
497 func TestApplySmPatchShouldOutputPrimitiveListItemsInCorrectOrder(t *testing.T) {
498 cases := []struct {
499 name string
500 skip bool
501 patch string
502 expectedOutput string
503 }{
504 {
505 name: "Order should not change when patch has foo only",
506 patch: `apiVersion: v1
507 kind: Pod
508 metadata:
509 name: test
510 finalizers: ["foo"]
511 `,
512 expectedOutput: `apiVersion: v1
513 kind: Pod
514 metadata:
515 finalizers:
516 - foo
517 - bar
518 name: test
519 `,
520 },
521 {
522 name: "Order should not change when patch has bar only",
523 skip: true, // TODO: This test should pass but fails currently. Fix the problem and unskip this test
524 patch: `apiVersion: v1
525 kind: Pod
526 metadata:
527 name: test
528 finalizers: ["bar"]
529 `,
530 expectedOutput: `apiVersion: v1
531 kind: Pod
532 metadata:
533 finalizers:
534 - foo
535 - bar
536 name: test
537 `,
538 },
539 {
540 name: "Order should not change and should include a new item at the beginning when patch has a new list item",
541 patch: `apiVersion: v1
542 kind: Pod
543 metadata:
544 name: test
545 finalizers: ["baz"]
546 `,
547 expectedOutput: `apiVersion: v1
548 kind: Pod
549 metadata:
550 finalizers:
551 - baz
552 - foo
553 - bar
554 name: test
555 `,
556 },
557 {
558 name: "Order should not change when patch has foo and bar in same order",
559 patch: `apiVersion: v1
560 kind: Pod
561 metadata:
562 name: test
563 finalizers: ["foo", "bar"]
564 `,
565 expectedOutput: `apiVersion: v1
566 kind: Pod
567 metadata:
568 finalizers:
569 - foo
570 - bar
571 name: test
572 `,
573 },
574 {
575 name: "Order should change when patch has foo and bar in different order",
576 patch: `apiVersion: v1
577 kind: Pod
578 metadata:
579 name: test
580 finalizers: ["bar", "foo"]
581 `,
582 expectedOutput: `apiVersion: v1
583 kind: Pod
584 metadata:
585 finalizers:
586 - bar
587 - foo
588 name: test
589 `,
590 },
591 }
592 for _, tc := range cases {
593 t.Run(tc.name, func(t *testing.T) {
594 if tc.skip {
595 t.Skip()
596 }
597
598 resource, err := factory.FromBytes([]byte(`
599 kind: Pod
600 metadata:
601 name: test
602 finalizers: ["foo", "bar"]
603 `))
604 require.NoError(t, err)
605
606 patch, err := factory.FromBytes([]byte(tc.patch))
607 require.NoError(t, err)
608 require.NoError(t, resource.ApplySmPatch(patch))
609 bytes, err := resource.AsYAML()
610 require.NoError(t, err)
611 assert.Equal(t, tc.expectedOutput, string(bytes))
612 })
613 }
614 }
615
616 func TestMergeDataMapFrom(t *testing.T) {
617 resource, err := factory.FromBytes([]byte(`
618 apiVersion: v1
619 kind: BlahBlah
620 metadata:
621 name: clown
622 data:
623 fruit: pear
624 `))
625 if !assert.NoError(t, err) {
626 t.FailNow()
627 }
628 patch, err := factory.FromBytes([]byte(`
629 apiVersion: v1
630 kind: Whatever
631 metadata:
632 name: spaceship
633 data:
634 spaceship: enterprise
635 `))
636 if !assert.NoError(t, err) {
637 t.FailNow()
638 }
639 resource.MergeDataMapFrom(patch)
640 bytes, err := resource.AsYAML()
641 require.NoError(t, err)
642 assert.Equal(t, `apiVersion: v1
643 data:
644 fruit: pear
645 spaceship: enterprise
646 kind: BlahBlah
647 metadata:
648 name: clown
649 `, string(bytes))
650 }
651
652 func TestApplySmPatch_SwapOrder(t *testing.T) {
653 s1 := `
654 apiVersion: example.com/v1
655 kind: Foo
656 metadata:
657 name: my-foo
658 spec:
659 bar:
660 B:
661 C: Z
662 `
663 s2 := `
664 apiVersion: example.com/v1
665 kind: Foo
666 metadata:
667 name: my-foo
668 spec:
669 bar:
670 C: Z
671 D: W
672 baz:
673 hello: world
674 `
675 expected := `apiVersion: example.com/v1
676 kind: Foo
677 metadata:
678 name: my-foo
679 spec:
680 bar:
681 C: Z
682 D: W
683 baz:
684 hello: world
685 `
686 r1, err := factory.FromBytes([]byte(s1))
687 require.NoError(t, err)
688 r2, err := factory.FromBytes([]byte(s2))
689 require.NoError(t, err)
690 require.NoError(t, r1.ApplySmPatch(r2))
691 bytes, err := r1.AsYAML()
692 require.NoError(t, err)
693 assert.Equal(t, expected, string(bytes))
694
695 r1, _ = factory.FromBytes([]byte(s1))
696 r2, _ = factory.FromBytes([]byte(s2))
697 require.NoError(t, r2.ApplySmPatch(r1))
698 bytes, err = r2.AsYAML()
699 require.NoError(t, err)
700 assert.Equal(t, expected, string(bytes))
701 }
702
703 func TestApplySmPatch(t *testing.T) {
704 const (
705 myDeployment = "Deployment"
706 myCRD = "myCRD"
707 )
708
709 tests := map[string]struct {
710 base string
711 patch []string
712 expected string
713 errorExpected bool
714 errorMsg string
715 }{
716 "withschema-label-image-container": {
717 base: baseResource(myDeployment),
718 patch: []string{
719 addLabelAndEnvPatch(myDeployment),
720 changeImagePatch(myDeployment, "nginx:latest"),
721 addContainerAndEnvPatch(myDeployment),
722 },
723 errorExpected: false,
724 expected: expectedResultMultiPatch(myDeployment, false),
725 },
726 "withschema-image-container-label": {
727 base: baseResource(myDeployment),
728 patch: []string{
729 changeImagePatch(myDeployment, "nginx:latest"),
730 addContainerAndEnvPatch(myDeployment),
731 addLabelAndEnvPatch(myDeployment),
732 },
733 errorExpected: false,
734 expected: expectedResultMultiPatch(myDeployment, true),
735 },
736 "withschema-container-label-image": {
737 base: baseResource(myDeployment),
738 patch: []string{
739 addContainerAndEnvPatch(myDeployment),
740 addLabelAndEnvPatch(myDeployment),
741 changeImagePatch(myDeployment, "nginx:latest"),
742 },
743 errorExpected: false,
744 expected: expectedResultMultiPatch(myDeployment, true),
745 },
746 "noschema-label-image-container": {
747 base: baseResource(myCRD),
748 patch: []string{
749 addLabelAndEnvPatch(myCRD),
750 changeImagePatch(myCRD, "nginx:latest"),
751 addContainerAndEnvPatch(myCRD),
752 },
753 // Might be better if this complained about patch conflict.
754 // See plugin/builtin/patchstrategicmergetransformer/psmt_test.go
755 expected: `apiVersion: apps/v1
756 kind: myCRD
757 metadata:
758 name: deploy1
759 spec:
760 template:
761 metadata:
762 labels:
763 old-label: old-value
764 some-label: some-value
765 spec:
766 containers:
767 - env:
768 - name: ANOTHERENV
769 value: ANOTHERVALUE
770 name: nginx
771 - image: anotherimage
772 name: anothercontainer
773 `,
774 },
775 "noschema-image-container-label": {
776 base: baseResource(myCRD),
777 patch: []string{
778 changeImagePatch(myCRD, "nginx:latest"),
779 addContainerAndEnvPatch(myCRD),
780 addLabelAndEnvPatch(myCRD),
781 },
782 // Might be better if this complained about patch conflict.
783 expected: `apiVersion: apps/v1
784 kind: myCRD
785 metadata:
786 name: deploy1
787 spec:
788 template:
789 metadata:
790 labels:
791 old-label: old-value
792 some-label: some-value
793 spec:
794 containers:
795 - env:
796 - name: SOMEENV
797 value: SOMEVALUE
798 name: nginx
799 `,
800 },
801 "noschema-container-label-image": {
802 base: baseResource(myCRD),
803 patch: []string{
804 addContainerAndEnvPatch(myCRD),
805 addLabelAndEnvPatch(myCRD),
806 changeImagePatch(myCRD, "nginx:latest"),
807 },
808 // Might be better if this complained about patch conflict.
809 expected: `apiVersion: apps/v1
810 kind: myCRD
811 metadata:
812 name: deploy1
813 spec:
814 template:
815 metadata:
816 labels:
817 old-label: old-value
818 some-label: some-value
819 spec:
820 containers:
821 - image: nginx:latest
822 name: nginx
823 `,
824 },
825
826 "withschema-label-latest-someV-01": {
827 base: baseResource(myDeployment),
828 patch: []string{
829 addLabelAndEnvPatch(myDeployment),
830 changeImagePatch(myDeployment, "nginx:latest"),
831 changeImagePatch(myDeployment, "nginx:1.7.9"),
832 },
833 expected: `apiVersion: apps/v1
834 kind: Deployment
835 metadata:
836 name: deploy1
837 spec:
838 template:
839 metadata:
840 labels:
841 old-label: old-value
842 some-label: some-value
843 spec:
844 containers:
845 - env:
846 - name: SOMEENV
847 value: SOMEVALUE
848 image: nginx:1.7.9
849 name: nginx
850 `,
851 },
852 "withschema-latest-label-someV-02": {
853 base: baseResource(myDeployment),
854 patch: []string{
855 changeImagePatch(myDeployment, "nginx:latest"),
856 addLabelAndEnvPatch(myDeployment),
857 changeImagePatch(myDeployment, "nginx:1.7.9"),
858 },
859 expected: `apiVersion: apps/v1
860 kind: Deployment
861 metadata:
862 name: deploy1
863 spec:
864 template:
865 metadata:
866 labels:
867 old-label: old-value
868 some-label: some-value
869 spec:
870 containers:
871 - env:
872 - name: SOMEENV
873 value: SOMEVALUE
874 image: nginx:1.7.9
875 name: nginx
876 `,
877 },
878 "withschema-latest-label-someV-03": {
879 base: baseResource(myDeployment),
880 patch: []string{
881 changeImagePatch(myDeployment, "nginx:1.7.9"),
882 addLabelAndEnvPatch(myDeployment),
883 changeImagePatch(myDeployment, "nginx:latest"),
884 },
885 expected: `apiVersion: apps/v1
886 kind: Deployment
887 metadata:
888 name: deploy1
889 spec:
890 template:
891 metadata:
892 labels:
893 old-label: old-value
894 some-label: some-value
895 spec:
896 containers:
897 - env:
898 - name: SOMEENV
899 value: SOMEVALUE
900 image: nginx:latest
901 name: nginx
902 `,
903 },
904 "withschema-latest-label-someV-04": {
905 base: baseResource(myDeployment),
906 patch: []string{
907 changeImagePatch(myDeployment, "nginx:1.7.9"),
908 changeImagePatch(myDeployment, "nginx:latest"),
909 addLabelAndEnvPatch(myDeployment),
910 changeImagePatch(myDeployment, "nginx:nginx"),
911 },
912 expected: `apiVersion: apps/v1
913 kind: Deployment
914 metadata:
915 name: deploy1
916 spec:
917 template:
918 metadata:
919 labels:
920 old-label: old-value
921 some-label: some-value
922 spec:
923 containers:
924 - env:
925 - name: SOMEENV
926 value: SOMEVALUE
927 image: nginx:nginx
928 name: nginx
929 `,
930 },
931 "noschema-latest-label-someV-01": {
932 base: baseResource(myCRD),
933 patch: []string{
934 addLabelAndEnvPatch(myCRD),
935 changeImagePatch(myCRD, "nginx:latest"),
936 changeImagePatch(myCRD, "nginx:1.7.9"),
937 },
938 expected: `apiVersion: apps/v1
939 kind: myCRD
940 metadata:
941 name: deploy1
942 spec:
943 template:
944 metadata:
945 labels:
946 old-label: old-value
947 some-label: some-value
948 spec:
949 containers:
950 - image: nginx:1.7.9
951 name: nginx
952 `,
953 },
954 "noschema-latest-label-someV-02": {
955 base: baseResource(myCRD),
956 patch: []string{
957 changeImagePatch(myCRD, "nginx:latest"),
958 addLabelAndEnvPatch(myCRD),
959 changeImagePatch(myCRD, "nginx:1.7.9"),
960 },
961 expected: expectedResultJMP("nginx:1.7.9"),
962 },
963 "noschema-latest-label-someV-03": {
964 base: baseResource(myCRD),
965 patch: []string{
966 changeImagePatch(myCRD, "nginx:1.7.9"),
967 addLabelAndEnvPatch(myCRD),
968 changeImagePatch(myCRD, "nginx:latest"),
969 },
970 expected: `apiVersion: apps/v1
971 kind: myCRD
972 metadata:
973 name: deploy1
974 spec:
975 template:
976 metadata:
977 labels:
978 old-label: old-value
979 some-label: some-value
980 spec:
981 containers:
982 - image: nginx:latest
983 name: nginx
984 `,
985 },
986 "noschema-latest-label-someV-04": {
987 base: baseResource(myCRD),
988 patch: []string{
989 changeImagePatch(myCRD, "nginx:1.7.9"),
990 changeImagePatch(myCRD, "nginx:latest"),
991 addLabelAndEnvPatch(myCRD),
992 changeImagePatch(myCRD, "nginx:nginx"),
993 },
994 expected: `apiVersion: apps/v1
995 kind: myCRD
996 metadata:
997 name: deploy1
998 spec:
999 template:
1000 metadata:
1001 labels:
1002 old-label: old-value
1003 some-label: some-value
1004 spec:
1005 containers:
1006 - image: nginx:nginx
1007 name: nginx
1008 `,
1009 },
1010 }
1011
1012 for name, test := range tests {
1013 resource, err := factory.FromBytes([]byte(test.base))
1014 require.NoError(t, err)
1015 for _, p := range test.patch {
1016 patch, err := factory.FromBytes([]byte(p))
1017 require.NoError(t, err, name)
1018 require.NoError(t, resource.ApplySmPatch(patch), name)
1019 }
1020 bytes, err := resource.AsYAML()
1021 if test.errorExpected {
1022 require.Error(t, err, name)
1023 } else {
1024 require.NoError(t, err, name)
1025 assert.Equal(t, test.expected, string(bytes), name)
1026 }
1027 }
1028 }
1029
1030 func TestResourceStorePreviousId(t *testing.T) {
1031 tests := map[string]struct {
1032 input string
1033 newName string
1034 newNs string
1035 expected string
1036 }{
1037 "default namespace, first previous name": {
1038 input: `apiVersion: apps/v1
1039 kind: Secret
1040 metadata:
1041 name: oldName
1042 `,
1043 newName: "newName",
1044 newNs: "",
1045 expected: `apiVersion: apps/v1
1046 kind: Secret
1047 metadata:
1048 annotations:
1049 internal.config.kubernetes.io/previousKinds: Secret
1050 internal.config.kubernetes.io/previousNames: oldName
1051 internal.config.kubernetes.io/previousNamespaces: default
1052 name: newName
1053 `,
1054 },
1055
1056 "default namespace, second previous name": {
1057 input: `apiVersion: apps/v1
1058 kind: Secret
1059 metadata:
1060 annotations:
1061 internal.config.kubernetes.io/previousKinds: Secret
1062 internal.config.kubernetes.io/previousNames: oldName
1063 internal.config.kubernetes.io/previousNamespaces: default
1064 name: oldName2
1065 `,
1066 newName: "newName",
1067 newNs: "",
1068 expected: `apiVersion: apps/v1
1069 kind: Secret
1070 metadata:
1071 annotations:
1072 internal.config.kubernetes.io/previousKinds: Secret,Secret
1073 internal.config.kubernetes.io/previousNames: oldName,oldName2
1074 internal.config.kubernetes.io/previousNamespaces: default,default
1075 name: newName
1076 `,
1077 },
1078
1079 "non-default namespace": {
1080 input: `apiVersion: apps/v1
1081 kind: Secret
1082 metadata:
1083 annotations:
1084 internal.config.kubernetes.io/previousKinds: Secret
1085 internal.config.kubernetes.io/previousNames: oldName
1086 internal.config.kubernetes.io/previousNamespaces: default
1087 name: oldName2
1088 namespace: oldNamespace
1089 `,
1090 newName: "newName",
1091 newNs: "newNamespace",
1092 expected: `apiVersion: apps/v1
1093 kind: Secret
1094 metadata:
1095 annotations:
1096 internal.config.kubernetes.io/previousKinds: Secret,Secret
1097 internal.config.kubernetes.io/previousNames: oldName,oldName2
1098 internal.config.kubernetes.io/previousNamespaces: default,oldNamespace
1099 name: newName
1100 namespace: newNamespace
1101 `,
1102 },
1103 }
1104 factory := provider.NewDefaultDepProvider().GetResourceFactory()
1105 for i := range tests {
1106 test := tests[i]
1107 t.Run(i, func(t *testing.T) {
1108 resources, err := factory.SliceFromBytes([]byte(test.input))
1109 if !assert.NoError(t, err) || len(resources) == 0 {
1110 t.FailNow()
1111 }
1112 r := resources[0]
1113 r.StorePreviousId()
1114 r.SetName(test.newName)
1115 if test.newNs != "" {
1116 r.SetNamespace(test.newNs)
1117 }
1118 bytes, err := r.AsYAML()
1119 if !assert.NoError(t, err) {
1120 t.FailNow()
1121 }
1122 assert.Equal(t, test.expected, string(bytes))
1123 })
1124 }
1125 }
1126
1127 func TestResource_PrevIds(t *testing.T) {
1128 tests := map[string]struct {
1129 input string
1130 expected []resid.ResId
1131 }{
1132 "no previous IDs": {
1133 input: `apiVersion: apps/v1
1134 kind: Secret
1135 metadata:
1136 name: name
1137 `,
1138 expected: nil,
1139 },
1140
1141 "one previous ID": {
1142 input: `apiVersion: apps/v1
1143 kind: Secret
1144 metadata:
1145 annotations:
1146 internal.config.kubernetes.io/previousKinds: Secret
1147 internal.config.kubernetes.io/previousNames: oldName
1148 internal.config.kubernetes.io/previousNamespaces: default
1149 name: newName
1150 `,
1151 expected: []resid.ResId{
1152 {
1153 Gvk: resid.Gvk{Group: "apps", Version: "v1", Kind: "Secret"},
1154 Name: "oldName",
1155 Namespace: resid.DefaultNamespace,
1156 },
1157 },
1158 },
1159
1160 "two ids": {
1161 input: `apiVersion: apps/v1
1162 kind: Secret
1163 metadata:
1164 annotations:
1165 internal.config.kubernetes.io/previousKinds: Secret,Secret
1166 internal.config.kubernetes.io/previousNames: oldName,oldName2
1167 internal.config.kubernetes.io/previousNamespaces: default,oldNamespace
1168 name: newName
1169 namespace: newNamespace
1170 `,
1171 expected: []resid.ResId{
1172 {
1173 Gvk: resid.Gvk{Group: "apps", Version: "v1", Kind: "Secret"},
1174 Name: "oldName",
1175 Namespace: resid.DefaultNamespace,
1176 },
1177 {
1178 Gvk: resid.Gvk{Group: "apps", Version: "v1", Kind: "Secret"},
1179 Name: "oldName2",
1180 Namespace: "oldNamespace",
1181 },
1182 },
1183 },
1184 }
1185 factory := provider.NewDefaultDepProvider().GetResourceFactory()
1186 for i := range tests {
1187 test := tests[i]
1188 t.Run(i, func(t *testing.T) {
1189 resources, err := factory.SliceFromBytes([]byte(test.input))
1190 if !assert.NoError(t, err) || len(resources) == 0 {
1191 t.FailNow()
1192 }
1193 r := resources[0]
1194 assert.Equal(t, test.expected, r.PrevIds())
1195 })
1196 }
1197 }
1198
1199 // baseResource produces a base object which used to test
1200 // patch transformation
1201 // Also the structure is matching the Deployment syntax
1202 // the kind can be replaced to allow testing using CRD
1203 // without access to the schema
1204 func baseResource(kind string) string {
1205 res := `
1206 apiVersion: apps/v1
1207 kind: %s
1208 metadata:
1209 name: deploy1
1210 spec:
1211 template:
1212 metadata:
1213 labels:
1214 old-label: old-value
1215 spec:
1216 containers:
1217 - name: nginx
1218 image: nginx`
1219 return fmt.Sprintf(res, kind)
1220 }
1221
1222 // addContainerAndEnvPatch produces a patch object which adds
1223 // an entry in the env slice of the first/nginx container
1224 // as well as adding a label in the metadata
1225 // Note that for SMP/WithSchema merge, the name:nginx entry
1226 // is mandatory
1227 func addLabelAndEnvPatch(kind string) string {
1228 return fmt.Sprintf(`
1229 apiVersion: apps/v1
1230 kind: %s
1231 metadata:
1232 name: deploy1
1233 spec:
1234 template:
1235 metadata:
1236 labels:
1237 some-label: some-value
1238 spec:
1239 containers:
1240 - name: nginx
1241 env:
1242 - name: SOMEENV
1243 value: SOMEVALUE`, kind)
1244 }
1245
1246 // addContainerAndEnvPatch produces a patch object which adds
1247 // an entry in the env slice of the first/nginx container
1248 // as well as adding a second container in the container list
1249 // Note that for SMP/WithSchema merge, the name:nginx entry
1250 // is mandatory
1251 func addContainerAndEnvPatch(kind string) string {
1252 return fmt.Sprintf(`
1253 apiVersion: apps/v1
1254 kind: %s
1255 metadata:
1256 name: deploy1
1257 spec:
1258 template:
1259 spec:
1260 containers:
1261 - name: nginx
1262 env:
1263 - name: ANOTHERENV
1264 value: ANOTHERVALUE
1265 - name: anothercontainer
1266 image: anotherimage`, kind)
1267 }
1268
1269 // addContainerAndEnvPatch produces a patch object which replaces
1270 // the value of the image field in the first/nginx container
1271 // Note that for SMP/WithSchema merge, the name:nginx entry
1272 // is mandatory
1273 func changeImagePatch(kind string, newImage string) string {
1274 return fmt.Sprintf(`
1275 apiVersion: apps/v1
1276 kind: %s
1277 metadata:
1278 name: deploy1
1279 spec:
1280 template:
1281 spec:
1282 containers:
1283 - name: nginx
1284 image: %s`, kind, newImage)
1285 }
1286
1287 // utility method to build the expected result of a multipatch
1288 // the order of the patches still have influence especially
1289 // in the insertion location within arrays.
1290 func expectedResultMultiPatch(kind string, reversed bool) string {
1291 pattern := `apiVersion: apps/v1
1292 kind: %s
1293 metadata:
1294 name: deploy1
1295 spec:
1296 template:
1297 metadata:
1298 labels:
1299 old-label: old-value
1300 some-label: some-value
1301 spec:
1302 containers:
1303 - env:
1304 %s
1305 image: nginx:latest
1306 name: nginx
1307 - image: anotherimage
1308 name: anothercontainer
1309 `
1310 if reversed {
1311 return fmt.Sprintf(pattern, kind, `- name: SOMEENV
1312 value: SOMEVALUE
1313 - name: ANOTHERENV
1314 value: ANOTHERVALUE`)
1315 }
1316 return fmt.Sprintf(pattern, kind, `- name: ANOTHERENV
1317 value: ANOTHERVALUE
1318 - name: SOMEENV
1319 value: SOMEVALUE`)
1320 }
1321
1322 // utility method building the expected output of a JMP.
1323 // imagename parameter allows to build a result consistent
1324 // with the JMP behavior which basically overrides the
1325 // entire "containers" list.
1326 func expectedResultJMP(imagename string) string {
1327 if imagename == "" {
1328 return `apiVersion: apps/v1
1329 kind: myCRD
1330 metadata:
1331 name: deploy1
1332 spec:
1333 template:
1334 metadata:
1335 labels:
1336 old-label: old-value
1337 some-label: some-value
1338 spec:
1339 containers:
1340 - env:
1341 - name: SOMEENV
1342 value: SOMEVALUE
1343 name: nginx
1344 `
1345 }
1346 return fmt.Sprintf(`apiVersion: apps/v1
1347 kind: myCRD
1348 metadata:
1349 name: deploy1
1350 spec:
1351 template:
1352 metadata:
1353 labels:
1354 old-label: old-value
1355 some-label: some-value
1356 spec:
1357 containers:
1358 - image: %s
1359 name: nginx
1360 `, imagename)
1361 }
1362
1363 func TestSameEndingSubarray(t *testing.T) {
1364 testCases := map[string]struct {
1365 a []string
1366 b []string
1367 expected bool
1368 }{
1369 "both nil": {
1370 expected: true,
1371 },
1372 "one nil": {
1373 b: []string{},
1374 expected: true,
1375 },
1376 "both empty": {
1377 a: []string{},
1378 b: []string{},
1379 expected: true,
1380 },
1381 "no1": {
1382 a: []string{"a"},
1383 b: []string{},
1384 expected: false,
1385 },
1386 "no2": {
1387 a: []string{"b", "a"},
1388 b: []string{"b"},
1389 expected: false,
1390 },
1391 "yes1": {
1392 a: []string{"a", "b"},
1393 b: []string{"b"},
1394 expected: true,
1395 },
1396 "yes2": {
1397 a: []string{"a", "b", "c"},
1398 b: []string{"b", "c"},
1399 expected: true,
1400 },
1401 "yes3": {
1402 a: []string{"a", "b", "c", "d", "e", "f"},
1403 b: []string{"f"},
1404 expected: true,
1405 },
1406 }
1407 for n := range testCases {
1408 tc := testCases[n]
1409 t.Run(n, func(t *testing.T) {
1410 assert.Equal(t, tc.expected, utils.SameEndingSubSlice(tc.a, tc.b))
1411 })
1412 }
1413 }
1414
1415 func TestGetGvk(t *testing.T) {
1416 r, err := factory.FromBytes([]byte(`
1417 apiVersion: apps/v1
1418 kind: Deployment
1419 metadata:
1420 name: clown
1421 spec:
1422 numReplicas: 1
1423 `))
1424 require.NoError(t, err)
1425
1426 gvk := r.GetGvk()
1427 expected := "apps"
1428 actual := gvk.Group
1429 if expected != actual {
1430 t.Fatalf("expected '%s', got '%s'", expected, actual)
1431 }
1432 expected = "v1"
1433 actual = gvk.Version
1434 if expected != actual {
1435 t.Fatalf("expected '%s', got '%s'", expected, actual)
1436 }
1437 expected = "Deployment"
1438 actual = gvk.Kind
1439 if expected != actual {
1440 t.Fatalf("expected '%s', got '%s'", expected, actual)
1441 }
1442 }
1443 func TestSetGvk(t *testing.T) {
1444 r, err := factory.FromBytes([]byte(`
1445 apiVersion: v1
1446 kind: Deployment
1447 metadata:
1448 name: clown
1449 spec:
1450 numReplicas: 1
1451 `))
1452 require.NoError(t, err)
1453 r.SetGvk(resid.GvkFromString("knd.ver.grp"))
1454 gvk := r.GetGvk()
1455 if expected, actual := "grp", gvk.Group; expected != actual {
1456 t.Fatalf("expected '%s', got '%s'", expected, actual)
1457 }
1458 if expected, actual := "ver", gvk.Version; expected != actual {
1459 t.Fatalf("expected '%s', got '%s'", expected, actual)
1460 }
1461 if expected, actual := "knd", gvk.Kind; expected != actual {
1462 t.Fatalf("expected '%s', got '%s'", expected, actual)
1463 }
1464 }
1465
1466 func TestRefBy(t *testing.T) {
1467 r, err := factory.FromBytes([]byte(`
1468 apiVersion: v1
1469 kind: Deployment
1470 metadata:
1471 name: clown
1472 spec:
1473 numReplicas: 1
1474 `))
1475 require.NoError(t, err)
1476 r.AppendRefBy(resid.FromString("knd1.ver1.gr1/name1.ns1"))
1477 assert.Equal(t, `apiVersion: v1
1478 kind: Deployment
1479 metadata:
1480 name: clown
1481 annotations:
1482 internal.config.kubernetes.io/refBy: 'knd1.ver1.gr1/name1.ns1'
1483 spec:
1484 numReplicas: 1
1485 `, r.RNode.MustString())
1486 assert.Equal(t, r.GetRefBy(), []resid.ResId{resid.FromString("knd1.ver1.gr1/name1.ns1")})
1487
1488 r.AppendRefBy(resid.FromString("knd2.ver2.gr2/name2.ns2"))
1489 assert.Equal(t, `apiVersion: v1
1490 kind: Deployment
1491 metadata:
1492 name: clown
1493 annotations:
1494 internal.config.kubernetes.io/refBy: 'knd1.ver1.gr1/name1.ns1,knd2.ver2.gr2/name2.ns2'
1495 spec:
1496 numReplicas: 1
1497 `, r.RNode.MustString())
1498 assert.Equal(t, []resid.ResId{
1499 resid.FromString("knd1.ver1.gr1/name1.ns1"),
1500 resid.FromString("knd2.ver2.gr2/name2.ns2"),
1501 }, r.GetRefBy())
1502 }
1503
1504 func TestOrigin(t *testing.T) {
1505 r, err := factory.FromBytes([]byte(`
1506 apiVersion: v1
1507 kind: Deployment
1508 metadata:
1509 name: clown
1510 spec:
1511 numReplicas: 1
1512 `))
1513 require.NoError(t, err)
1514 origin := &Origin{
1515 Path: "deployment.yaml",
1516 Repo: "github.com/myrepo",
1517 Ref: "master",
1518 }
1519 require.NoError(t, r.SetOrigin(origin))
1520 assert.Equal(t, `apiVersion: v1
1521 kind: Deployment
1522 metadata:
1523 name: clown
1524 annotations:
1525 config.kubernetes.io/origin: |
1526 path: deployment.yaml
1527 repo: github.com/myrepo
1528 ref: master
1529 spec:
1530 numReplicas: 1
1531 `, r.MustString())
1532 or, err := r.GetOrigin()
1533 require.NoError(t, err)
1534 assert.Equal(t, origin, or)
1535 }
1536
1537 func TestTransformations(t *testing.T) {
1538 r, err := factory.FromBytes([]byte(`
1539 apiVersion: v1
1540 kind: Deployment
1541 metadata:
1542 name: clown
1543 spec:
1544 numReplicas: 1
1545 `))
1546 require.NoError(t, err)
1547 origin1 := &Origin{
1548 Repo: "github.com/myrepo",
1549 Ref: "master",
1550 ConfiguredIn: "config.yaml",
1551 ConfiguredBy: kyaml.ResourceIdentifier{
1552 TypeMeta: kyaml.TypeMeta{
1553 APIVersion: "builtin",
1554 Kind: "Generator",
1555 },
1556 NameMeta: kyaml.NameMeta{
1557 Name: "my-name",
1558 Namespace: "my-namespace",
1559 },
1560 },
1561 }
1562 origin2 := &Origin{
1563 ConfiguredIn: "../base/config.yaml",
1564 ConfiguredBy: kyaml.ResourceIdentifier{
1565 TypeMeta: kyaml.TypeMeta{
1566 APIVersion: "builtin",
1567 Kind: "Generator",
1568 },
1569 NameMeta: kyaml.NameMeta{
1570 Name: "my-name",
1571 Namespace: "my-namespace",
1572 },
1573 },
1574 }
1575 require.NoError(t, r.AddTransformation(origin1))
1576 assert.Equal(t, `apiVersion: v1
1577 kind: Deployment
1578 metadata:
1579 name: clown
1580 annotations:
1581 alpha.config.kubernetes.io/transformations: |
1582 - repo: github.com/myrepo
1583 ref: master
1584 configuredIn: config.yaml
1585 configuredBy:
1586 apiVersion: builtin
1587 kind: Generator
1588 name: my-name
1589 namespace: my-namespace
1590 spec:
1591 numReplicas: 1
1592 `, r.MustString())
1593 require.NoError(t, r.AddTransformation(origin2))
1594 assert.Equal(t, `apiVersion: v1
1595 kind: Deployment
1596 metadata:
1597 name: clown
1598 annotations:
1599 alpha.config.kubernetes.io/transformations: |
1600 - repo: github.com/myrepo
1601 ref: master
1602 configuredIn: config.yaml
1603 configuredBy:
1604 apiVersion: builtin
1605 kind: Generator
1606 name: my-name
1607 namespace: my-namespace
1608 - configuredIn: ../base/config.yaml
1609 configuredBy:
1610 apiVersion: builtin
1611 kind: Generator
1612 name: my-name
1613 namespace: my-namespace
1614 spec:
1615 numReplicas: 1
1616 `, r.MustString())
1617 transformations, err := r.GetTransformations()
1618 require.NoError(t, err)
1619 assert.Equal(t, Transformations{origin1, origin2}, transformations)
1620 require.NoError(t, r.ClearTransformations())
1621 assert.Equal(t, `apiVersion: v1
1622 kind: Deployment
1623 metadata:
1624 name: clown
1625 spec:
1626 numReplicas: 1
1627 `, r.MustString())
1628 }