How to test controller's reconciliation function that requeues? #3290
-
Hi all, Suppose you have a reconcile function that creates a k8s resource for each CR, e.g a Pod or Deployment. I see that it is suggested to requeue after you made such resource. This will mean that reconcile function will return before it reached the other steps (such as updating statuses). In a regular cluster where controller is installed, the reconcile func will be called again, but how to do that in the controller_test.go? And maybe a bigger question - why do the examples show two different techniques
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi @hellt ,
If I understand your question when testing reconciliation functions that requeue, you can simulate the requeue behavior by repeatedly invoking the reconciliation function until it no longer returns a requeue result. This simulates what would happen in a real cluster. With Ginkgo and ENVTEST, I think you could do something like:
It would not be recommend use fake client but you might able to do the same doing something like ```go
import (
"context"
"testing"
"github.com/go-logr/logr/testing"
"github.com/stretchr/testify/require"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
func TestReconcileWithFakeClient(t *testing.T) {
// Create a fake client to mock API calls
cl := fake.NewFakeClient()
// Create an instance of your reconciler
r := &YourReconciler{
Client: cl,
Log: testing.NullLogger{},
}
req := reconcile.Request{
NamespacedName: types.NamespacedName{Name: "yourCRName", Namespace: "default"},
}
maxRequeues := 5
for i := 0; i < maxRequeues; i++ {
res, err := r.Reconcile(context.TODO(), req)
// Break if there's no requeue
if err != nil {
require.FailNow(t, "Failed to reconcile", err)
}
if !res.Requeue {
break
}
}
} For new users, looking at the scaffolded tests by Kubebuilder's
Hope this helps! I am closing this one as sorted out |
Beta Was this translation helpful? Give feedback.
Hi @hellt ,
If I understand your question when testing reconciliation functions that requeue, you can simulate the requeue behavior by repeatedly invoking the reconciliation function until it no longer returns a requeue result. This simulates what would happen in a real cluster.
With Ginkgo and ENVTEST, I think you could do something like: