Sub topic 17
Testing operators
This chapter assumes you can read Go, know the reconcile loop from the earlier chapters, and have a scaffolded kubebuilder project.
What to test
An operator is a function from cluster state to cluster changes. Tests therefore fall into three layers. Each layer trades speed for realism.
| Layer | Runs | Catches |
|---|---|---|
| Fake client | In memory, milliseconds | Reconcile logic, idempotency |
| envtest | Real `kube-apiserver` and etcd, no kubelet | CRD schema, defaults, validation, status subresource |
| End-to-end | Real cluster such as kind | Deployment, RBAC, webhooks, real Pods |
Unit testing reconcile
The controller-runtime fake client stores objects in memory. Call Reconcile twice to check that it is idempotent. The second call must change nothing.
package controller
import (
"context"
"testing"
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
examplev1 "example.com/webapp/api/v1"
)
func TestReconcileCreatesDeployment(t *testing.T) {
scheme := runtime.NewScheme()
_ = clientgoscheme.AddToScheme(scheme)
_ = examplev1.AddToScheme(scheme)
app := &examplev1.WebApp{
ObjectMeta: metav1.ObjectMeta{Name: "hello", Namespace: "default"},
Spec: examplev1.WebAppSpec{Image: "nginx:1.27", Replicas: 2},
}
c := fake.NewClientBuilder().
WithScheme(scheme).
WithObjects(app).
WithStatusSubresource(app).
Build()
r := &WebAppReconciler{Client: c, Scheme: scheme}
key := types.NamespacedName{Name: "hello", Namespace: "default"}
for i := 0; i < 2; i++ {
if _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: key}); err != nil {
t.Fatalf("reconcile %d: %v", i, err)
}
}
var d appsv1.Deployment
if err := c.Get(context.Background(), key, &d); err != nil {
t.Fatal(err)
}
if *d.Spec.Replicas != 2 {
t.Fatalf("replicas = %d, want 2", *d.Spec.Replicas)
}
}Integration tests with envtest
The fake client does not enforce your CRD. It accepts a WebApp with a missing image or negative replicas. envtest starts a real API server and loads the CRD YAML generated by make manifests. Use it to confirm that:
- Defaults are applied, so
replicasbecomes 1 when omitted. - Invalid objects are rejected, such as
replicas: -1. - Your controller reaches the expected state when it runs against the API server.
No kubelet runs in envtest, so Deployments never create Pods. Your test must set deploy.Status.ReadyReplicas itself, then check that the WebApp status follows. Poll with Gomega's Eventually, because reconciliation is asynchronous.
Kubebuilder scaffolds a suite_test.go that starts envtest. Run it with make test.
Common errors
- Asserting on the result of one reconcile. Reconcile can run at any time and in any order. Assert on the final state.
- Skipping the delete path. Test that deleting a WebApp returns no error, and that finalizer cleanup runs once.
- Missing binaries. envtest needs
kube-apiserverandetcd. Install them withsetup-envtestand setKUBEBUILDER_ASSETS. - Testing RBAC with admin credentials. envtest runs as admin, so missing permissions only show up in end-to-end tests.
Exercise
Your reconciler passes a fake-client test, but on a real cluster a WebApp with replicas: -1 is accepted by your test and rejected by the cluster. Which layer should have caught it, and why?
Show answer
An envtest integration test. The fake client does not load the CRD, so it never applies the schema's minimum: 0 rule. envtest runs a real API server with the CRD installed, so it rejects the object just as a cluster would.