Skip to content

Commit

Permalink
Add the unit test template for webhook and controllers.
Browse files Browse the repository at this point in the history
Signed-off-by: dashanji <[email protected]>
  • Loading branch information
dashanji committed Oct 8, 2023
1 parent 2725874 commit f04e5a8
Show file tree
Hide file tree
Showing 58 changed files with 4,206 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
Copyright 2023 The Kubernetes authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package v1

import (
. "github.com/onsi/ginkgo/v2"
)

var _ = Describe("CronJob Webhook", func() {

Context("When creating CronJob under Defaulting Webhook", func() {
It("Should fill in the default value if a required field is empty", func() {
/*
// Assuming CronJob has a field "Memory" that shouldn't be lower than 100Mi,
// and the logic of the defaulting webhook is to set Memory to 100Mi if it's lower than 100Mi.
cronjob := &CronJob{
Spec: CronJobSpec{
Memory: "10Mi",
// other fields...
},
}
err := k8sClient.Create(context.Background(), cronjob)
Expect(err).NotTo(HaveOccurred())
Expect(cronjob.Spec.Memory).To(Equal("100Mi")) // Expect the default value to be set.
// Add more assertions if needed.
*/
})
// TODO(user): Add the test cases for defaulting webhook.
})

Context("When creating CronJob under Validating Webhook", func() {
It("Should deny if a required field is empty", func() {
/*
// Assuming CronJob has a field "Name" that shouldn't be empty.
cronjob := &CronJob{
ObjectMeta: metav1.ObjectMeta{
Name: "test-CronJob",
Namespace: "default",
},
Spec: CronJobSpec{
// fill in the required fields
},
}
Expect(k8sClient.Create(ctx, cronjob)).To(Succeed())
err := k8sClient.Create(context.Background(), cronjob)
Expect(err).To(HaveOccurred()) // Expect an error because the Name field is empty.
// Optionally, you can check for specific error messages or types.
*/

})

It("Should admit if all required fields are provided", func() {
/*
cronjob := &CronJob{
Spec: CronJobSpec{
Name: "ValidName",
// other fields...
},
}
err := k8sClient.Create(context.Background(), cronjob)
Expect(err).NotTo(HaveOccurred()) // Expect no error as it's a valid resource.
*/
})
// TODO(user): Add the test cases for validating webhook.
})

})
1 change: 1 addition & 0 deletions pkg/plugins/common/kustomize/v2/scaffolds/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package scaffolds

import (
"fmt"

pluginutil "sigs.k8s.io/kubebuilder/v3/pkg/plugin/util"

log "github.com/sirupsen/logrus"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ func (f *ControllerTest) SetTemplateDefaults() error {
f.PackageName = "controllers"
}

f.IfExistsAction = machinery.OverwriteFile

log.Println("creating import for %", f.Resource.Path)
f.TemplateBody = controllerTestTemplate

Expand Down
1 change: 1 addition & 0 deletions pkg/plugins/golang/v3/scaffolds/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ func (s *apiScaffolder) Scaffold() error {
if err := scaffold.Execute(
&controllers.SuiteTest{Force: s.force},
&controllers.Controller{ControllerRuntimeVersion: ControllerRuntimeVersion, Force: s.force},
&controllers.ControllerTest{Force: s.force, DoAPI: doAPI},
); err != nil {
return fmt.Errorf("error scaffolding controller: %v", err)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package api

import (
"fmt"
"path/filepath"
"strings"

log "github.com/sirupsen/logrus"

"sigs.k8s.io/kubebuilder/v3/pkg/machinery"
)

var _ machinery.Template = &WebhookTest{}

// WebhookTest scaffolds the file that sets up the webhook unit tests
type WebhookTest struct { // nolint:maligned
machinery.TemplateMixin
machinery.MultiGroupMixin
machinery.BoilerplateMixin
machinery.ResourceMixin

Force bool
}

// SetTemplateDefaults implements file.Template
func (f *WebhookTest) SetTemplateDefaults() error {
if f.Path == "" {
if f.MultiGroup {
if f.Resource.Group != "" {
f.Path = filepath.Join("apis", "%[group]", "%[version]", "%[kind]_webhook_test.go")
} else {
f.Path = filepath.Join("apis", "%[version]", "%[kind]_webhook_test.go")
}
} else {
f.Path = filepath.Join("api", "%[version]", "%[kind]_webhook_test.go")
}
}
f.Path = f.Resource.Replacer().Replace(f.Path)
log.Println(f.Path)

webhookTestTemplate := webhookTestTemplate
templates := make([]string, 0)
if f.Resource.HasDefaultingWebhook() {
templates = append(templates, defaultWebhookTestTemplate)
}
if f.Resource.HasValidationWebhook() {
templates = append(templates, validateWebhookTestTemplate)
}
if f.Resource.HasConversionWebhook() {
templates = append(templates, conversionWebhookTestTemplate)
}
f.TemplateBody = fmt.Sprintf(webhookTestTemplate, strings.Join(templates, "\n"))

if f.Force {
f.IfExistsAction = machinery.OverwriteFile
}

return nil
}

const webhookTestTemplate = `{{ .Boilerplate }}
package {{ .Resource.Version }}
import (
. "github.com/onsi/ginkgo/v2"
)
var _ = Describe("{{ .Resource.Kind }} Webhook", func() {
%s
})
`

const conversionWebhookTestTemplate = `
Context("When creating {{ .Resource.Kind }} under Conversion Webhook", func() {
It("Should get the converted version of {{ .Resource.Kind }}" , func() {
/*
// Assuming {{ .Resource.Kind }} has a previous version named "v1alpha1" and current version named "v1".
typeResourceName := types.NamespacedName{
Name: "test-{{ .Resource.Kind }}",
Namespace: "default",
}
{{ lower .Resource.Kind }} := &{{ .Resource.Kind }}V1alpha1.{{ .Resource.Kind }}{
ObjectMeta: metav1.ObjectMeta{
Name: "test-{{ .Resource.Kind }}",
Namespace: "default",
},
Spec: {{ .Resource.Kind }}Spec{
// fill in the required fields
},
}
Expect(k8sClient.Create(ctx, {{ lower .Resource.Kind }})).To(Succeed())
// check if the converted version of {{ .Resource.Kind }} can be retrieved.
converted{{ .Resource.Kind }} := &{{ .Resource.Kind }}V1.{{ .Resource.Kind }}{}
err := k8sClient.Get(context.Background(), typeResourceName, converted{{ .Resource.Kind }})
{{ lower .Resource.Kind }}V1 := &{{ .Resource.Kind }}V1.{{ .Resource.Kind }}{}
err := k8sClient.Create(context.Background(), client.ObjectKey{
Name: "test-{{ .Resource.Kind }}",
Namespace: "default",
}, &converted{{ .Resource.Kind }})
Expect(err).NotTo(HaveOccurred())
// Optionally, you can check for the converted object's fields.
*/
})
// TODO(user): Add the test cases for conversion webhook.
})
`

const validateWebhookTestTemplate = `
Context("When creating {{ .Resource.Kind }} under Validating Webhook", func() {
It("Should deny if a required field is empty", func() {
/*
// Assuming {{ .Resource.Kind }} has a field "Name" that shouldn't be empty.
{{ lower .Resource.Kind }} := &{{ .Resource.Kind }}{
ObjectMeta: metav1.ObjectMeta{
Name: "test-{{ .Resource.Kind }}",
Namespace: "default",
},
Spec: {{ .Resource.Kind }}Spec{
// fill in the required fields
},
}
Expect(k8sClient.Create(ctx, {{ lower .Resource.Kind }})).To(Succeed())
err := k8sClient.Create(context.Background(), {{ lower .Resource.Kind }})
Expect(err).To(HaveOccurred()) // Expect an error because the Name field is empty.
// Optionally, you can check for specific error messages or types.
*/
})
It("Should admit if all required fields are provided", func() {
/*
{{ lower .Resource.Kind }} := &{{ .Resource.Kind }}{
Spec: {{ .Resource.Kind }}Spec{
Name: "ValidName",
// other fields...
},
}
err := k8sClient.Create(context.Background(), {{ lower .Resource.Kind }})
Expect(err).NotTo(HaveOccurred()) // Expect no error as it's a valid resource.
*/
})
// TODO(user): Add the test cases for validating webhook.
})
`

const defaultWebhookTestTemplate = `
Context("When creating {{ .Resource.Kind }} under Defaulting Webhook", func() {
It("Should fill in the default value if a required field is empty", func() {
/*
// Assuming {{ .Resource.Kind }} has a field "Memory" that shouldn't be lower than 100Mi,
// and the logic of the defaulting webhook is to set Memory to 100Mi if it's lower than 100Mi.
{{ lower .Resource.Kind }} := &{{ .Resource.Kind }}{
Spec: {{ .Resource.Kind }}Spec{
Memory: "10Mi",
// other fields...
},
}
err := k8sClient.Create(context.Background(), {{ lower .Resource.Kind }})
Expect(err).NotTo(HaveOccurred())
Expect({{ lower .Resource.Kind }}.Spec.Memory).To(Equal("100Mi")) // Expect the default value to be set.
// Add more assertions if needed.
*/
})
// TODO(user): Add the test cases for defaulting webhook.
})
`
Loading

0 comments on commit f04e5a8

Please sign in to comment.