knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/kmeta/accessor_test.go (about) 1 /* 2 Copyright 2018 The Knative 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 kmeta 18 19 import ( 20 "testing" 21 22 "github.com/google/go-cmp/cmp" 23 corev1 "k8s.io/api/core/v1" 24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 "k8s.io/client-go/tools/cache" 26 27 . "knative.dev/pkg/testing" 28 ) 29 30 // Ensure our resource satisfies the interface. 31 var _ Accessor = (*Resource)(nil) 32 33 func TestAccessor(t *testing.T) { 34 goodResource := &Resource{} 35 36 tests := []struct { 37 name string 38 o interface{} 39 want Accessor 40 }{{ 41 name: "bad object returns error", 42 o: struct{}{}, 43 }, { 44 name: "deleted with bad final state", 45 o: cache.DeletedFinalStateUnknown{ 46 Obj: struct{}{}, 47 }, 48 }, { 49 name: "good object", 50 o: goodResource, 51 want: Accessor(goodResource), 52 }, { 53 name: "deleted with good final state", 54 o: cache.DeletedFinalStateUnknown{ 55 Obj: goodResource, 56 }, 57 want: Accessor(goodResource), 58 }} 59 60 for _, test := range tests { 61 t.Run(test.name, func(t *testing.T) { 62 if test.want == nil { 63 got, err := DeletionHandlingAccessor(test.o) 64 if err == nil { 65 t.Errorf("DeletionHandlingAccessor() = %v, wanted error", got) 66 } 67 } else { 68 got, err := DeletionHandlingAccessor(test.o) 69 if err != nil { 70 t.Error("DeletionHandlingAccessor() =", err) 71 } 72 if diff := cmp.Diff(got, test.want); diff != "" { 73 t.Error("DeletionHandlingAccessor =", diff) 74 } 75 } 76 }) 77 } 78 } 79 80 func TestObjectReference(t *testing.T) { 81 r := &Resource{ 82 TypeMeta: metav1.TypeMeta{ 83 Kind: "king", 84 APIVersion: "some.api.version/v1", 85 }, 86 ObjectMeta: metav1.ObjectMeta{ 87 Name: "name", 88 Namespace: "namespace", 89 }, 90 } 91 92 want := corev1.ObjectReference{ 93 APIVersion: "some.api.version/v1", 94 Kind: "king", 95 Name: "name", 96 Namespace: "namespace", 97 } 98 99 if diff := cmp.Diff(want, ObjectReference(r)); diff != "" { 100 t.Error("Unexpected ObjectReference (-want, +got)", diff) 101 } 102 }