sigs.k8s.io/cluster-api@v1.7.1/util/defaulting/defaulting.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 defaulting
    18  
    19  import (
    20  	"testing"
    21  
    22  	. "github.com/onsi/gomega"
    23  	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    24  )
    25  
    26  // DefaultingValidator interface is for objects that define both defaulting
    27  // and validating webhooks.
    28  type DefaultingValidator interface { //nolint:revive
    29  	admission.Defaulter
    30  	admission.Validator
    31  }
    32  
    33  // DefaultValidateTest returns a new testing function to be used in tests to
    34  // make sure defaulting webhooks also pass validation tests on create,
    35  // update and delete.
    36  func DefaultValidateTest(object DefaultingValidator) func(*testing.T) {
    37  	return func(t *testing.T) {
    38  		t.Helper()
    39  
    40  		createCopy := object.DeepCopyObject().(DefaultingValidator)
    41  		updateCopy := object.DeepCopyObject().(DefaultingValidator)
    42  		deleteCopy := object.DeepCopyObject().(DefaultingValidator)
    43  		defaultingUpdateCopy := updateCopy.DeepCopyObject().(DefaultingValidator)
    44  
    45  		t.Run("validate-on-create", func(t *testing.T) {
    46  			g := NewWithT(t)
    47  			createCopy.Default()
    48  			warnings, err := createCopy.ValidateCreate()
    49  			g.Expect(err).ToNot(HaveOccurred())
    50  			g.Expect(warnings).To(BeEmpty())
    51  		})
    52  		t.Run("validate-on-update", func(t *testing.T) {
    53  			g := NewWithT(t)
    54  			defaultingUpdateCopy.Default()
    55  			updateCopy.Default()
    56  			warnings, err := defaultingUpdateCopy.ValidateUpdate(updateCopy)
    57  			g.Expect(err).ToNot(HaveOccurred())
    58  			g.Expect(warnings).To(BeEmpty())
    59  		})
    60  		t.Run("validate-on-delete", func(t *testing.T) {
    61  			g := NewWithT(t)
    62  			deleteCopy.Default()
    63  			warnings, err := deleteCopy.ValidateDelete()
    64  			g.Expect(err).ToNot(HaveOccurred())
    65  			g.Expect(warnings).To(BeEmpty())
    66  		})
    67  	}
    68  }