Repository navigation
Expand file tree
/
Copy pathtesting.go
More file actions
427 lines (367 loc) · 11.7 KB
/
Copy pathtesting.go
File metadata and controls
427 lines (367 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package devtest
import (
"context"
"fmt"
"os"
"runtime"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"github.com/ethereum-optimism/optimism/op-service/log"
"github.com/ethereum-optimism/optimism/op-service/log/logfilter"
"github.com/ethereum-optimism/optimism/op-service/logmods"
"github.com/ethereum-optimism/optimism/op-service/testlog"
"github.com/ethereum-optimism/optimism/op-service/testreq"
)
const ExpectPreconditionsMet = "DEVNET_EXPECT_PRECONDITIONS_MET"
const FailFlakyTests = "DEVNET_FAIL_FLAKY_TESTS"
var (
// RootContext is the context that is used for the root of the test suite.
// It should be set for good before any tests are run.
RootContext = context.Background()
)
type T interface {
CommonT
// TempDir creates a temporary directory, and returns the file-path.
// This directory is cleaned up at the end of the test, and must not be shared between tests.
TempDir() string
// Cleanup runs the given function at the end of the test-scope,
// or at the end of the sub-test (if this is a nested test).
// This function will clean-up before the package-level testing scope may be complete.
// Do not use the test-scope cleanup with shared resources.
Cleanup(fn func())
// Run runs the given function in as a sub-test.
Run(name string, fn func(T))
// Ctx returns a context that will be canceled at the end of this (sub) test-scope,
// and inherits the context of the parent-test-scope.
Ctx() context.Context
// WithCtx makes a copy of T with a specific context.
// The ctx must match the test-scope of the existing context.
// This function is used to create a T with annotated context, e.g. a specific resource, rather than a sub-scope.
WithCtx(ctx context.Context) T
// Parallel signals that this test is to be run in parallel with (and only with) other parallel tests.
Parallel()
// Skip is equivalent to Log followed by SkipNow.
Skip(args ...any)
// Skipped reports whether the test was skipped.
Skipped() bool
// Skipf is equivalent to Logf followed by SkipNow.
Skipf(format string, args ...any)
// SkipNow marks the test as skipped and stops test execution.
// It is remapped to FailNow if the env var DEVNET_EXPECT_PRECONDITIONS_MET is set to true.
SkipNow()
// Gate provides everything that Require does, but skips instead of fails the test upon error.
Gate() *testreq.Assertions
// MarkFlaky downgrades future test failures to skips unless DEVNET_FAIL_FLAKY_TESTS is set.
// Call this near the top of the test, before storing any Require()-derived helper.
MarkFlaky(reason string)
// Deadline reports the time at which the test binary will have
// exceeded the timeout specified by the -timeout flag.
//
// The ok result is false if the -timeout flag indicates "no timeout" (0).
Deadline() (deadline time.Time, ok bool)
// This distinguishes the interface from other testing interfaces,
// such as the one used at package-level for shared system construction.
TestOnly()
}
// This testing subset is sufficient for the require.Assertions to work.
var _ require.TestingT = T(nil)
// testingT implements the T interface by wrapping around a regular golang testing.T
type testingT struct {
t *testing.T
logger log.Logger
tracer trace.Tracer
ctx context.Context
req *testreq.Assertions
gate *testreq.Assertions
flaky bool
reason string
}
func mustNotSkip() bool {
v := os.Getenv(ExpectPreconditionsMet)
out, _ := strconv.ParseBool(v) // default to false
return out
}
func mustFailFlakyTests() bool {
v := os.Getenv(FailFlakyTests)
out, _ := strconv.ParseBool(v) // default to false
return out
}
func (t *testingT) shouldSkipFlakyFailure() bool {
return t.flaky && !mustFailFlakyTests()
}
func (t *testingT) skipFlakyFailure(msg string) {
if t.reason != "" {
t.logger.Warn("Ignoring failure in flaky test", "reason", t.reason, "failure", msg)
t.t.Skipf("FLAKY_FAIL: %s: %s", t.reason, msg)
} else {
t.logger.Warn("Ignoring failure in flaky test", "failure", msg)
t.t.Skipf("FLAKY_FAIL: %s", msg)
}
}
func (t *testingT) Error(args ...any) {
t.t.Helper()
if t.shouldSkipFlakyFailure() {
t.skipFlakyFailure(fmt.Sprintln(args...))
return
}
// Write directly to testing.T, not the structured logger. The structured logger's
// terminal handler quotes messages containing '=' (via escapeMessage/strconv.Quote),
// which escapes all \n and \t, making testify's multi-line assertion diffs unreadable.
t.t.Error(args...)
}
func (t *testingT) Errorf(format string, args ...any) {
t.t.Helper()
if t.shouldSkipFlakyFailure() {
t.skipFlakyFailure(fmt.Sprintf(format, args...))
return
}
// Write directly to testing.T, not the structured logger. The structured logger's
// terminal handler quotes messages containing '=' (via escapeMessage/strconv.Quote),
// which escapes all \n and \t, making testify's multi-line assertion diffs unreadable.
t.t.Errorf(format, args...)
}
func (t *testingT) Fail() {
t.t.Helper()
if t.shouldSkipFlakyFailure() {
t.skipFlakyFailure("test called Fail")
return
}
// if we already closed and failed, then this error is stale
if t.ctx.Err() != nil && t.t.Failed() {
return
}
t.t.Fail()
}
func (t *testingT) FailNow() {
t.t.Helper()
if t.shouldSkipFlakyFailure() {
t.skipFlakyFailure("test called FailNow")
return
}
// If we already closed and failed the test-scope, then there is nothing to do.
// This happens on e.g. a go-routine spawned by require.Eventually, when the time runs out,
// the ctx is closed, a shared resource fails to do a lookup because of the ctx-timeout,
// and the eventually-condition then does a no-error check, causing the test-scope to error after it already had.
if t.ctx.Err() != nil && t.t.Failed() {
// Exit the go-routine that is running us (actual testing.T FailNow does this too).
// Still runs deferred calls on this go-routine.
runtime.Goexit()
return
}
t.t.FailNow()
}
func (t *testingT) TempDir() string {
return t.t.TempDir()
}
func (t *testingT) TempDirWithPrefix(prefix string) string {
t.t.Helper()
tempDir, err := os.MkdirTemp("", tempDirPattern(prefix))
if err != nil {
t.Errorf("failed to create temp dir: %v", err)
t.FailNow()
}
require.NotEmpty(t, tempDir, "sanity check temp-dir path is not empty")
require.NotEqual(t, "/", tempDir, "sanity-check temp-dir is not root")
t.Cleanup(func() {
if err := os.RemoveAll(tempDir); err != nil {
t.logger.Error("Failed to clean up temp dir", "dir", tempDir, "err", err)
}
})
return tempDir
}
func (t *testingT) Cleanup(fn func()) {
t.t.Cleanup(fn)
}
func (t *testingT) Log(args ...any) {
t.t.Helper()
// Note: the test-logger catches panics when the test is logged to after test-end.
// Note: we do not use t.Log directly, to keep the log-formatting more consistent.
t.logger.Info(fmt.Sprintln(args...))
}
func (t *testingT) Logf(format string, args ...any) {
t.t.Helper()
// Note: the test-logger catches panics when the test is logged to after test-end.
// Note: we do not use t.Logf directly, to keep the log-formatting more consistent.
t.logger.Info(fmt.Sprintf(format, args...))
}
func (t *testingT) Helper() {
t.t.Helper()
}
func (t *testingT) Name() string {
return t.t.Name()
}
func (t *testingT) Logger() log.Logger {
return t.logger
}
func (t *testingT) Tracer() trace.Tracer {
return t.tracer
}
func (t *testingT) Ctx() context.Context {
return t.ctx
}
func (t *testingT) WithCtx(ctx context.Context) T {
expected := TestScope(t.ctx)
got := TestScope(ctx)
t.req.Equal(expected, got, "cannot replace context with different test-scope")
logger := t.logger.WithContext(ctx)
out := &testingT{
t: t.t,
logger: logger,
tracer: t.tracer,
ctx: ctx,
flaky: t.flaky,
reason: t.reason,
}
out.req = testreq.New(out)
out.gate = testreq.New(&gateAdapter{out})
return out
}
func (t *testingT) Require() *testreq.Assertions {
return t.req
}
func (t *testingT) MarkFlaky(reason string) {
t.flaky = true
if reason != "" {
t.reason = reason
}
t.t.Cleanup(func() {
if !t.t.Failed() && !t.t.Skipped() && !mustFailFlakyTests() {
if t.reason != "" {
t.t.Skipf("FLAKY_PASS: %s", t.reason)
} else {
t.t.Skip("FLAKY_PASS")
}
}
})
}
func (t *testingT) Run(name string, fn func(T)) {
baseName := t.Name()
t.t.Run(name, func(subGoT *testing.T) {
ctx := AddTestScope(t.ctx, name)
ctx, cancel := context.WithCancel(ctx)
subGoT.Cleanup(cancel)
tracer := otel.Tracer(baseName + "::" + name)
ctx, span := tracer.Start(ctx, name)
subGoT.Cleanup(func() {
span.End()
})
logger := t.logger.WithContext(ctx) // attach the sub-test context as default log-context
subT := &testingT{
t: subGoT,
logger: logger,
tracer: tracer,
ctx: ctx,
flaky: t.flaky,
reason: t.reason,
}
subT.req = testreq.New(subT)
subT.gate = testreq.New(&gateAdapter{subT})
if subT.flaky {
subGoT.Cleanup(func() {
if !subGoT.Failed() && !subGoT.Skipped() && !mustFailFlakyTests() {
if subT.reason != "" {
subGoT.Skipf("FLAKY_PASS: %s", subT.reason)
} else {
subGoT.Skip("FLAKY_PASS")
}
}
})
}
fn(subT)
})
}
func (t *testingT) Parallel() {
t.logger.Info("Running test in parallel")
t.t.Parallel()
}
func (t *testingT) Skip(args ...any) {
t.t.Helper()
if mustNotSkip() {
t.Error("Unexpected test-skip!", fmt.Sprintln(args...))
return
}
t.Log(args...)
t.t.SkipNow()
}
func (t *testingT) Skipped() bool {
t.t.Helper()
return t.t.Skipped()
}
func (t *testingT) Skipf(format string, args ...any) {
t.t.Helper()
if mustNotSkip() {
t.Error("Unexpected test-skip!", fmt.Sprintf(format, args...))
return
}
t.Logf(format, args...)
t.t.SkipNow()
}
func (t *testingT) SkipNow() {
t.t.Helper()
if mustNotSkip() {
t.FailNow()
return
}
t.t.SkipNow()
}
func (t *testingT) Gate() *testreq.Assertions {
return t.gate
}
// Deadline reports the time at which the test binary will have
// exceeded the timeout specified by the -timeout flag.
//
// The ok result is false if the -timeout flag indicates "no timeout" (0).
func (t *testingT) Deadline() (deadline time.Time, ok bool) {
return t.t.Deadline()
}
func (t *testingT) TestOnly() {
panic("do not use - this method only forces the interface to be unique")
}
var _ T = (*testingT)(nil)
// DefaultTestLogLevel is set to info level to show relevant logs without being overly verbose unless configured otherwise.
var DefaultTestLogLevel = log.LevelInfo
// SerialT wraps around a test-logger and turns it into a T for devstack testing.
func SerialT(t *testing.T) T {
ctx := RootContext
ctx = AddTestScope(ctx, t.Name())
var cancel context.CancelFunc
if deadline, hasDeadline := t.Deadline(); hasDeadline {
ctx, cancel = context.WithDeadline(ctx, deadline.Add(-3*time.Second))
} else {
ctx, cancel = context.WithCancel(ctx)
}
t.Cleanup(cancel)
tracer := otel.Tracer(t.Name())
ctx, span := tracer.Start(ctx, t.Name())
t.Cleanup(func() {
span.End()
})
// Set the lowest default log-level, so the log-filters on top can apply correctly
baseLogger := testlog.LoggerWithHandlerMod(t, log.LevelTrace,
wrapTracingHandler, logfilter.WrapFilterHandler, logfilter.WrapContextHandler)
h, ok := logmods.FindHandler[logfilter.FilterHandler](baseLogger.Handler())
if ok {
// Apply default log level. This may be overridden later.
h.Set(logfilter.DefaultMute(logfilter.Level(log.LevelInfo).Show()))
}
logger := baseLogger.WithContext(ctx) // Set the default context; any log call without context will use this
out := &testingT{
t: t,
logger: logger,
tracer: tracer,
ctx: ctx,
}
out.req = testreq.New(out)
out.gate = testreq.New(&gateAdapter{out})
return out
}
// ParallelT creates a T interface with parallel testing enabled by default
func ParallelT(t *testing.T) T {
out := SerialT(t)
out.Parallel()
return out
}