@@ -25,8 +25,22 @@ time, and delayed merges.
25
25
26
26
#### Debuggability ####
27
27
28
- If your test fails, it should provide as detailed as possible reasons
29
- for the failure in its output. "Timeout" is not a useful error
28
+ If your test fails, it should provide as detailed as possible reasons for the
29
+ failure in its failure message. The failure message is the string that gets
30
+ passed (directly or indirectly) to ` ginkgo.Fail(f) ` . That text is what gets
31
+ shown in the overview of failed tests for a Prow job and what gets aggregated
32
+ by https://go.k8s.io/triage .
33
+
34
+ A good failure message:
35
+ - identifies the test failure
36
+ - has enough details to provide some initial understanding of what went wrong
37
+
38
+ It's okay for it to contain information that changes during each test
39
+ run. Aggregation [ simplifies the failure message with regular
40
+ expressions] ( https://github.com/kubernetes/test-infra/blob/d56bc333ae8acf176887a3249f750e7a8e0377f0/triage/summarize/text.go#L39-L69 )
41
+ before looking for similar failures.
42
+
43
+ "Timeout" is not a useful error
30
44
message. "Timed out after 60 seconds waiting for pod xxx to enter
31
45
running state, still in pending state" is much more useful to someone
32
46
trying to figure out why your test failed and what to do about it.
@@ -38,17 +52,288 @@ like the following generates rather useless errors:
38
52
Expect(err).NotTo(HaveOccurred())
39
53
```
40
54
41
- Rather
55
+ Errors returned by client-go can be very detailed. A better way to test for
56
+ errors is with ` framework.ExpectNoError ` because it logs the full error and
57
+ then includes only the shorter ` err.Error() ` in the failure message. To make
58
+ that failure message more informative,
42
59
[ annotate] ( https://onsi.github.io/gomega/#annotating-assertions ) your assertion with something like this:
43
60
44
61
```
45
- Expect(err).NotTo(HaveOccurred() , "Failed to create %d foobars, only created %d", foobarsReqd, foobarsCreated)
62
+ framework.ExpectNoError(err , "tried creating %d foobars, only created %d", foobarsReqd, foobarsCreated)
46
63
```
47
64
48
65
On the other hand, overly verbose logging, particularly of non-error conditions, can make
49
66
it unnecessarily difficult to figure out whether a test failed and if
50
67
so why? So don't log lots of irrelevant stuff either.
51
68
69
+ Except for this special case, using Gomega assertions directly is
70
+ encouraged. They are more versatile than the (few) wrappers that were added to
71
+ the E2E framework. Use assertions that match the check in the test. Using Go
72
+ code to evaluate some condition and then checking the result often isn't
73
+ informative. For example this check should be avoided:
74
+
75
+ ```
76
+ gomega.Expect(strings.Contains(actualStr, expectedSubStr)).To(gomega.Equal(true))
77
+ ```
78
+
79
+ Better pass both values to Gomega, which will automatically include them in the
80
+ failure message. Add an annotation that explains what the assertion is about:
81
+
82
+ ```
83
+ gomega.Expect(actualStr).To(gomega.ContainSubstring("xyz"), "checking log output")
84
+ ```
85
+
86
+ This produces the following failure message:
87
+ ```
88
+ [FAILED] checking log output
89
+ Expected
90
+ <string>: hello world
91
+ to contain substring
92
+ <string>: xyz
93
+ ```
94
+
95
+ If there is no suitable Gomega assertion, call ` ginkgo.Failf ` directly:
96
+ ```
97
+ import "github.com/onsi/gomega/format"
98
+
99
+ ok := someCustomCheck(abc)
100
+ if !ok {
101
+ ginkgo.Failf("check xyz failed for object:\n%s", format.Object(abc))
102
+ }
103
+ ```
104
+
105
+ [ Comparing a boolean] ( https://github.com/kubernetes/kubernetes/issues/105678 )
106
+ like this against ` true ` or ` false ` with ` gomega.Equal ` or
107
+ ` framework.ExpectEqual ` is not useful because dumping the actual and expected
108
+ value just distracts from the underlying failure reason.
109
+
110
+ Dumping structs with ` format.Object ` is recommended. Starting with Kubernetes
111
+ 1.26, ` format.Object ` will pretty-print Kubernetes API objects or structs [ as
112
+ YAML and omit unset
113
+ fields] ( https://github.com/kubernetes/kubernetes/pull/113384 ) , which is more
114
+ readable than other alternatives like ` fmt.Sprintf("%+v") ` .
115
+
116
+ Consider writing a [ Gomega
117
+ matcher] ( https://onsi.github.io/gomega/#adding-your-own-matchers ) . It combines
118
+ the custom check and generating the failure messages and can make tests more
119
+ readable.
120
+
121
+ It is good practice to include details like the object that failed some
122
+ assertion in the failure message because then a) the information is available
123
+ when analyzing a failure that occurred in the CI and b) it only gets logged
124
+ when some assertion fails. Always dumping objects via log messages can make the
125
+ test output very large and may distract from the relevant information.
126
+
127
+ #### Recovering from test failures ####
128
+
129
+ All tests should ensure that a cluster is restored to the state that it was in
130
+ before the test ran. [ ` ginkgo.DeferCleanup `
131
+ ] ( https://pkg.go.dev/github.com/onsi/ginkgo/v2#DeferCleanup ) is recommended for
132
+ this because it can be called similar to ` defer ` directly after setting up
133
+ something. It is better than ` defer ` because Ginkgo will show additional
134
+ details about which cleanup code is running and (if possible) handle timeouts
135
+ for that code (see next section). Is is better than ` ginkgo.AfterEach ` because
136
+ it is not necessary to define additional variables and because
137
+ ` ginkgo.DeferCleanup ` executes code in the more useful last-in-first-out order,
138
+ i.e. things that get set up first get removed last.
139
+
140
+ Objects created in the test namespace do not need to be deleted because
141
+ deleting the namespace will also delete them. However, if deleting an object
142
+ may fail, then explicitly cleaning it up is better because then failures or
143
+ timeouts related to it will be more obvious.
144
+
145
+ In cases where the test may have removed the object, ` framework.IgnoreNotFound `
146
+ can be used to ignore the "not found" error:
147
+ ```
148
+ podClient := f.ClientSet.CoreV1().Pods(f.Namespace.Name)
149
+ pod, err := podClient.Create(ctx, testPod, metav1.CreateOptions{})
150
+ framework.ExpectNoError(err, "create test pod")
151
+ ginkgo.DeferCleanup(framework.IgnoreNotFound(podClient.Delete), pod.Name, metav1.DeleteOptions{})
152
+ ```
153
+
154
+ #### Interrupting tests ####
155
+
156
+ When aborting a manual ` gingko ./test/e2e ` invocation with CTRL-C or a signal,
157
+ the currently running test(s) should stop immediately. This gets achieved by
158
+ accepting a ` ctx context.Context ` as first parameter in the Ginkgo callback
159
+ function and then passing that context through to all code that might
160
+ block. When Ginkgo notices that it needs to shut down, it will cancel that
161
+ context and all code trying to use it will immediately return with a `context
162
+ canceled` error. Cleanup callbacks get a new context which will time out
163
+ eventually to ensure that tests don't get stuck. For a detailed description,
164
+ see https://onsi.github.io/ginkgo/#interrupting-aborting-and-timing-out-suites .
165
+ Most of the E2E tests [ were update to use the Ginkgo
166
+ context] ( https://github.com/kubernetes/kubernetes/pull/112923 ) at the start of
167
+ the 1.27 development cycle.
168
+
169
+ There are some gotchas:
170
+
171
+ - Don't use the ` ctx ` passed into ` ginkgo.It ` in a ` ginkgo.DeferCleanup `
172
+ callback because the context will be canceled when the cleanup code
173
+ runs. This is wrong:
174
+
175
+ ginkgo.It("something", func(ctx context.Context) {
176
+ ...
177
+ ginkgo.DeferCleanup(func() {
178
+ // do something with ctx
179
+ })
180
+ })
181
+
182
+ Instead, register a function which accepts a new context:
183
+
184
+ ginkgo.DeferCleanup(func(ctx context.Context) {
185
+ // do something with the new ctx
186
+ })
187
+
188
+ Anonymous functions can be avoided by passing some existing function and its
189
+ parameters directly to ` ginkgo.DeferCleanup ` . Again, beware to * not* pass the
190
+ wrong ` ctx ` . This is wrong:
191
+
192
+ ginkgo.It("something", func(ctx context.Context) {
193
+ ...
194
+ ginkgo.DeferCleanup(myDeleteFunc, ctx, objName)
195
+ })
196
+
197
+ Instead, just pass the other parameters and let ` ginkgo.DeferCleanup `
198
+ add a new context:
199
+
200
+ ginkgo.DeferCleanup(myDeleteFunc, objName)
201
+
202
+ - When starting some background goroutine in a ` ginkgo.BeforeEach ` callback,
203
+ use ` context.WithCancel(context.Background()) ` . The context passed into the
204
+ callback will get canceled when the callback returns, which would cause the
205
+ background goroutine to stop before the test runs. This works:
206
+
207
+ backgroundCtx, cancel := context.WithCancel(context.Background())
208
+ ginkgo.DeferCleanup(cancel)
209
+ _, controller = cache.NewInformer( ... )
210
+ go controller.Run(backgroundCtx.Done())
211
+
212
+ - When adding a timeout to the context for one particular operation,
213
+ beware of overwriting the ` ctx ` variable. This code here applies
214
+ the timeout to the next call and everything else that follows:
215
+
216
+ ctx, cancel := context.WithTimeout(ctx, 5 * time.Second)
217
+ defer cancel()
218
+ someOperation(ctx)
219
+ ...
220
+ anotherOperation(ctx)
221
+
222
+ Better use some other variable name:
223
+
224
+ timeoutCtx, cancel := context.WithTimeout(ctx, 5 * time.Second)
225
+ defer cancel()
226
+ someOperation(timeoutCtx)
227
+
228
+ When the intention is to set a timeout for the entire callback, use
229
+ [ ` ginkgo.NodeTimeout ` ] ( https://pkg.go.dev/github.com/onsi/ginkgo/v2#NodeTimeout ) :
230
+
231
+ ginkgo.It("something", ginkgo.NodeTimeout(30 * time.Second), func(ctx context.Context) {
232
+ })
233
+
234
+ There is also a ` ginkgo.SpecTimeout ` , but that then also includes the time
235
+ taken for ` BeforeEach ` , ` AfterEach ` and ` DeferCleanup ` callbacks.
236
+
237
+ #### Polling and timeouts ####
238
+
239
+ When waiting for something to happen, use a reasonable timeout. Without it, a
240
+ test might keep running until the entire test suite gets killed by the
241
+ CI. Beware that the CI under load may take a lot longer to complete some
242
+ operation compared to running the same test locally. On the other hand, a too
243
+ long timeout can be annoying when trying to debug tests locally.
244
+
245
+ The framework provides some [ common
246
+ timeouts] ( https://github.com/kubernetes/kubernetes/blob/eba98af1d8b19b120e39f3/test/e2e/framework/timeouts.go#L44-L109 )
247
+ through the [ framework
248
+ instance] ( https://github.com/kubernetes/kubernetes/blob/1e84987baccbccf929eba98af1d8b19b120e39f3/test/e2e/framework/framework.go#L122-L123 ) .
249
+ When writing a test, check whether one of those fits before defining a custom
250
+ timeout in the test.
251
+
252
+ Good code that waits for something to happen meets the following criteria:
253
+ - accepts a context for test timeouts
254
+ - informative during interactive use (i.e. intermediate reports, either
255
+ periodically or on demand)
256
+ - little to no output during a CI run except when it fails
257
+ - full explanation when it fails: when it observes some state and then
258
+ encounters errors reading the state, then dumping both the latest
259
+ observed state and the latest error is useful
260
+ - extension mechanism for writing custom checks
261
+ - early abort when condition cannot be reached anymore
262
+
263
+ [ ` gomega.Eventually ` ] ( https://pkg.go.dev/github.com/onsi/gomega#Eventually )
264
+ satisfies all of these criteria and therefore is recommended, but not required.
265
+ In https://github.com/kubernetes/kubernetes/pull/113298 ,
266
+ [ test/e2e/framework/pods/wait.go] ( https://github.com/pohly/kubernetes/blob/222f65506252354da012c2e9d5457a6944a4e681/test/e2e/framework/pod/wait.go )
267
+ and the framework were modified to use gomega. Typically, ` Eventually ` is
268
+ passed a function which gets an object or lists several of them, then ` Should `
269
+ checks against the expected result. Errors and retries specific to Kubernetes
270
+ are handled by [ wrapping client-go
271
+ functions] ( https://github.com/kubernetes/kubernetes/blob/master/test/e2e/framework/get.go ) .
272
+
273
+ Using gomega assertions in helper packages is problematic for two reasons:
274
+ - The stacktrace associated with the failure starts with the helper unless
275
+ extra care is take to pass in a stack offset.
276
+ - Additional explanations for a potential failure must be prepared beforehand
277
+ and passed in.
278
+
279
+ The E2E framework therefore uses a different approach:
280
+ - [ ` framework.Gomega() ` ] ( https://github.com/pohly/kubernetes/blob/222f65506252354da012c2e9d5457a6944a4e681/test/e2e/framework/expect.go#L80-L101 )
281
+ offers similar functions as the ` gomega ` package, except that they return a
282
+ normal error instead of failing the test.
283
+ - That error gets wrapped with ` fmt.Errorf("<explanation>: %w) ` to
284
+ add additional information, just as in normal Go code.
285
+ - Wrapping the error (` %w ` instead of ` %v ` ) is important because then
286
+ ` framework.ExpectNoError ` directly uses the error message as failure without
287
+ additional boiler plate text. It also is able to log the stacktrace where
288
+ the error occurred and not just where it was finally treated as a test
289
+ failure.
290
+
291
+ Some tips for writing and debugging long-running tests:
292
+
293
+ - Use ` ginkgo.By ` to record individual steps. Ginkgo will use that information
294
+ when describing where a test timed out.
295
+
296
+ - Invoke the ` ginkgo ` CLI with ` --poll-progress-after=30s ` or some other
297
+ suitable duration to [ be informed
298
+ early] ( https://onsi.github.io/ginkgo/#getting-visibility-into-long-running-specs )
299
+ why a test doesn't complete and where it is stuck. A SIGINFO or SIGUSR1
300
+ signal can be sent to the CLI and/or e2e.test processes to trigger an
301
+ immediate progress report.
302
+
303
+ - Use [ ` gomega.Eventually ` ] ( https://pkg.go.dev/github.com/onsi/gomega#Eventually )
304
+ to wait for some condition. When it times out or
305
+ gets stuck, the last failed assertion will be included in the report
306
+ automatically. A good way to invoke it is:
307
+
308
+ gomega.Eventually(ctx, func(ctx context.Context) (book Book, err error) {
309
+ // Retrieve book from API server and return it.
310
+ ...
311
+ }).WithPolling(5 * time.Second).WithTimeout(30 * time.Second).
312
+ Should(gomega.HaveField("Author.DOB.Year()", BeNumerically("<", 1900)))
313
+
314
+ Avoid testing for some condition inside the callback and returning a boolean
315
+ because then failure messages are not informative (see above).
316
+
317
+ Some of the E2E framework sub-packages have helper functions that wait for
318
+ certain domain-specific conditions. Currently most of these functions don't
319
+ follow best practices (not using gomega.Eventually, error messages not very
320
+ informative). [ Work is
321
+ planned] ( https://github.com/kubernetes/kubernetes/issues/106575 ) in that
322
+ area, so beware that these APIs may
323
+ change at some point.
324
+
325
+ - Use ` gomega.Consistently ` to ensure that some condition is true
326
+ for a while.
327
+
328
+ - Both ` gomega.Consistently ` and ` gomega.Eventually ` can be aborted early via
329
+ [ ` gomega.StopPolling ` ] ( https://onsi.github.io/gomega/#bailing-out-early---polling-functions ) .
330
+
331
+ - Avoid polling with functions that don't take a context (` wait.Poll ` ,
332
+ ` wait.PollImmediate ` , ` wait.Until ` , ...) and replace with their counterparts
333
+ that do (` wait.PollWithContext ` , ` wait.PollImmediateWithContext ` ,
334
+ ` wait.UntilWithContext ` , ...) or even better, with ` gomega.Eventually ` .
335
+
336
+
52
337
#### Ability to run in non-dedicated test clusters ####
53
338
54
339
To reduce end-to-end delay and improve resource utilization when
0 commit comments