@@ -25,9 +25,10 @@ package controllers
25
25
26
26
import (
27
27
"path/filepath"
28
- ctrl "sigs.k8s.io/controller-runtime"
29
28
"testing"
30
29
30
+ ctrl "sigs.k8s.io/controller-runtime"
31
+
31
32
. "github.com/onsi/ginkgo"
32
33
. "github.com/onsi/gomega"
33
34
"k8s.io/client-go/kubernetes/scheme"
@@ -112,8 +113,14 @@ var _ = BeforeSuite(func() {
112
113
The only difference is that the manager is started in a separate goroutine so it does not block the cleanup of envtest
113
114
when you’re done running your tests.
114
115
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.
117
124
*/
118
125
119
126
k8sManager , err := ctrl .NewManager (cfg , ctrl.Options {
@@ -122,7 +129,7 @@ var _ = BeforeSuite(func() {
122
129
Expect (err ).ToNot (HaveOccurred ())
123
130
124
131
err = (& CronJobReconciler {
125
- Client : k8sManager . GetClient () ,
132
+ Client : k8sClient ,
126
133
Scheme : k8sManager .GetScheme (),
127
134
Log : ctrl .Log .WithName ("controllers" ).WithName ("CronJob" ),
128
135
}).SetupWithManager (k8sManager )
@@ -132,10 +139,6 @@ var _ = BeforeSuite(func() {
132
139
err = k8sManager .Start (ctrl .SetupSignalHandler ())
133
140
Expect (err ).ToNot (HaveOccurred ())
134
141
}()
135
-
136
- k8sClient = k8sManager .GetClient ()
137
- Expect (k8sClient ).ToNot (BeNil ())
138
-
139
142
}, 60 )
140
143
141
144
/*
0 commit comments