Skip to content

Commit 2dad561

Browse files
add integration tests for controller
1 parent 9a435ce commit 2dad561

File tree

21 files changed

+335
-13
lines changed

21 files changed

+335
-13
lines changed

pkg/plugins/golang/deploy-image/v1alpha1/scaffolds/api.go

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,12 @@ func (s *apiScaffolder) Scaffold() error {
111111
return fmt.Errorf("error updating config/samples: %v", err)
112112
}
113113

114+
if err := scaffold.Execute(
115+
&controllers.ControllerTest{},
116+
); err != nil {
117+
return fmt.Errorf("error creating controllers/**_controller_test.go: %v", err)
118+
}
119+
114120
return nil
115121
}
116122

@@ -140,9 +146,13 @@ func (s *apiScaffolder) scafffoldControllerWithImage(scaffold *machinery.Scaffol
140146
// users can change the values
141147
var res string
142148
for _, value := range strings.Split(s.command, ",") {
143-
res += fmt.Sprintf("\"%s\",", strings.TrimSpace(value))
149+
res += fmt.Sprintf(" \"%s\",", strings.TrimSpace(value))
144150
}
151+
// remove the latest ,
145152
res = res[:len(res)-1]
153+
// remove the first space to not fail in the go fmt ./...
154+
res = strings.TrimLeft(res, " ")
155+
146156
err := util.InsertCode(controllerPath, `SecurityContext: &corev1.SecurityContext{
147157
RunAsNonRoot: &[]bool{true}[0],
148158
AllowPrivilegeEscalation: &[]bool{false}[0],
@@ -208,8 +218,8 @@ func (s *apiScaffolder) scaffoldCreateAPIFromGolang() error {
208218
}
209219

210220
const containerTemplate = `Containers: []corev1.Container{{
211-
Image: "%s",
212-
Name: "%s",
221+
Image: "%s",
222+
Name: "%s",
213223
ImagePullPolicy: corev1.PullIfNotPresent,
214224
// Ensure restrictive context for the container
215225
// More info: https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted
@@ -225,10 +235,10 @@ const containerTemplate = `Containers: []corev1.Container{{
225235
}}`
226236

227237
const runAsUserTemplate = `
228-
RunAsUser: &[]int64{%s}[0],`
238+
RunAsUser: &[]int64{%s}[0],`
229239

230240
const commandTemplate = `
231-
Command: []string{%s},`
241+
Command: []string{%s},`
232242

233243
const portTemplate = `
234244
Ports: []corev1.ContainerPort{{
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
/*
2+
Copyright 2022 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 controllers
18+
19+
import (
20+
"fmt"
21+
"path/filepath"
22+
23+
"sigs.k8s.io/kubebuilder/v3/pkg/machinery"
24+
)
25+
26+
var _ machinery.Template = &ControllerTest{}
27+
28+
// ControllerTest scaffolds the file that defines tests for the controller for a CRD or a builtin resource
29+
// nolint:maligned
30+
type ControllerTest struct {
31+
machinery.TemplateMixin
32+
machinery.MultiGroupMixin
33+
machinery.BoilerplateMixin
34+
machinery.ResourceMixin
35+
36+
Image string
37+
}
38+
39+
// SetTemplateDefaults implements file.Template
40+
func (f *ControllerTest) SetTemplateDefaults() error {
41+
if f.Path == "" {
42+
if f.MultiGroup && f.Resource.Group != "" {
43+
f.Path = filepath.Join("controllers", "%[group]", "%[kind]_controller_test.go")
44+
} else {
45+
f.Path = filepath.Join("controllers", "%[kind]_controller_test.go")
46+
}
47+
}
48+
f.Path = f.Resource.Replacer().Replace(f.Path)
49+
50+
fmt.Println("creating import for %", f.Resource.Path)
51+
f.TemplateBody = controllerTestTemplate
52+
53+
return nil
54+
}
55+
56+
//nolint:lll
57+
const controllerTestTemplate = `{{ .Boilerplate }}
58+
59+
package {{ if and .MultiGroup .Resource.Group }}{{ .Resource.PackageName }}{{ else }}controllers{{ end }}
60+
61+
import (
62+
"fmt"
63+
"k8s.io/apimachinery/pkg/api/errors"
64+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
65+
"k8s.io/apimachinery/pkg/types"
66+
67+
"time"
68+
"context"
69+
70+
. "github.com/onsi/ginkgo"
71+
. "github.com/onsi/gomega"
72+
73+
{{ if not (isEmptyStr .Resource.Path) -}}
74+
{{ .Resource.ImportAlias }} "{{ .Resource.Path }}"
75+
{{- end }}
76+
)
77+
78+
var _ = Describe("{{ .Resource.Kind }} controller", func() {
79+
80+
// Define utility constants for object names and testing timeouts/durations and intervals.
81+
const (
82+
{{ .Resource.Kind }}Name = "test-{{ lower .Resource.Kind }}"
83+
{{ .Resource.Kind }}Namespace = "test-{{ lower .Resource.Kind }}"
84+
)
85+
86+
Context("{{ .Resource.Kind }} controller test", func() {
87+
It("should create successfully the custom resource for the {{ .Resource.Kind }}", func() {
88+
ctx := context.Background()
89+
90+
By("Creating the custom resource for the Kind {{ .Resource.Kind }}")
91+
{{ lower .Resource.Kind }} := &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{}
92+
err := k8sClient.Get(ctx, types.NamespacedName{Name: {{ .Resource.Kind }}Name, Namespace: {{ .Resource.Kind }}Namespace}, {{ lower .Resource.Kind }})
93+
if err != nil && errors.IsNotFound(err) {
94+
// Define a new custom resource
95+
{{ lower .Resource.Kind }} := &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{
96+
TypeMeta: metav1.TypeMeta{
97+
APIVersion: "{{ .Resource.Group }}.{{ .Resource.Domain }}/{{ .Resource.Version }}",
98+
Kind: "{{ .Resource.Kind }}",
99+
},
100+
ObjectMeta: metav1.ObjectMeta{
101+
Name: {{ .Resource.Kind }}Name,
102+
Namespace: {{ .Resource.Kind }}Namespace,
103+
},
104+
Spec: {{ .Resource.ImportAlias }}.{{ .Resource.Kind }}Spec{
105+
Size: 1,
106+
},
107+
}
108+
fmt.Fprintf(GinkgoWriter, fmt.Sprintf("Creating a new custom resource in the namespace: %s with the name %s\n", {{ lower .Resource.Kind }}.Namespace, {{ lower .Resource.Kind }}.Name))
109+
err = k8sClient.Create(ctx, {{ lower .Resource.Kind }})
110+
if err != nil {
111+
Expect(err).To(Not(HaveOccurred()))
112+
}
113+
}
114+
115+
By("Checking with {{ .Resource.Kind }} Kind exist")
116+
Eventually(func() error {
117+
found := &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{}
118+
err = k8sClient.Get(ctx, types.NamespacedName{Name: {{ .Resource.Kind }}Name, Namespace: {{ .Resource.Kind }}Namespace}, found)
119+
if err != nil {
120+
return err
121+
}
122+
return nil
123+
}, time.Minute, time.Second).Should(Succeed())
124+
})
125+
})
126+
127+
})
128+
`

pkg/plugins/golang/v3/scaffolds/internal/templates/controllers/controller_suitetest.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,10 @@ package controllers
130130
import (
131131
"path/filepath"
132132
"testing"
133+
133134
. "github.com/onsi/ginkgo"
134135
. "github.com/onsi/gomega"
136+
135137
"k8s.io/client-go/kubernetes/scheme"
136138
"k8s.io/client-go/rest"
137139
"sigs.k8s.io/controller-runtime/pkg/client"

test/e2e/deployimage/plugin_cluster_test.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,15 +189,16 @@ func Run(kbc *utils.TestContext, imageCR string) {
189189
ExpectWithOffset(1, err).NotTo(HaveOccurred())
190190

191191
By("building the controller image")
192-
err = kbc.Make("docker-build", "IMG="+kbc.ImageName)
192+
cmd := exec.Command("docker", "build", "-t", kbc.ImageName, ".")
193+
_, err = kbc.Run(cmd)
193194
ExpectWithOffset(1, err).NotTo(HaveOccurred())
194195

195196
By("loading the controller docker image into the kind cluster")
196197
err = kbc.LoadImageToKindCluster()
197198
ExpectWithOffset(1, err).NotTo(HaveOccurred())
198199

199200
By("deploying the controller-manager")
200-
cmd := exec.Command("make", "deploy", "IMG="+kbc.ImageName)
201+
cmd = exec.Command("make", "deploy", "IMG="+kbc.ImageName)
201202
outputMake, err := kbc.Run(cmd)
202203
ExpectWithOffset(1, err).NotTo(HaveOccurred())
203204

testdata/project-v3-addon/controllers/suite_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
. "github.com/onsi/ginkgo"
2424
. "github.com/onsi/gomega"
25+
2526
"k8s.io/client-go/kubernetes/scheme"
2627
"k8s.io/client-go/rest"
2728
"sigs.k8s.io/controller-runtime/pkg/client"

testdata/project-v3-config/controllers/suite_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
. "github.com/onsi/ginkgo"
2424
. "github.com/onsi/gomega"
25+
2526
"k8s.io/client-go/kubernetes/scheme"
2627
"k8s.io/client-go/rest"
2728
"sigs.k8s.io/controller-runtime/pkg/client"

testdata/project-v3-multigroup/controllers/apps/suite_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
. "github.com/onsi/ginkgo"
2424
. "github.com/onsi/gomega"
25+
2526
appsv1 "k8s.io/api/apps/v1"
2627
"k8s.io/client-go/kubernetes/scheme"
2728
"k8s.io/client-go/rest"

testdata/project-v3-multigroup/controllers/crew/suite_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
. "github.com/onsi/ginkgo"
2424
. "github.com/onsi/gomega"
25+
2526
"k8s.io/client-go/kubernetes/scheme"
2627
"k8s.io/client-go/rest"
2728
"sigs.k8s.io/controller-runtime/pkg/client"

testdata/project-v3-multigroup/controllers/fiz/suite_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
. "github.com/onsi/ginkgo"
2424
. "github.com/onsi/gomega"
25+
2526
"k8s.io/client-go/kubernetes/scheme"
2627
"k8s.io/client-go/rest"
2728
"sigs.k8s.io/controller-runtime/pkg/client"

testdata/project-v3-multigroup/controllers/foo.policy/suite_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
. "github.com/onsi/ginkgo"
2424
. "github.com/onsi/gomega"
25+
2526
"k8s.io/client-go/kubernetes/scheme"
2627
"k8s.io/client-go/rest"
2728
"sigs.k8s.io/controller-runtime/pkg/client"

0 commit comments

Comments
 (0)