Debian Codegraph @

tb.go

raw
1 package check
2
3 import (
4 "bytes"
5 "context"
6 "fmt"
7 "slices"
8 "strings"
9 "testing"
10
11 "github.com/powerman/check/internal/contextx"
12 )
13
14 // checks holds all check-specific state and the whole checker/report machinery
15 // (Nil, Equal, ..., Must, Should, TODO/MustAll bookkeeping).
16 // It is embedded anonymously in both [TB] and [C],
17 // which is what gives each of them the full checker API for free.
18 //
19 // checks deliberately does NOT implement any [testing.TB] method
20 // (Error, Errorf, Fail, FailNow, Context, Helper, Cleanup, ...):
21 // every call into the real test/benchmark/fuzz target
22 // goes through the explicit tb field instead of through embedding.
23 // TB and C each separately embed their own single,
24 // unambiguous [testing.TB]-implementing source
25 // (the wrapped [testing.TB] for TB, the wrapped [*testing.T] for C) -
26 // since checks never claims any of the same method names,
27 // embedding it alongside that source never creates an ambiguous selector,
28 // and - just as important - Helper/Cleanup/etc. promoted from that single source
29 // stay genuinely zero-cost (no synthetic wrapper frame),
30 // so a caller-defined helper that itself calls t.Helper()
31 // correctly hides its own frame from failure locations.
32 type checks struct {
33 tb testing.TB
34
35 todo bool
36 must bool
37 ctx context.Context // Non-nil only after MergeContext.
38 }
39
40 func (c *checks) withTODO() *checks {
41 d := *c
42 d.todo = true
43 return &d
44 }
45
46 func (c *checks) withMustAll() *checks {
47 d := *c
48 d.must = true
49 return &d
50 }
51
52 // context returns the context associated with c:
53 // the one merged in by the most recent MergeContext call if any, otherwise tb's own Context().
54 func (c *checks) context() context.Context {
55 if c.ctx != nil {
56 return c.ctx
57 }
58 return c.tb.Context()
59 }
60
61 // mergeContext returns a *checks derived from c
62 // whose context() combines ctx with the current context():
63 // values are looked up in ctx first, falling back to the current context();
64 // cancellation/deadline come from both, whichever happens first.
65 // Calling it again merges in one more context.
66 // The returned cancel must be registered by the caller (TB/C),
67 // since only they know which Cleanup to call it through.
68 func (c *checks) mergeContext(ctx context.Context) (*checks, context.CancelFunc) {
69 merged, cancel := contextx.Merge(ctx, c.context())
70 d := *c
71 d.ctx = merged
72 return &d, cancel
73 }
74
75 func (c *checks) pass() {
76 statsMu.Lock()
77 defer statsMu.Unlock()
78
79 if stats[c.tb] == nil {
80 stats[c.tb] = newTestStat(c.tb.Name(), false)
81 }
82 if c.todo {
83 stats[c.tb].forged.value++
84 } else {
85 stats[c.tb].passed.value++
86 }
87 }
88
89 func (c *checks) fail() {
90 statsMu.Lock()
91 defer statsMu.Unlock()
92
93 if stats[c.tb] == nil {
94 stats[c.tb] = newTestStat(c.tb.Name(), false)
95 }
96 stats[c.tb].failed.value++
97 }
98
99 func (c *checks) report(ok bool, msg []any, checker string, name []string, args []any) bool { //nolint:revive // False positive.
100 c.tb.Helper()
101
102 if ok != c.todo {
103 c.pass()
104 return ok
105 }
106
107 if c.todo {
108 checker = "TODO " + checker
109 }
110
111 dump := make([]dump, 0, len(args))
112 for _, arg := range args {
113 dump = append(dump, newDump(arg))
114 }
115
116 failure := new(bytes.Buffer)
117 fmt.Fprintf(failure, "%s\nChecker: %s%s%s\n",
118 format(msg...),
119 ansiYellow, checker, ansiReset,
120 )
121 // Reverse order to show Actual: last.
122 for i, v := range slices.Backward(dump) {
123 fmt.Fprintf(failure, "%-10s", name[i]+":")
124 switch name[i] {
125 case nameActual:
126 fmt.Fprint(failure, ansiRed)
127 default:
128 fmt.Fprint(failure, ansiGreen)
129 }
130 fmt.Fprintf(failure, "%s%s", v, ansiReset)
131 }
132
133 wantDiff := len(dump) == 2 && name[0] == nameActual && name[1] == nameExpected
134 if wantDiff {
135 fmt.Fprintf(failure, "\n%s", colouredDiff(dump[0].diff(dump[1])))
136 }
137 c.tb.Errorf("%s\n", failure)
138
139 c.fail()
140
141 if c.must {
142 c.tb.FailNow() // Already counted above: bypass the counting FailNow wrapper.
143 }
144 return ok
145 }
146
147 func (c *checks) reportShould1(funcName string, actual any, msg []any, ok bool) bool {
148 c.tb.Helper()
149 return c.report(ok, msg,
150 "Should "+funcName,
151 []string{nameActual},
152 []any{actual})
153 }
154
155 func (c *checks) reportShould2(funcName string, actual, expected any, msg []any, ok bool) bool {
156 c.tb.Helper()
157 return c.report(ok, msg,
158 "Should "+funcName,
159 []string{nameActual, nameExpected},
160 []any{actual, expected})
161 }
162
163 func (c *checks) report0(msg []any, ok bool) bool {
164 c.tb.Helper()
165 return c.report(ok, msg,
166 callerFuncName(1),
167 []string{},
168 []any{})
169 }
170
171 func (c *checks) report1(actual any, msg []any, ok bool) bool {
172 c.tb.Helper()
173 return c.report(ok, msg,
174 callerFuncName(1),
175 []string{nameActual},
176 []any{actual})
177 }
178
179 func (c *checks) report2(actual, expected any, msg []any, ok bool) bool {
180 c.tb.Helper()
181 checker, arg2Name := callerFuncName(1), nameExpected
182 if strings.Contains(checker, "Match") {
183 arg2Name = "Regex"
184 }
185 return c.report(ok, msg,
186 checker,
187 []string{nameActual, arg2Name},
188 []any{actual, expected})
189 }
190
191 func (c *checks) report3(actual, expected1, expected2 any, msg []any, ok bool) bool {
192 c.tb.Helper()
193 checker, arg2Name, arg3Name := callerFuncName(1), "arg1", "arg2"
194 switch {
195 case strings.Contains(checker, "Between"):
196 arg2Name, arg3Name = "Min", "Max"
197 case strings.Contains(checker, "Delta"):
198 arg2Name, arg3Name = nameExpected, "Delta"
199 case strings.Contains(checker, "SMAPE"):
200 arg2Name, arg3Name = nameExpected, "SMAPE"
201 }
202 return c.report(ok, msg,
203 checker,
204 []string{nameActual, arg2Name, arg3Name},
205 []any{actual, expected1, expected2})
206 }
207
208 // Must interrupt test using t.FailNow if called with false value.
209 //
210 // This provides an easy way to turn any check into assertion:
211 //
212 // t.Must(t.Nil(err))
213 func (c *checks) Must(continueTest bool, msg ...any) { //nolint:revive // False positive.
214 c.tb.Helper()
215 c.report0(msg, continueTest)
216 if !continueTest {
217 c.tb.FailNow() // Already counted above: bypass the counting FailNow wrapper.
218 }
219 }
220
221 // TB wraps [testing.TB] to make it convenient to call checkers in tests,
222 // benchmarks and fuzz targets.
223 //
224 // Use [New] or [Must] to create it.
225 // [C] is a thin, [*testing.T]-only compatibility shell built on top of the same machinery.
226 type TB struct {
227 testing.TB
228 *checks
229 }
230
231 var _ testing.TB = (*TB)(nil)
232
233 type (
234 // ShouldFunc1 is like Nil or Zero.
235 ShouldFunc1 func(t *TB, actual any) bool
236 // ShouldFunc2 is like Equal or Match.
237 ShouldFunc2 func(t *TB, actual, expected any) bool
238 )
239
240 // Should use user-provided check function to do actual check.
241 //
242 // anyShouldFunc must have type ShouldFunc1 or ShouldFunc2.
243 // It should return true if check was successful.
244 // There is no need to call t.Error in anyShouldFunc -
245 // this will be done automatically when it returns.
246 //
247 // args must contain at least 1 element for ShouldFunc1 and at least 2 elements for ShouldFunc2.
248 // Rest of elements will be processed as usual msg ...interface{} param.
249 //
250 // Example:
251 //
252 // func bePositive(_ *check.TB, actual interface{}) bool {
253 // return actual.(int) > 0
254 // }
255 // func TestCustomCheck(tt *testing.T) {
256 // t := check.T(tt)
257 // t.Should(bePositive, 42, "custom check!!!")
258 // }
259 func (t *TB) Should(anyShouldFunc any, args ...any) bool {
260 t.Helper()
261 switch f := anyShouldFunc.(type) {
262 case func(t *TB, actual any) bool:
263 return t.should1(f, args...)
264 case func(t *TB, actual, expected any) bool:
265 return t.should2(f, args...)
266 default:
267 panic("anyShouldFunc is not a ShouldFunc1 or ShouldFunc2")
268 }
269 }
270
271 func (t *TB) should1(f ShouldFunc1, args ...any) bool {
272 t.Helper()
273 if len(args) < 1 {
274 panic("not enough params for " + funcName(f))
275 }
276 actual, msg := args[0], args[1:]
277 return t.reportShould1(funcName(f), actual, msg,
278 f(t, actual))
279 }
280
281 func (t *TB) should2(f ShouldFunc2, args ...any) bool {
282 t.Helper()
283 const minArgs = 2
284 if len(args) < minArgs {
285 panic("not enough params for " + funcName(f))
286 }
287 actual, expected, msg := args[0], args[1], args[2:]
288 return t.reportShould2(funcName(f), actual, expected, msg,
289 f(t, actual, expected))
290 }
291
292 // New creates and returns new *TB, which wraps given tb and supposed to be used inplace of it,
293 // providing you with access to many useful helpers in addition to standard methods
294 // of [testing.TB].
295 //
296 // A failed check does not stop the test - use [TB.MustAll] or [TB.Must](continueTest)
297 // to turn checks into assertions. See [Must] for a fail-fast alternative.
298 //
299 // TB doesn't provide Run/Parallel: call tb.Run/tb.Parallel on the original
300 // [*testing.T]/[*testing.B]/[*testing.F].
301 func New(tb testing.TB) *TB { //nolint:thelper // With check we name it tb, not t!
302 return &TB{TB: tb, checks: &checks{tb: tb}}
303 }
304
305 // Must creates and returns new *TB like [New],
306 // but every failed check will interrupt the test using [TB.FailNow].
307 //
308 // This is the recommended default constructor for new tests.
309 func Must(tb testing.TB) *TB { //nolint:thelper // With check we name it tb, not t!
310 return &TB{TB: tb, checks: &checks{tb: tb, must: true}}
311 }
312
313 // TODO creates and returns new *TB, which have only one difference from original one:
314 // every passing check is now handled as failed and vice versa
315 // (this doesn't affect boolean value returned by check).
316 // You can continue using both old and new *TB at same time.
317 //
318 // Swapping passed/failed gives you ability to temporary mark some failed test as passed.
319 // For example, this may be useful to avoid broken builds in CI.
320 // This is often better than commenting, deleting or skipping broken test
321 // because it will continue to execute,
322 // and eventually when reason why it fails will be fixed this test will became failed again -
323 // notifying you the mark can and should be removed from this test now.
324 func (t *TB) TODO() *TB {
325 return &TB{TB: t.TB, checks: t.withTODO()}
326 }
327
328 // MustAll creates and returns new *TB, which have only one difference from original one:
329 // every failed check will interrupt test using t.FailNow.
330 // You can continue using both old and new *TB at same time.
331 //
332 // This provides an easy way to turn all checks into assertion.
333 func (t *TB) MustAll() *TB {
334 return &TB{TB: t.TB, checks: t.withMustAll()}
335 }
336
337 // Context returns the context associated with t:
338 // the context merged in by the most recent [TB.MergeContext] call if any,
339 // otherwise the standard [testing.TB.Context]().
340 func (t *TB) Context() context.Context {
341 return t.context()
342 }
343
344 // MergeContext returns a derived *TB whose Context() combines ctx with the current Context():
345 // values are looked up in ctx first, falling back to the current Context();
346 // cancellation/deadline come from both, whichever happens first.
347 // Calling MergeContext again merges in one more context.
348 //
349 // This is meant for injecting an application base context (e.g. one carrying a slog handler)
350 // into tests, on top of the per-test cancellation/deadline testing.TB.Context() already provides.
351 func (t *TB) MergeContext(ctx context.Context) *TB {
352 merged, cancel := t.mergeContext(ctx)
353 t.Cleanup(cancel)
354 return &TB{TB: t.TB, checks: merged}
355 }
356
357 // Error is equivalent to Log followed by Fail.
358 //
359 // It is like t.Errorf with TODO() and statistics support.
360 func (t *TB) Error(args ...any) {
361 t.Helper()
362 t.report0(args, false)
363 }
364
365 // Errorf is equivalent to Logf followed by Fail.
366 //
367 // It is like t.Errorf with TODO() and statistics support.
368 func (t *TB) Errorf(format string, args ...any) {
369 t.Helper()
370 t.report0(append([]any{format}, args...), false)
371 }
372
373 // Fatal is equivalent to Log followed by FailNow.
374 //
375 // It is like t.Fatal with TODO() and statistics support.
376 func (t *TB) Fatal(args ...any) {
377 t.Helper()
378 t.report0(args, false)
379 if !t.todo {
380 t.TB.FailNow() // Already counted above: bypass the counting FailNow wrapper.
381 }
382 }
383
384 // Fatalf is equivalent to Logf followed by FailNow.
385 //
386 // It is like t.Fatalf with TODO() and statistics support.
387 func (t *TB) Fatalf(format string, args ...any) {
388 t.Helper()
389 t.report0(append([]any{format}, args...), false)
390 if !t.todo {
391 t.TB.FailNow() // Already counted above: bypass the counting FailNow wrapper.
392 }
393 }
394
395 // Fail marks the function as having failed but continues execution.
396 //
397 // Unlike plain [testing.TB.Fail], calling it directly (rather than through
398 // a checker) is still counted in check's pass/fail statistics.
399 func (t *TB) Fail() {
400 t.fail()
401 t.TB.Fail()
402 }
403
404 // FailNow marks the function as having failed and stops its execution.
405 //
406 // Unlike plain [testing.TB.FailNow], calling it directly (rather than
407 // through a checker) is still counted in check's pass/fail statistics.
408 func (t *TB) FailNow() {
409 t.fail()
410 t.TB.FailNow()
411 }