Skip to content

Commit e5b6435

Browse files
authored
Merge pull request #2066 from leovct/use-client-new-in-tests
📖 Use client.New instead of manager client in tests
2 parents e806ba0 + bdfa597 commit e5b6435

File tree

1 file changed

+11
-8
lines changed
  • docs/book/src/cronjob-tutorial/testdata/project/controllers

1 file changed

+11
-8
lines changed

docs/book/src/cronjob-tutorial/testdata/project/controllers/suite_test.go

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,10 @@ package controllers
2525

2626
import (
2727
"path/filepath"
28-
ctrl "sigs.k8s.io/controller-runtime"
2928
"testing"
3029

30+
ctrl "sigs.k8s.io/controller-runtime"
31+
3132
. "github.com/onsi/ginkgo"
3233
. "github.com/onsi/gomega"
3334
"k8s.io/client-go/kubernetes/scheme"
@@ -112,8 +113,14 @@ var _ = BeforeSuite(func() {
112113
The only difference is that the manager is started in a separate goroutine so it does not block the cleanup of envtest
113114
when you’re done running your tests.
114115
115-
Once you've added the code below, you can actually delete the k8sClient above, because you can get k8sClient from the manager
116-
(as shown below).
116+
It is not recommended to use the manager client in tests because it is not strongly consistent. Indeed, the manager
117+
client is designed to do the "right thing" for controllers by default which is to read from caches. The best solution
118+
is to instantiate a new client using client.New for tests (as k8sClient above). It will provide a client that reads
119+
directly from the API meaning that you can write tests expecting read-after-write consistency.
120+
121+
However, keep in mind that you should not do this in the controller's conciliation loop (read an object after you have
122+
written it). Kubernetes favors an approach where you first do some reads, process and then do some writes and return.
123+
This way, you let the queue take care of the next cycle of readings if they are necessary.
117124
*/
118125

119126
k8sManager, err := ctrl.NewManager(cfg, ctrl.Options{
@@ -122,7 +129,7 @@ var _ = BeforeSuite(func() {
122129
Expect(err).ToNot(HaveOccurred())
123130

124131
err = (&CronJobReconciler{
125-
Client: k8sManager.GetClient(),
132+
Client: k8sClient,
126133
Scheme: k8sManager.GetScheme(),
127134
Log: ctrl.Log.WithName("controllers").WithName("CronJob"),
128135
}).SetupWithManager(k8sManager)
@@ -132,10 +139,6 @@ var _ = BeforeSuite(func() {
132139
err = k8sManager.Start(ctrl.SetupSignalHandler())
133140
Expect(err).ToNot(HaveOccurred())
134141
}()
135-
136-
k8sClient = k8sManager.GetClient()
137-
Expect(k8sClient).ToNot(BeNil())
138-
139142
}, 60)
140143

141144
/*

0 commit comments

Comments
 (0)