knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/apis/duck/v1/cronjob_defaults_test.go (about) 1 /* 2 Copyright 2021 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 v1 18 19 import ( 20 "context" 21 "strings" 22 "testing" 23 24 "github.com/google/go-cmp/cmp" 25 batchv1 "k8s.io/api/batch/v1" 26 corev1 "k8s.io/api/core/v1" 27 ) 28 29 func TestCronJobDefaulting(t *testing.T) { 30 c := CronJob{ 31 Spec: batchv1.CronJobSpec{ 32 JobTemplate: batchv1.JobTemplateSpec{ 33 Spec: batchv1.JobSpec{ 34 Template: corev1.PodTemplateSpec{ 35 Spec: corev1.PodSpec{ 36 Containers: []corev1.Container{{ 37 Name: "blah", 38 Image: "busybox", 39 }}, 40 }, 41 }, 42 }, 43 }, 44 }, 45 } 46 47 tests := []struct { 48 name string 49 with func(context.Context) context.Context 50 want *CronJob 51 }{{ 52 name: "no check", 53 with: func(ctx context.Context) context.Context { 54 return ctx 55 }, 56 want: c.DeepCopy(), 57 }, { 58 name: "no change", 59 with: func(ctx context.Context) context.Context { 60 return WithCronJobDefaulter(ctx, func(ctx context.Context, c *CronJob) { 61 }) 62 }, 63 want: c.DeepCopy(), 64 }, { 65 name: "no busybox", 66 with: func(ctx context.Context) context.Context { 67 return WithCronJobDefaulter(ctx, func(ctx context.Context, c *CronJob) { 68 for i, con := range c.Spec.JobTemplate.Spec.Template.Spec.InitContainers { 69 if !strings.Contains(con.Image, "@") { 70 c.Spec.JobTemplate.Spec.Template.Spec.InitContainers[i].Image = con.Image + "@sha256:deadbeef" 71 } 72 } 73 for i, con := range c.Spec.JobTemplate.Spec.Template.Spec.Containers { 74 if !strings.Contains(con.Image, "@") { 75 c.Spec.JobTemplate.Spec.Template.Spec.Containers[i].Image = con.Image + "@sha256:deadbeef" 76 } 77 } 78 }) 79 }, 80 want: &CronJob{ 81 Spec: batchv1.CronJobSpec{ 82 JobTemplate: batchv1.JobTemplateSpec{ 83 Spec: batchv1.JobSpec{ 84 Template: corev1.PodTemplateSpec{ 85 Spec: corev1.PodSpec{ 86 Containers: []corev1.Container{{ 87 Name: "blah", 88 Image: "busybox@sha256:deadbeef", 89 }}, 90 }, 91 }, 92 }, 93 }, 94 }, 95 }, 96 }} 97 98 for _, test := range tests { 99 t.Run(test.name, func(t *testing.T) { 100 ctx := test.with(context.Background()) 101 got := c.DeepCopy() 102 got.SetDefaults(ctx) 103 if !cmp.Equal(test.want, got) { 104 t.Errorf("SetDefaults (-want, +got) = %s", cmp.Diff(test.want, got)) 105 } 106 }) 107 } 108 }