|
| 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 | + "k8s.io/apimachinery/pkg/runtime" |
| 24 | +) |
| 25 | + |
| 26 | +// DefaultingValidator interface is for objects that define both defaulting |
| 27 | +// and validating webhooks. |
| 28 | +type DefaultingValidator interface { |
| 29 | + runtime.Object |
| 30 | + Default() |
| 31 | + ValidateCreate() error |
| 32 | + ValidateUpdate(old runtime.Object) error |
| 33 | + ValidateDelete() error |
| 34 | +} |
| 35 | + |
| 36 | +// DefaultValidateTest returns a new testing function to be used in tests to |
| 37 | +// make sure defaulting webhooks also pass validation tests on create, |
| 38 | +// update and delete. |
| 39 | +func DefaultValidateTest(object DefaultingValidator) func(*testing.T) { |
| 40 | + return func(t *testing.T) { |
| 41 | + createCopy := object.DeepCopyObject().(DefaultingValidator) |
| 42 | + updateCopy := object.DeepCopyObject().(DefaultingValidator) |
| 43 | + deleteCopy := object.DeepCopyObject().(DefaultingValidator) |
| 44 | + defaultingUpdateCopy := updateCopy.DeepCopyObject().(DefaultingValidator) |
| 45 | + |
| 46 | + t.Run("validate-on-create", func(t *testing.T) { |
| 47 | + g := gomega.NewWithT(t) |
| 48 | + createCopy.Default() |
| 49 | + g.Expect(createCopy.ValidateCreate()).To(gomega.Succeed()) |
| 50 | + }) |
| 51 | + t.Run("validate-on-update", func(t *testing.T) { |
| 52 | + g := gomega.NewWithT(t) |
| 53 | + defaultingUpdateCopy.Default() |
| 54 | + g.Expect(defaultingUpdateCopy.ValidateUpdate(updateCopy)).To(gomega.Succeed()) |
| 55 | + }) |
| 56 | + t.Run("validate-on-delete", func(t *testing.T) { |
| 57 | + g := gomega.NewWithT(t) |
| 58 | + deleteCopy.Default() |
| 59 | + g.Expect(deleteCopy.ValidateDelete()).To(gomega.Succeed()) |
| 60 | + }) |
| 61 | + } |
| 62 | +} |
0 commit comments