1
2
3
4 package object
5
6 import (
7 "testing"
8
9 "github.com/stretchr/testify/assert"
10 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
11 "sigs.k8s.io/kustomize/kyaml/kio/kioutil"
12 )
13
14 func TestUnstructuredToInfo(t *testing.T) {
15 testCases := map[string]struct {
16 obj *unstructured.Unstructured
17 expectedSource string
18 expectedName string
19 expectedNamespace string
20 }{
21 "with path annotation": {
22 obj: &unstructured.Unstructured{
23 Object: map[string]interface{}{
24 "apiVersion": "apps/v1",
25 "kind": "Deployment",
26 "metadata": map[string]interface{}{
27 "name": "foo",
28 "annotations": map[string]interface{}{
29 kioutil.PathAnnotation: "deployment.yaml",
30 },
31 },
32 },
33 },
34 expectedSource: "deployment.yaml",
35 expectedName: "foo",
36 expectedNamespace: "",
37 },
38 "with both new and legacy annotations": {
39 obj: &unstructured.Unstructured{
40 Object: map[string]interface{}{
41 "apiVersion": "apps/v1",
42 "kind": "Deployment",
43 "metadata": map[string]interface{}{
44 "name": "foo",
45 "annotations": map[string]interface{}{
46 kioutil.PathAnnotation: "deployment.yaml",
47 kioutil.LegacyPathAnnotation: "deployment.yaml",
48 },
49 },
50 },
51 },
52 expectedSource: "deployment.yaml",
53 expectedName: "foo",
54 expectedNamespace: "",
55 },
56 "without path annotation": {
57 obj: &unstructured.Unstructured{
58 Object: map[string]interface{}{
59 "apiVersion": "apps/v1",
60 "kind": "Deployment",
61 "metadata": map[string]interface{}{
62 "name": "foo",
63 "namespace": "bar",
64 },
65 },
66 },
67 expectedSource: "unstructured",
68 expectedName: "foo",
69 expectedNamespace: "bar",
70 },
71 }
72
73 for tn, tc := range testCases {
74 t.Run(tn, func(t *testing.T) {
75 inf, err := UnstructuredToInfo(tc.obj)
76 if !assert.NoError(t, err) {
77 t.FailNow()
78 }
79 assert.Equal(t, tc.expectedSource, inf.Source)
80 assert.Equal(t, tc.expectedName, inf.Name)
81 assert.Equal(t, tc.expectedNamespace, inf.Namespace)
82
83 u := inf.Object.(*unstructured.Unstructured)
84 annos, found, err := unstructured.NestedStringMap(u.Object, "metadata", "annotations")
85 if !assert.NoError(t, err) {
86 t.FailNow()
87 }
88
89 if found {
90 for _, a := range []kioutil.AnnotationKey{kioutil.PathAnnotation, kioutil.LegacyPathAnnotation} {
91 _, hasAnnotation := annos[a]
92 assert.False(t, hasAnnotation, "did not expect %s", a)
93 }
94 }
95 })
96 }
97 }
98
View as plain text