...
1
16
17 package webhook
18
19 import (
20 "encoding/json"
21 "reflect"
22 "testing"
23
24 jsonpatch "github.com/evanphx/json-patch"
25 "k8s.io/api/admission/v1"
26 corev1 "k8s.io/api/core/v1"
27 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
28 "k8s.io/apimachinery/pkg/runtime"
29 )
30
31 func TestAddLabel(t *testing.T) {
32 testCases := []struct {
33 name string
34 initialLabels map[string]string
35 expectedLabels map[string]string
36 }{
37 {
38 name: "add first label",
39 initialLabels: nil,
40 expectedLabels: map[string]string{"added-label": "yes"},
41 },
42 {
43 name: "add second label",
44 initialLabels: map[string]string{"other-label": "yes"},
45 expectedLabels: map[string]string{"other-label": "yes", "added-label": "yes"},
46 },
47 {
48 name: "idempotent update label",
49 initialLabels: map[string]string{"added-label": "yes"},
50 expectedLabels: map[string]string{"added-label": "yes"},
51 },
52 }
53
54 for _, tc := range testCases {
55 t.Run(tc.name, func(t *testing.T) {
56 request := corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Labels: tc.initialLabels}}
57 raw, err := json.Marshal(request)
58 if err != nil {
59 t.Fatal(err)
60 }
61 review := v1.AdmissionReview{Request: &v1.AdmissionRequest{Object: runtime.RawExtension{Raw: raw}}}
62 response := addLabel(review)
63 if response.Patch != nil {
64 patchObj, err := jsonpatch.DecodePatch(response.Patch)
65 if err != nil {
66 t.Fatal(err)
67 }
68 raw, err = patchObj.Apply(raw)
69 if err != nil {
70 t.Fatal(err)
71 }
72 }
73
74 objType := reflect.TypeOf(request)
75 objTest := reflect.New(objType).Interface()
76 err = json.Unmarshal(raw, objTest)
77 if err != nil {
78 t.Fatal(err)
79 }
80 actual := objTest.(*corev1.ConfigMap)
81 if !reflect.DeepEqual(actual.Labels, tc.expectedLabels) {
82 t.Errorf("\nexpected %#v, got %#v, patch: %v", actual.Labels, tc.expectedLabels, string(response.Patch))
83 }
84 })
85 }
86 }
87
View as plain text