sigs.k8s.io/cluster-api@v1.7.1/internal/webhooks/util/util.go (about) 1 /* 2 Copyright 2021 The Kubernetes 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 util includes the utility functions for testing webhooks. 18 package util 19 20 import ( 21 "context" 22 "testing" 23 24 "github.com/onsi/gomega" 25 "k8s.io/apimachinery/pkg/runtime" 26 "sigs.k8s.io/controller-runtime/pkg/webhook" 27 ) 28 29 // CustomDefaulterValidator interface is for objects that define both custom defaulting 30 // and custom validating webhooks. 31 type CustomDefaulterValidator interface { 32 webhook.CustomDefaulter 33 webhook.CustomValidator 34 } 35 36 // CustomDefaultValidateTest returns a new testing function to be used in tests to 37 // make sure custom defaulting webhooks also pass validation tests on create, 38 // update and delete. 39 func CustomDefaultValidateTest(ctx context.Context, obj runtime.Object, webhook CustomDefaulterValidator) func(*testing.T) { 40 return func(t *testing.T) { 41 t.Helper() 42 43 createCopy := obj.DeepCopyObject() 44 updateCopy := obj.DeepCopyObject() 45 deleteCopy := obj.DeepCopyObject() 46 defaultingUpdateCopy := updateCopy.DeepCopyObject() 47 48 t.Run("validate-on-create", func(t *testing.T) { 49 g := gomega.NewWithT(t) 50 g.Expect(webhook.Default(ctx, createCopy)).To(gomega.Succeed()) 51 _, err := webhook.ValidateCreate(ctx, createCopy) 52 g.Expect(err).ToNot(gomega.HaveOccurred()) 53 }) 54 t.Run("validate-on-update", func(t *testing.T) { 55 g := gomega.NewWithT(t) 56 g.Expect(webhook.Default(ctx, defaultingUpdateCopy)).To(gomega.Succeed()) 57 g.Expect(webhook.Default(ctx, updateCopy)).To(gomega.Succeed()) 58 _, err := webhook.ValidateUpdate(ctx, createCopy, defaultingUpdateCopy) 59 g.Expect(err).ToNot(gomega.HaveOccurred()) 60 }) 61 t.Run("validate-on-delete", func(t *testing.T) { 62 g := gomega.NewWithT(t) 63 g.Expect(webhook.Default(ctx, deleteCopy)).To(gomega.Succeed()) 64 _, err := webhook.ValidateDelete(ctx, deleteCopy) 65 g.Expect(err).ToNot(gomega.HaveOccurred()) 66 }) 67 } 68 }