knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/reconciler/testing/generate_name_reactor_test.go (about) 1 /* 2 Copyright 2019 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 testing 18 19 import ( 20 "testing" 21 22 "github.com/google/go-cmp/cmp" 23 appsv1 "k8s.io/api/apps/v1" 24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 "k8s.io/apimachinery/pkg/runtime" 26 "k8s.io/apimachinery/pkg/runtime/schema" 27 clientgotesting "k8s.io/client-go/testing" 28 ) 29 30 var deploymentsResource = schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"} 31 32 func TestGenerateNameReactor(t *testing.T) { 33 tests := []struct { 34 name string 35 deployment *appsv1.Deployment 36 expectedName string 37 }{{ 38 name: "resource with name", 39 expectedName: "basic", 40 deployment: &appsv1.Deployment{ 41 ObjectMeta: metav1.ObjectMeta{ 42 Name: "basic", 43 }, 44 }, 45 }, { 46 name: "resource with generatedName", 47 expectedName: "fancy-00001", 48 deployment: &appsv1.Deployment{ 49 ObjectMeta: metav1.ObjectMeta{ 50 GenerateName: "fancy-", 51 }, 52 }, 53 }, { 54 name: "resource with name and generatedName", 55 expectedName: "fancy-00002", 56 deployment: &appsv1.Deployment{ 57 ObjectMeta: metav1.ObjectMeta{ 58 Name: "fancy-00002", 59 GenerateName: "fancy-", 60 }, 61 }, 62 }, { 63 name: "broken resource with no names", 64 expectedName: "", 65 deployment: &appsv1.Deployment{}, 66 }} 67 68 for _, tc := range tests { 69 t.Run(tc.name, func(t *testing.T) { 70 lastHandlerInvoked := false 71 72 fake := &clientgotesting.Fake{} 73 var mutated *appsv1.Deployment 74 fake.AddReactor("*", "*", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) { 75 create, ok := action.(clientgotesting.CreateAction) 76 if !ok { 77 return false, nil, nil 78 } 79 deploy, ok := create.GetObject().(*appsv1.Deployment) 80 if !ok { 81 return false, nil, nil 82 } 83 lastHandlerInvoked = true 84 mutated = deploy 85 return false, nil, nil 86 }) 87 88 PrependGenerateNameReactor(fake) 89 90 action := clientgotesting.NewCreateAction(deploymentsResource, "namespace", tc.deployment) 91 92 fake.Invokes(action, &appsv1.Deployment{}) 93 94 if diff := cmp.Diff(tc.expectedName, mutated.GetName()); diff != "" { 95 t.Error(diff) 96 } 97 98 if !lastHandlerInvoked { 99 t.Error("GenerateNameReactor should not interfere with the fake's ReactionChain") 100 } 101 }) 102 } 103 }