Skip to content

Commit

Permalink
Merge pull request #1767 from schrej/feature/komega
Browse files Browse the repository at this point in the history
✨ Add Kubernetes Gomega extension with to make testing controllers easier
  • Loading branch information
k8s-ci-robot committed Mar 4, 2022
2 parents eb292e5 + c19a6ed commit 9ee63fc
Show file tree
Hide file tree
Showing 8 changed files with 563 additions and 5 deletions.
4 changes: 2 additions & 2 deletions go.mod
Expand Up @@ -8,12 +8,12 @@ require (
github.com/go-logr/logr v1.2.0
github.com/go-logr/zapr v1.2.0
github.com/onsi/ginkgo v1.16.5
github.com/onsi/gomega v1.17.0
github.com/onsi/gomega v1.18.1
github.com/prometheus/client_golang v1.11.1
github.com/prometheus/client_model v0.2.0
go.uber.org/goleak v1.1.12
go.uber.org/zap v1.19.1
golang.org/x/sys v0.0.0-20211029165221-6e7872819dc8
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac
gomodules.xyz/jsonpatch/v2 v2.2.0
k8s.io/api v0.23.0
Expand Down
10 changes: 7 additions & 3 deletions go.sum
Expand Up @@ -233,6 +233,7 @@ github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLe
github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
Expand Down Expand Up @@ -353,11 +354,14 @@ github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9k
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/ginkgo/v2 v2.0.0 h1:CcuG/HvWNkkaqCUpJifQY8z7qEMBJya6aLPx6ftGyjQ=
github.com/onsi/ginkgo/v2 v2.0.0/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=
github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.17.0 h1:9Luw4uT5HTjHTN8+aNcSThgH1vdXnmdJ8xIfZ4wyTRE=
github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
Expand Down Expand Up @@ -676,8 +680,8 @@ golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211029165221-6e7872819dc8 h1:M69LAlWZCshgp0QSzyDcSsSIejIEeuaCVpmwcKwyLMk=
golang.org/x/sys v0.0.0-20211029165221-6e7872819dc8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b h1:9zKuko04nR4gjZ4+DNjHqRlAJqbJETHwiNKDqTfOjfE=
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
Expand Down
14 changes: 14 additions & 0 deletions pkg/envtest/komega/OWNERS
@@ -0,0 +1,14 @@
approvers:
- controller-runtime-admins
- controller-runtime-maintainers
- controller-runtime-approvers
- schrej
- JoelSpeed
- sbueringer
reviewers:
- controller-runtime-admins
- controller-runtime-reviewers
- controller-runtime-approvers
- schrej
- JoelSpeed
- sbueringer
92 changes: 92 additions & 0 deletions pkg/envtest/komega/default.go
@@ -0,0 +1,92 @@
package komega

import (
"context"

"sigs.k8s.io/controller-runtime/pkg/client"
)

// defaultK is the Komega used by the package global functions.
var defaultK = &komega{ctx: context.Background()}

// SetClient sets the client used by the package global functions.
func SetClient(c client.Client) {
defaultK.client = c
}

// SetContext sets the context used by the package global functions.
func SetContext(c context.Context) {
defaultK.ctx = c
}

func checkDefaultClient() {
if defaultK.client == nil {
panic("Default Komega's client is not set. Use SetClient to set it.")
}
}

// Get returns a function that fetches a resource and returns the occurring error.
// It can be used with gomega.Eventually() like this
// deployment := appsv1.Deployment{ ... }
// gomega.Eventually(komega.Get(&deployment)).To(gomega.Succeed())
// By calling the returned function directly it can also be used with gomega.Expect(komega.Get(...)()).To(...)
func Get(obj client.Object) func() error {
checkDefaultClient()
return defaultK.Get(obj)
}

// List returns a function that lists resources and returns the occurring error.
// It can be used with gomega.Eventually() like this
// deployments := v1.DeploymentList{ ... }
// gomega.Eventually(k.List(&deployments)).To(gomega.Succeed())
// By calling the returned function directly it can also be used as gomega.Expect(k.List(...)()).To(...)
func List(list client.ObjectList, opts ...client.ListOption) func() error {
checkDefaultClient()
return defaultK.List(list, opts...)
}

// Update returns a function that fetches a resource, applies the provided update function and then updates the resource.
// It can be used with gomega.Eventually() like this:
// deployment := appsv1.Deployment{ ... }
// gomega.Eventually(k.Update(&deployment, func (o client.Object) {
// deployment.Spec.Replicas = 3
// return &deployment
// })).To(gomega.Scucceed())
// By calling the returned function directly it can also be used as gomega.Expect(k.Update(...)()).To(...)
func Update(obj client.Object, f func(), opts ...client.UpdateOption) func() error {
checkDefaultClient()
return defaultK.Update(obj, f, opts...)
}

// UpdateStatus returns a function that fetches a resource, applies the provided update function and then updates the resource's status.
// It can be used with gomega.Eventually() like this:
// deployment := appsv1.Deployment{ ... }
// gomega.Eventually(k.Update(&deployment, func (o client.Object) {
// deployment.Status.AvailableReplicas = 1
// return &deployment
// })).To(gomega.Scucceed())
// By calling the returned function directly it can also be used as gomega.Expect(k.UpdateStatus(...)()).To(...)
func UpdateStatus(obj client.Object, f func(), opts ...client.UpdateOption) func() error {
checkDefaultClient()
return defaultK.UpdateStatus(obj, f, opts...)
}

// Object returns a function that fetches a resource and returns the object.
// It can be used with gomega.Eventually() like this:
// deployment := appsv1.Deployment{ ... }
// gomega.Eventually(k.Object(&deployment)).To(HaveField("Spec.Replicas", gomega.Equal(pointer.Int32(3))))
// By calling the returned function directly it can also be used as gomega.Expect(k.Object(...)()).To(...)
func Object(obj client.Object) func() (client.Object, error) {
checkDefaultClient()
return defaultK.Object(obj)
}

// ObjectList returns a function that fetches a resource and returns the object.
// It can be used with gomega.Eventually() like this:
// deployments := appsv1.DeploymentList{ ... }
// gomega.Eventually(k.ObjectList(&deployments)).To(HaveField("Items", HaveLen(1)))
// By calling the returned function directly it can also be used as gomega.Expect(k.ObjectList(...)()).To(...)
func ObjectList(list client.ObjectList, opts ...client.ListOption) func() (client.ObjectList, error) {
checkDefaultClient()
return defaultK.ObjectList(list, opts...)
}
116 changes: 116 additions & 0 deletions pkg/envtest/komega/default_test.go
@@ -0,0 +1,116 @@
package komega

import (
"testing"

. "github.com/onsi/gomega"
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/pointer"
)

func TestDefaultGet(t *testing.T) {
g := NewWithT(t)

fc := createFakeClient()
SetClient(fc)

fetched := appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Namespace: "default",
Name: "test",
},
}
g.Eventually(Get(&fetched)).Should(Succeed())

g.Expect(*fetched.Spec.Replicas).To(BeEquivalentTo(5))
}

func TestDefaultList(t *testing.T) {
g := NewWithT(t)

fc := createFakeClient()
SetClient(fc)

list := appsv1.DeploymentList{}
g.Eventually(List(&list)).Should(Succeed())

g.Expect(list.Items).To(HaveLen(1))
depl := exampleDeployment()
g.Expect(list.Items[0]).To(And(
HaveField("ObjectMeta.Name", Equal(depl.ObjectMeta.Name)),
HaveField("ObjectMeta.Namespace", Equal(depl.ObjectMeta.Namespace)),
))
}

func TestDefaultUpdate(t *testing.T) {
g := NewWithT(t)

fc := createFakeClient()
SetClient(fc)

updateDeployment := appsv1.Deployment{
ObjectMeta: exampleDeployment().ObjectMeta,
}
g.Eventually(Update(&updateDeployment, func() {
updateDeployment.Annotations = map[string]string{"updated": "true"}
})).Should(Succeed())

fetched := appsv1.Deployment{
ObjectMeta: exampleDeployment().ObjectMeta,
}
g.Expect(Object(&fetched)()).To(HaveField("ObjectMeta.Annotations", HaveKeyWithValue("updated", "true")))
}

func TestDefaultUpdateStatus(t *testing.T) {
g := NewWithT(t)

fc := createFakeClient()
SetClient(fc)

updateDeployment := appsv1.Deployment{
ObjectMeta: exampleDeployment().ObjectMeta,
}
g.Eventually(UpdateStatus(&updateDeployment, func() {
updateDeployment.Status.AvailableReplicas = 1
})).Should(Succeed())

fetched := appsv1.Deployment{
ObjectMeta: exampleDeployment().ObjectMeta,
}
g.Expect(Object(&fetched)()).To(HaveField("Status.AvailableReplicas", BeEquivalentTo(1)))
}

func TestDefaultObject(t *testing.T) {
g := NewWithT(t)

fc := createFakeClient()
SetClient(fc)

fetched := appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Namespace: "default",
Name: "test",
},
}
g.Eventually(Object(&fetched)).Should(And(
Not(BeNil()),
HaveField("Spec.Replicas", Equal(pointer.Int32(5))),
))
}

func TestDefaultObjectList(t *testing.T) {
g := NewWithT(t)

fc := createFakeClient()
SetClient(fc)

list := appsv1.DeploymentList{}
g.Eventually(ObjectList(&list)).Should(And(
Not(BeNil()),
HaveField("Items", And(
HaveLen(1),
ContainElement(HaveField("Spec.Replicas", Equal(pointer.Int32(5)))),
)),
))
}
78 changes: 78 additions & 0 deletions pkg/envtest/komega/interfaces.go
@@ -0,0 +1,78 @@
/*
Copyright 2021 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 komega

import (
"context"

"sigs.k8s.io/controller-runtime/pkg/client"
)

// Komega is a collection of utilites for writing tests involving a mocked
// Kubernetes API.
type Komega interface {
// Get returns a function that fetches a resource and returns the occurring error.
// It can be used with gomega.Eventually() like this
// deployment := appsv1.Deployment{ ... }
// gomega.Eventually(k.Get(&deployment)).To(gomega.Succeed())
// By calling the returned function directly it can also be used with gomega.Expect(k.Get(...)()).To(...)
Get(client.Object) func() error

// List returns a function that lists resources and returns the occurring error.
// It can be used with gomega.Eventually() like this
// deployments := v1.DeploymentList{ ... }
// gomega.Eventually(k.List(&deployments)).To(gomega.Succeed())
// By calling the returned function directly it can also be used as gomega.Expect(k.List(...)()).To(...)
List(client.ObjectList, ...client.ListOption) func() error

// Update returns a function that fetches a resource, applies the provided update function and then updates the resource.
// It can be used with gomega.Eventually() like this:
// deployment := appsv1.Deployment{ ... }
// gomega.Eventually(k.Update(&deployment, func (o client.Object) {
// deployment.Spec.Replicas = 3
// return &deployment
// })).To(gomega.Scucceed())
// By calling the returned function directly it can also be used as gomega.Expect(k.Update(...)()).To(...)
Update(client.Object, func(), ...client.UpdateOption) func() error

// UpdateStatus returns a function that fetches a resource, applies the provided update function and then updates the resource's status.
// It can be used with gomega.Eventually() like this:
// deployment := appsv1.Deployment{ ... }
// gomega.Eventually(k.Update(&deployment, func (o client.Object) {
// deployment.Status.AvailableReplicas = 1
// return &deployment
// })).To(gomega.Scucceed())
// By calling the returned function directly it can also be used as gomega.Expect(k.UpdateStatus(...)()).To(...)
UpdateStatus(client.Object, func(), ...client.UpdateOption) func() error

// Object returns a function that fetches a resource and returns the object.
// It can be used with gomega.Eventually() like this:
// deployment := appsv1.Deployment{ ... }
// gomega.Eventually(k.Object(&deployment)).To(HaveField("Spec.Replicas", gomega.Equal(pointer.Int32(3))))
// By calling the returned function directly it can also be used as gomega.Expect(k.Object(...)()).To(...)
Object(client.Object) func() (client.Object, error)

// ObjectList returns a function that fetches a resource and returns the object.
// It can be used with gomega.Eventually() like this:
// deployments := appsv1.DeploymentList{ ... }
// gomega.Eventually(k.ObjectList(&deployments)).To(HaveField("Items", HaveLen(1)))
// By calling the returned function directly it can also be used as gomega.Expect(k.ObjectList(...)()).To(...)
ObjectList(client.ObjectList, ...client.ListOption) func() (client.ObjectList, error)

// WithContext returns a copy that uses the given context.
WithContext(context.Context) Komega
}

0 comments on commit 9ee63fc

Please sign in to comment.