Skip to content

Commit

Permalink
Merge pull request #679 from droot/feature/test-scaffolding-2.0
Browse files Browse the repository at this point in the history
Moved to ginkgo based tests in scaffolding 2.0
  • Loading branch information
k8s-ci-robot authored May 16, 2019
2 parents 76a9cdd + ed46300 commit a43f866
Show file tree
Hide file tree
Showing 21 changed files with 1,063 additions and 38 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ install: build
cp ./bin/kubebuilder $(shell go env GOPATH)/bin/kubebuilder

generate:
./generated_golden.sh
GO111MODULE=on ./generated_golden.sh

test:
go test -v ./cmd/... ./pkg/...
Expand Down
9 changes: 9 additions & 0 deletions pkg/scaffold/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ func (api *API) scaffoldV2() error {
Path: filepath.Join("api", r.Version, fmt.Sprintf("%s_types.go", strings.ToLower(r.Kind))),
},
Resource: r},
&resourcev2.VersionSuiteTest{Resource: r},
&resourcev2.TypesTest{Resource: r},
&resourcev2.Group{Resource: r},
&resourcev2.CRDSample{Resource: r},
&crdv2.EnableWebhookPatch{Resource: r},
Expand Down Expand Up @@ -187,8 +189,10 @@ func (api *API) scaffoldV2() error {
fmt.Println(filepath.Join("controllers", fmt.Sprintf("%s_controller.go", strings.ToLower(r.Kind))))

ctrlScaffolder := &resourcev2.Controller{Resource: r}
testsuiteScaffolder := &resourcev2.ControllerSuiteTest{Resource: r}
err := (&Scaffold{}).Execute(
input.Options{},
testsuiteScaffolder,
ctrlScaffolder,
)
if err != nil {
Expand All @@ -199,6 +203,11 @@ func (api *API) scaffoldV2() error {
if err != nil {
return fmt.Errorf("error updating main.go with reconciler code: %v", err)
}

err = testsuiteScaffolder.UpdateTestSuite()
if err != nil {
return fmt.Errorf("error updating suite_test.go under controllers pkg: %v", err)
}
}

return nil
Expand Down
155 changes: 155 additions & 0 deletions pkg/scaffold/v2/controller_suitetest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
Copyright 2019 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 v2

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

"github.com/markbates/inflect"
"sigs.k8s.io/kubebuilder/pkg/scaffold/input"
"sigs.k8s.io/kubebuilder/pkg/scaffold/v1/resource"
"sigs.k8s.io/kubebuilder/pkg/scaffold/v2/internal"
)

var _ input.File = &ControllerSuiteTest{}

// ControllerSuiteTest scaffolds the suite_test.go file to setup the controller test
type ControllerSuiteTest struct {
input.Input

// Resource is the resource to scaffold the controller_kind_test.go file for
Resource *resource.Resource

// ResourcePackage is the package of the Resource
ResourcePackage string

// Plural is the plural lowercase of kind
Plural string

// Is the Group + "." + Domain for the Resource
GroupDomain string
}

// GetInput implements input.File
func (v *ControllerSuiteTest) GetInput() (input.Input, error) {
if v.Path == "" {
v.Path = filepath.Join("controllers", "suite_test.go")
}
v.TemplateBody = controllerSuiteTestTemplate
return v.Input, nil
}

// Validate validates the values
func (v *ControllerSuiteTest) Validate() error {
return v.Resource.Validate()
}

var controllerSuiteTestTemplate = `{{ .Boilerplate }}
package controllers
import (
"path/filepath"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
// +kubebuilder:scaffold:imports
)
// These tests use Ginkgo (BDD-style Go testing framework). Refer to
// http://onsi.github.io/ginkgo/ to learn more about Ginkgo.
var cfg *rest.Config
var k8sClient client.Client
var testEnv *envtest.Environment
func TestAPIs(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecsWithDefaultAndCustomReporters(t,
"Controller Suite",
[]Reporter{envtest.NewlineReporter{}})
}
var _ = BeforeSuite(func(done Done) {
logf.SetLogger(zap.LoggerTo(GinkgoWriter, true))
By("bootstrapping test environment")
testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases")},
}
cfg, err := testEnv.Start()
Expect(err).ToNot(HaveOccurred())
Expect(cfg).ToNot(BeNil())
// +kubebuilder:scaffold:scheme
k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
Expect(err).ToNot(HaveOccurred())
Expect(k8sClient).ToNot(BeNil())
close(done)
}, 60)
var _ = AfterSuite(func() {
By("tearing down the test environment")
err := testEnv.Stop()
Expect(err).ToNot(HaveOccurred())
})
`

// UpdateTestSuite updates given file (suite_test.go) with code fragments required for
// adding import paths and code setup for new types.
func (a *ControllerSuiteTest) UpdateTestSuite() error {

a.ResourcePackage, a.GroupDomain = getResourceInfo(a.Resource, a.Input)
if a.Plural == "" {
rs := inflect.NewDefaultRuleset()
a.Plural = rs.Pluralize(strings.ToLower(a.Resource.Kind))
}

apiImportCodeFragment := fmt.Sprintf(`"%s/controllers"
%s%s "%s/%s"
`, a.Repo, a.Resource.Group, a.Resource.Version, a.ResourcePackage, a.Resource.Version)

addschemeCodeFragment := fmt.Sprintf(`err = %s%s.AddToScheme(scheme.Scheme)
Expect(err).NotTo(HaveOccurred())
`, a.Resource.Group, a.Resource.Version)

err := internal.InsertStringsInFile(a.Path,
apiPkgImportScaffoldMarker, apiImportCodeFragment,
apiSchemeScaffoldMarker, addschemeCodeFragment)
if err != nil {
return err
}

return nil
}
2 changes: 1 addition & 1 deletion pkg/scaffold/v2/gomod.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@ module {{ .Repo }}
go 1.12
require (
sigs.k8s.io/controller-runtime feature/modules
sigs.k8s.io/controller-runtime v0.2.0-alpha.1
)
`
2 changes: 1 addition & 1 deletion pkg/scaffold/v2/makefile.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ docker-push:
# download controller-gen if necessary
controller-gen:
ifeq (, $(shell which controller-gen))
go get sigs.k8s.io/controller-tools/cmd/controller-gen@v0.2.0-alpha.1
go get sigs.k8s.io/controller-tools/cmd/controller-gen@v0.2.0-alpha.2
CONTROLLER_GEN=$(shell go env GOPATH)/bin/controller-gen
else
CONTROLLER_GEN=$(shell which controller-gen)
Expand Down
123 changes: 123 additions & 0 deletions pkg/scaffold/v2/typestest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
Copyright 2019 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 v2

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

"sigs.k8s.io/kubebuilder/pkg/scaffold/input"
"sigs.k8s.io/kubebuilder/pkg/scaffold/v1/resource"
)

var _ input.File = &TypesTest{}

// TypesTest scaffolds the api/version/kind_types_test.go file to test the API schema
type TypesTest struct {
input.Input

// Resource is the resource to scaffold the types_test.go file for
Resource *resource.Resource
}

// GetInput implements input.File
func (t *TypesTest) GetInput() (input.Input, error) {
if t.Path == "" {
t.Path = filepath.Join("api", t.Resource.Version,
fmt.Sprintf("%s_types_test.go", strings.ToLower(t.Resource.Kind)))
}
t.TemplateBody = typesTestTemplate
t.IfExistsAction = input.Error
return t.Input, nil
}

// Validate validates the values
func (t *TypesTest) Validate() error {
return t.Resource.Validate()
}

var typesTestTemplate = `{{ .Boilerplate }}
package {{ .Resource.Version }}
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"golang.org/x/net/context"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
// These tests are written in BDD-style using Ginkgo framework. Refer to
// http://onsi.github.io/ginkgo to learn more.
var _ = Describe("{{ .Resource.Kind }}", func() {
var (
key types.NamespacedName
created, fetched *{{.Resource.Kind}}
)
BeforeEach(func(){
// Add any setup steps that needs to be executed before each test
})
AfterEach(func(){
// Add any teardown steps that needs to be executed after each test
})
// Add Tests for OpenAPI validation (or additonal CRD features) specified in
// your API definition.
// Avoid adding tests for vanilla CRUD operations because they would
// test Kubernetes API server, which isn't the goal here.
Context("Create API", func() {
It("should create an object successfully", func() {
key = types.NamespacedName{
Name: "foo",
{{ if .Resource.Namespaced -}}
Namespace: "default",
{{ end -}}
}
created = &{{ .Resource.Kind }}{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
{{ if .Resource.Namespaced -}}
Namespace: "default",
{{ end -}}
}}
By("creating an API obj")
Expect(k8sClient.Create(context.TODO(), created)).To(Succeed())
fetched = &{{ .Resource.Kind }}{}
Expect(k8sClient.Get(context.TODO(), key, fetched)).To(Succeed())
Expect(fetched).To(Equal(created))
By("deleting the created object")
Expect(k8sClient.Delete(context.TODO(), created)).To(Succeed())
Expect(k8sClient.Get(context.TODO(), key, created)).ToNot(Succeed())
})
})
})
`
Loading

0 comments on commit a43f866

Please sign in to comment.