Debian Codegraph @

td/t_struct.go

raw
1 // Copyright (c) 2018, 2019, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package td
8
9 import (
10 "reflect"
11 "strings"
12 "sync"
13 "testing"
14
15 "github.com/maxatome/go-testdeep/helpers/tdutil"
16 "github.com/maxatome/go-testdeep/internal/color"
17 "github.com/maxatome/go-testdeep/internal/trace"
18 "github.com/maxatome/go-testdeep/internal/types"
19 )
20
21 // T is a type that encapsulates [testing.TB] interface (which is
22 // implemented by [*testing.T] and [*testing.B]) allowing to easily use
23 // [*testing.T] methods as well as T ones.
24 type T struct {
25 testing.TB
26 Config ContextConfig // defaults to DefaultContextConfig
27 }
28
29 var _ testing.TB = T{}
30
31 // NewT returns a new [*T] instance. Typically used as:
32 //
33 // import (
34 // "testing"
35 //
36 // "github.com/maxatome/go-testdeep/td"
37 // )
38 //
39 // type Record struct {
40 // Id uint64
41 // Name string
42 // Age int
43 // CreatedAt time.Time
44 // }
45 //
46 // func TestCreateRecord(tt *testing.T) {
47 // t := NewT(tt, ContextConfig{
48 // MaxErrors: 3, // in case of failure, will dump up to 3 errors
49 // })
50 //
51 // before := time.Now()
52 // record, err := CreateRecord()
53 //
54 // if t.CmpNoError(err) {
55 // t.Log("No error, can now check struct contents")
56 //
57 // ok := t.Struct(record,
58 // &Record{
59 // Name: "Bob",
60 // Age: 23,
61 // },
62 // td.StructFields{
63 // "Id": td.NotZero(),
64 // "CreatedAt": td.Between(before, time.Now()),
65 // },
66 // "Newly created record")
67 // if ok {
68 // t.Log(Record created successfully!")
69 // }
70 // }
71 // }
72 //
73 // config is an optional parameter and, if passed, must be unique. It
74 // allows to configure how failures will be rendered during the
75 // lifetime of the returned instance.
76 //
77 // t := NewT(tt)
78 // t.Cmp(
79 // Record{Age: 12, Name: "Bob", Id: 12}, // got
80 // Record{Age: 21, Name: "John", Id: 28}) // expected
81 //
82 // will produce:
83 //
84 // === RUN TestFoobar
85 // --- FAIL: TestFoobar (0.00s)
86 // foobar_test.go:88: Failed test
87 // DATA.Id: values differ
88 // got: (uint64) 12
89 // expected: (uint64) 28
90 // DATA.Name: values differ
91 // got: "Bob"
92 // expected: "John"
93 // DATA.Age: values differ
94 // got: 12
95 // expected: 28
96 // FAIL
97 //
98 // Now with a special configuration:
99 //
100 // t := NewT(tt, ContextConfig{
101 // RootName: "RECORD", // got data named "RECORD" instead of "DATA"
102 // MaxErrors: 2, // stops after 2 errors instead of default 10
103 // })
104 // t.Cmp(
105 // Record{Age: 12, Name: "Bob", Id: 12}, // got
106 // Record{Age: 21, Name: "John", Id: 28}, // expected
107 // )
108 //
109 // will produce:
110 //
111 // === RUN TestFoobar
112 // --- FAIL: TestFoobar (0.00s)
113 // foobar_test.go:96: Failed test
114 // RECORD.Id: values differ
115 // got: (uint64) 12
116 // expected: (uint64) 28
117 // RECORD.Name: values differ
118 // got: "Bob"
119 // expected: "John"
120 // Too many errors (use TESTDEEP_MAX_ERRORS=-1 to see all)
121 // FAIL
122 //
123 // See [T.RootName] method to configure RootName in a more specific fashion.
124 //
125 // Note that setting MaxErrors to a negative value produces a dump
126 // with all errors.
127 //
128 // If MaxErrors is not set (or set to 0), it is set to
129 // DefaultContextConfig.MaxErrors which is potentially dependent from
130 // the TESTDEEP_MAX_ERRORS environment variable (else defaults to 10.)
131 // See [ContextConfig] documentation for details.
132 //
133 // Of course t can already be a [*T], in this special case if config
134 // is omitted, the Config of the new instance is a copy of the t
135 // Config, including hooks.
136 //
137 // See also other constructors [Assert], [Require] and [AssertRequire].
138 //
139 // See also configurators [T.Assert], [T.Require], [T.RootName],
140 // [T.FailureIsFatal], [T.UseEqual], [T.BeLax], [T.IgnoreUnexported]
141 // and [T.TestDeepInGotOK].
142 func NewT(t testing.TB, config ...ContextConfig) *T {
143 var newT T
144
145 const usage = "NewT(testing.TB[, ContextConfig])"
146 if t == nil {
147 panic(color.BadUsage(usage, nil, 1, false))
148 }
149 if len(config) > 1 {
150 t.Helper()
151 t.Fatal(color.TooManyParams(usage))
152 }
153
154 // Already a *T, so steal its testing.TB and its Config if needed
155 if tdT, ok := t.(*T); ok {
156 newT.TB = tdT.TB
157 if len(config) == 0 {
158 newT.Config = tdT.Config
159 } else {
160 newT.Config = config[0]
161 }
162 } else {
163 newT.TB = t
164 if len(config) == 0 {
165 newT.Config = DefaultContextConfig
166 } else {
167 newT.Config = config[0]
168 }
169 }
170 newT.Config.sanitize()
171
172 newT.initAnchors()
173
174 return &newT
175 }
176
177 // Assert returns a new [*T] instance with FailureIsFatal flag set to
178 // false.
179 //
180 // assert := Assert(t)
181 //
182 // is roughly equivalent to:
183 //
184 // assert := NewT(t).FailureIsFatal(false)
185 //
186 // See [NewT] documentation for usefulness of config optional parameter.
187 //
188 // See also other constructors [Require] and [AssertRequire].
189 //
190 // See also configurators [T.Assert], [T.Require], [T.RootName],
191 // [T.FailureIsFatal], [T.UseEqual], [T.BeLax], [T.IgnoreUnexported]
192 // and [T.TestDeepInGotOK].
193 func Assert(t testing.TB, config ...ContextConfig) *T {
194 return NewT(t, config...).FailureIsFatal(false)
195 }
196
197 // Require returns a new [*T] instance with FailureIsFatal flag set to
198 // true.
199 //
200 // require := Require(t)
201 //
202 // is roughly equivalent to:
203 //
204 // require := NewT(t).FailureIsFatal(true)
205 //
206 // See [NewT] documentation for usefulness of config optional parameter.
207 //
208 // See also other constructors [Assert] and [AssertRequire].
209 //
210 // See also configurators [T.Assert], [T.Require], [T.RootName],
211 // [T.FailureIsFatal], [T.UseEqual], [T.BeLax], [T.IgnoreUnexported]
212 // and [T.TestDeepInGotOK].
213 func Require(t testing.TB, config ...ContextConfig) *T {
214 return NewT(t, config...).FailureIsFatal()
215 }
216
217 // AssertRequire returns 2 instances of [*T]. assert with
218 // FailureIsFatal flag set to false, and require with FailureIsFatal
219 // flag set to true.
220 //
221 // assert, require := AssertRequire(t)
222 //
223 // is roughly equivalent to:
224 //
225 // assert, require := Assert(t), Require(t)
226 //
227 // See [NewT] documentation for usefulness of config optional parameter.
228 //
229 // See also other constructors [Assert] and [Require].
230 //
231 // See also configurators [T.Assert], [T.Require], [T.RootName],
232 // [T.FailureIsFatal], [T.UseEqual], [T.BeLax], [T.IgnoreUnexported]
233 // and [T.TestDeepInGotOK].
234 func AssertRequire(t testing.TB, config ...ContextConfig) (assert, require *T) {
235 assert = Assert(t, config...)
236 require = assert.FailureIsFatal()
237 return
238 }
239
240 // RootName changes the name of the got data. By default it is
241 // "DATA". For an HTTP response body, it could be "BODY" for example.
242 //
243 // It returns a new instance of [*T] so does not alter the original t
244 // and is used as follows:
245 //
246 // t.RootName("RECORD").
247 // Struct(record,
248 // &Record{
249 // Name: "Bob",
250 // Age: 23,
251 // },
252 // td.StructFields{
253 // "Id": td.NotZero(),
254 // "CreatedAt": td.Between(before, time.Now()),
255 // },
256 // "Newly created record")
257 //
258 // In case of error for the field Age, the failure message will contain:
259 //
260 // RECORD.Age: values differ
261 //
262 // Which is more readable than the generic:
263 //
264 // DATA.Age: values differ
265 //
266 // If "" is passed the name is set to "DATA", the default value.
267 //
268 // See also other configurators [T.Assert], [T.Require],
269 // [T.FailureIsFatal], [T.UseEqual], [T.BeLax], [T.IgnoreUnexported]
270 // and [T.TestDeepInGotOK].
271 func (t *T) RootName(rootName string) *T {
272 nt := *t
273 if rootName == "" {
274 rootName = contextDefaultRootName
275 }
276 nt.Config.RootName = rootName
277 return &nt
278 }
279
280 // FailureIsFatal allows to choose whether t.TB.Fatal() or
281 // t.TB.Error() will be used to print the next failure reports. When
282 // enable is true (or missing) testing.Fatal() will be called, else
283 // testing.Error(). Using [*testing.T] or [*testing.B] instance as
284 // t.TB value, FailNow() method is called behind the scenes when
285 // Fatal() is called. See [testing] documentation for details.
286 //
287 // It returns a new instance of [*T] so does not alter the original t
288 // and used as follows:
289 //
290 // // Following t.Cmp() will call Fatal() if failure
291 // t = t.FailureIsFatal()
292 // t.Cmp(...)
293 // t.Cmp(...)
294 // // Following t.Cmp() won't call Fatal() if failure
295 // t = t.FailureIsFatal(false)
296 // t.Cmp(...)
297 //
298 // or, if only one call is critic:
299 //
300 // // This Cmp() call will call Fatal() if failure
301 // t.FailureIsFatal().Cmp(...)
302 // // Following t.Cmp() won't call Fatal() if failure
303 // t.Cmp(...)
304 // t.Cmp(...)
305 //
306 // Note that t.FailureIsFatal() acts as t.FailureIsFatal(true).
307 //
308 // See also other configurators [T.Assert], [T.Require], [T.RootName],
309 // [T.UseEqual], [T.BeLax], [T.IgnoreUnexported] and
310 // [T.TestDeepInGotOK].
311 func (t *T) FailureIsFatal(enable ...bool) *T {
312 nt := *t
313 nt.Config.FailureIsFatal = len(enable) == 0 || enable[0]
314 return &nt
315 }
316
317 // Assert returns a new [*T] instance inheriting the t config but with
318 // FailureIsFatal flag set to false.
319 //
320 // It returns a new instance of [*T] so does not alter the original t
321 //
322 // It is a shortcut for:
323 //
324 // t.FailureIsFatal(false)
325 //
326 // See also other configurators [T.Require], [T.RootName],
327 // [T.FailureIsFatal], [T.UseEqual], [T.BeLax], [T.IgnoreUnexported]
328 // and [T.TestDeepInGotOK].
329 func (t *T) Assert() *T {
330 return t.FailureIsFatal(false)
331 }
332
333 // Require returns a new [*T] instance inheriting the t config but
334 // with FailureIsFatal flag set to true.
335 //
336 // It returns a new instance of [*T] so does not alter the original t
337 //
338 // It is a shortcut for:
339 //
340 // t.FailureIsFatal(true)
341 //
342 // See also other configurators [T.Assert], [T.RootName],
343 // [T.FailureIsFatal], [T.UseEqual], [T.BeLax], [T.IgnoreUnexported]
344 // and [T.TestDeepInGotOK].
345 func (t *T) Require() *T {
346 return t.FailureIsFatal(true)
347 }
348
349 // UseEqual tells go-testdeep to delegate the comparison of items
350 // whose type is one of types to their Equal() method.
351 //
352 // The signature this method should be:
353 //
354 // (A) Equal(B) bool
355 //
356 // with B assignable to A.
357 //
358 // See [time.Time.Equal] as an example of accepted Equal() method.
359 //
360 // It always returns a new instance of [*T] so does not alter the
361 // original t.
362 //
363 // t = t.UseEqual(time.Time{}, net.IP{})
364 //
365 // types items can also be [reflect.Type] items. In this case, the
366 // target type is the one reflected by the [reflect.Type].
367 //
368 // t = t.UseEqual(reflect.TypeOf(time.Time{}), reflect.typeOf(net.IP{}))
369 //
370 // As a special case, calling t.UseEqual() or t.UseEqual(true) returns
371 // an instance using the Equal() method globally, for all types owning
372 // an Equal() method. Other types fall back to the default comparison
373 // mechanism. t.UseEqual(false) returns an instance not using Equal()
374 // method anymore, except for types already recorded using a previous
375 // UseEqual call.
376 //
377 // See also other configurators [T.Assert], [T.Require], [T.RootName],
378 // [T.FailureIsFatal], [T.BeLax], [T.IgnoreUnexported] and
379 // [T.TestDeepInGotOK].
380 func (t *T) UseEqual(types ...any) *T {
381 // special case: UseEqual()
382 if len(types) == 0 {
383 nt := *t
384 nt.Config.UseEqual = true
385 return &nt
386 }
387
388 // special cases: UseEqual(true) or UseEqual(false)
389 if len(types) == 1 {
390 if ignore, ok := types[0].(bool); ok {
391 nt := *t
392 nt.Config.UseEqual = ignore
393 return &nt
394 }
395 }
396
397 // Enable UseEqual only for types types
398 t = t.copyWithHooks()
399
400 err := t.Config.hooks.AddUseEqual(types)
401 if err != nil {
402 t.Helper()
403 t.Fatal(color.Bad("UseEqual " + err.Error()))
404 }
405
406 return t
407 }
408
409 // BeLax allows to compare different but convertible types. If set to
410 // false, got and expected types must be the same. If set to true and
411 // expected type is convertible to got one, expected is first
412 // converted to go type before its comparison. See [CmpLax] or
413 // [T.CmpLax] and [Lax] operator to set this flag without providing a
414 // specific configuration.
415 //
416 // It returns a new instance of [*T] so does not alter the original t.
417 //
418 // Note that t.BeLax() acts as t.BeLax(true).
419 //
420 // See also other configurators [T.Assert], [T.Require], [T.RootName],
421 // [T.FailureIsFatal], [T.UseEqual], [T.IgnoreUnexported] and
422 // [T.TestDeepInGotOK].
423 func (t *T) BeLax(enable ...bool) *T {
424 nt := *t
425 nt.Config.BeLax = len(enable) == 0 || enable[0]
426 return &nt
427 }
428
429 // IgnoreUnexported tells go-testdeep to ignore unexported fields of
430 // structs whose type is one of types.
431 //
432 // It always returns a new instance of [*T] so does not alter the original t.
433 //
434 // t = t.IgnoreUnexported(MyStruct1{}, MyStruct2{})
435 //
436 // types items can also be [reflect.Type] items. In this case, the
437 // target type is the one reflected by the [reflect.Type].
438 //
439 // t = t.IgnoreUnexported(reflect.TypeOf(MyStruct1{}))
440 //
441 // As a special case, calling t.IgnoreUnexported() or
442 // t.IgnoreUnexported(true) returns an instance ignoring unexported
443 // fields globally, for all struct types. t.IgnoreUnexported(false)
444 // returns an instance not ignoring unexported fields anymore, except
445 // for types already recorded using a previous IgnoreUnexported call.
446 //
447 // See also other configurators [T.Assert], [T.Require], [T.RootName],
448 // [T.FailureIsFatal], [T.UseEqual], [T.BeLax] and
449 // [T.TestDeepInGotOK].
450 func (t *T) IgnoreUnexported(types ...any) *T {
451 // special case: IgnoreUnexported()
452 if len(types) == 0 {
453 nt := *t
454 nt.Config.IgnoreUnexported = true
455 return &nt
456 }
457
458 // special cases: IgnoreUnexported(true) or IgnoreUnexported(false)
459 if len(types) == 1 {
460 if ignore, ok := types[0].(bool); ok {
461 nt := *t
462 nt.Config.IgnoreUnexported = ignore
463 return &nt
464 }
465 }
466
467 // Enable IgnoreUnexported only for types types
468 t = t.copyWithHooks()
469
470 err := t.Config.hooks.AddIgnoreUnexported(types)
471 if err != nil {
472 t.Helper()
473 t.Fatal(color.Bad("IgnoreUnexported " + err.Error()))
474 }
475
476 return t
477 }
478
479 // TestDeepInGotOK tells go-testdeep not to panic when a [TestDeep]
480 // operator is found on got side. By default it is forbidden because
481 // most of the time it is a mistake to compare (expected, got) instead
482 // of official (got, expected).
483 //
484 // It returns a new instance of [*T] so does not alter the original t.
485 //
486 // Note that t.TestDeepInGotOK() acts as t.TestDeepInGotOK(true).
487 //
488 // See also other configurators [T.Assert], [T.Require], [T.RootName],
489 // [T.FailureIsFatal], [T.UseEqual], [T.BeLax] and
490 // [T.IgnoreUnexported].
491 func (t *T) TestDeepInGotOK(enable ...bool) *T {
492 nt := *t
493 nt.Config.TestDeepInGotOK = len(enable) == 0 || enable[0]
494 return &nt
495 }
496
497 // Cmp is mostly a shortcut for:
498 //
499 // Cmp(t.TB, got, expected, args...)
500 //
501 // with the exception that t.Config is used to configure the test
502 // [ContextConfig].
503 //
504 // args... are optional and allow to name the test. This name is
505 // used in case of failure to qualify the test. If len(args) > 1 and
506 // the first item of args is a string and contains a '%' rune then
507 // [fmt.Fprintf] is used to compose the name, else args are passed to
508 // [fmt.Fprint]. Do not forget it is the name of the test, not the
509 // reason of a potential failure.
510 func (t *T) Cmp(got, expected any, args ...any) bool {
511 t.Helper()
512 defer t.resetNonPersistentAnchors()
513 return cmpDeeply(newContext(t), t.TB, got, expected, args...)
514 }
515
516 // CmpDeeply works the same as [Cmp] and is still available for
517 // compatibility purpose. Use shorter [Cmp] in new code.
518 func (t *T) CmpDeeply(got, expected any, args ...any) bool {
519 t.Helper()
520 defer t.resetNonPersistentAnchors()
521 return cmpDeeply(newContext(t), t.TB, got, expected, args...)
522 }
523
524 // True is shortcut for:
525 //
526 // t.Cmp(got, true, args...)
527 //
528 // Returns true if the test is OK, false if it fails.
529 //
530 // t.True(IsAvailable(x), "x should be available")
531 //
532 // args... are optional and allow to name the test. This name is
533 // used in case of failure to qualify the test. If len(args) > 1 and
534 // the first item of args is a string and contains a '%' rune then
535 // [fmt.Fprintf] is used to compose the name, else args are passed to
536 // [fmt.Fprint]. Do not forget it is the name of the test, not the
537 // reason of a potential failure.
538 //
539 // See also [T.False].
540 func (t *T) True(got any, args ...any) bool {
541 t.Helper()
542 return t.Cmp(got, true, args...)
543 }
544
545 // False is shortcut for:
546 //
547 // t.Cmp(got, false, args...)
548 //
549 // Returns true if the test is OK, false if it fails.
550 //
551 // t.False(IsAvailable(x), "x should not be available")
552 //
553 // args... are optional and allow to name the test. This name is
554 // used in case of failure to qualify the test. If len(args) > 1 and
555 // the first item of args is a string and contains a '%' rune then
556 // [fmt.Fprintf] is used to compose the name, else args are passed to
557 // [fmt.Fprint]. Do not forget it is the name of the test, not the
558 // reason of a potential failure.
559 //
560 // See also [T.True].
561 func (t *T) False(got any, args ...any) bool {
562 t.Helper()
563 return t.Cmp(got, false, args...)
564 }
565
566 // CmpError checks that got is non-nil error.
567 //
568 // _, err := MyFunction(1, 2, 3)
569 // t.CmpError(err, "MyFunction(1, 2, 3) should return an error")
570 //
571 // CmpError and not Error to avoid collision with t.TB.Error method.
572 //
573 // args... are optional and allow to name the test. This name is
574 // used in case of failure to qualify the test. If len(args) > 1 and
575 // the first item of args is a string and contains a '%' rune then
576 // [fmt.Fprintf] is used to compose the name, else args are passed to
577 // [fmt.Fprint]. Do not forget it is the name of the test, not the
578 // reason of a potential failure.
579 //
580 // See also [T.CmpNoError].
581 func (t *T) CmpError(got error, args ...any) bool {
582 t.Helper()
583 return cmpError(newContext(t), t.TB, got, args...)
584 }
585
586 // CmpNoError checks that got is nil error.
587 //
588 // value, err := MyFunction(1, 2, 3)
589 // if t.CmpNoError(err) {
590 // // one can now check value...
591 // }
592 //
593 // CmpNoError and not NoError to be consistent with [T.CmpError] method.
594 //
595 // args... are optional and allow to name the test. This name is
596 // used in case of failure to qualify the test. If len(args) > 1 and
597 // the first item of args is a string and contains a '%' rune then
598 // [fmt.Fprintf] is used to compose the name, else args are passed to
599 // [fmt.Fprint]. Do not forget it is the name of the test, not the
600 // reason of a potential failure.
601 //
602 // See also [T.CmpError].
603 func (t *T) CmpNoError(got error, args ...any) bool {
604 t.Helper()
605 return cmpNoError(newContext(t), t.TB, got, args...)
606 }
607
608 // CmpPanic calls fn and checks a panic() occurred with the
609 // expectedPanic parameter. It returns true only if both conditions
610 // are fulfilled.
611 //
612 // Note that calling panic(nil) in fn body is always detected as a
613 // panic. [runtime] package says: before Go 1.21, programs that called
614 // panic(nil) observed recover returning nil. Starting in Go 1.21,
615 // programs that call panic(nil) observe recover returning a
616 // [*runtime.PanicNilError]. Programs can change back to the old
617 // behavior by setting GODEBUG=panicnil=1.
618 //
619 // t.CmpPanic(func() { panic("I am panicking!") },
620 // "I am panicking!",
621 // "The function should panic with the right string")
622 //
623 // t.CmpPanic(func() { panic("I am panicking!") },
624 // Contains("panicking!"),
625 // "The function should panic with a string containing `panicking!`")
626 //
627 // expected := &runtime.PanicNilError{} // should be nil if GODEBUG=panicnil=1
628 // t.CmpPanic(t, func() { panic(nil) }, expected, "Checks for panic(nil)")
629 //
630 // args... are optional and allow to name the test. This name is
631 // used in case of failure to qualify the test. If len(args) > 1 and
632 // the first item of args is a string and contains a '%' rune then
633 // [fmt.Fprintf] is used to compose the name, else args are passed to
634 // [fmt.Fprint]. Do not forget it is the name of the test, not the
635 // reason of a potential failure.
636 //
637 // See also [T.CmpNotPanic].
638 func (t *T) CmpPanic(fn func(), expected any, args ...any) bool {
639 t.Helper()
640 defer t.resetNonPersistentAnchors()
641 return cmpPanic(newContext(t), t, fn, expected, args...)
642 }
643
644 // CmpNotPanic calls fn and checks no panic() occurred. If a panic()
645 // occurred false is returned then the panic() parameter and the stack
646 // trace appear in the test report.
647 //
648 // Note that calling panic(nil) in fn body is always detected as a
649 // panic. [runtime] package says: before Go 1.21, programs that called
650 // panic(nil) observed recover returning nil. Starting in Go 1.21,
651 // programs that call panic(nil) observe recover returning a
652 // [*runtime.PanicNilError]. Programs can change back to the old
653 // behavior by setting GODEBUG=panicnil=1.
654 //
655 // t.CmpNotPanic(func() {}) // succeeds as function does not panic
656 //
657 // t.CmpNotPanic(func() { panic("I am panicking!") }) // fails
658 // t.CmpNotPanic(func() { panic(nil) }) // fails too
659 //
660 // args... are optional and allow to name the test. This name is
661 // used in case of failure to qualify the test. If len(args) > 1 and
662 // the first item of args is a string and contains a '%' rune then
663 // [fmt.Fprintf] is used to compose the name, else args are passed to
664 // [fmt.Fprint]. Do not forget it is the name of the test, not the
665 // reason of a potential failure.
666 //
667 // See also [T.CmpPanic].
668 func (t *T) CmpNotPanic(fn func(), args ...any) bool {
669 t.Helper()
670 return cmpNotPanic(newContext(t), t, fn, args...)
671 }
672
673 // Parallel marks this test as runnable in parallel with other
674 // parallel tests. If t.TB implements Parallel(), as [*testing.T]
675 // does, it is usually used to mark top-level tests and/or subtests as
676 // safe for parallel execution:
677 //
678 // func TestCreateRecord(tt *testing.T) {
679 // t := td.NewT(tt)
680 // t.Parallel()
681 //
682 // t.Run("no error", func(t *td.T) {
683 // t.Parallel()
684 //
685 // // ...
686 // })
687 //
688 // If t.TB does not implement Parallel(), this method is a no-op.
689 func (t *T) Parallel() {
690 p, ok := t.TB.(interface{ Parallel() })
691 if ok {
692 p.Parallel()
693 }
694 }
695
696 type runtFuncs struct {
697 run reflect.Value
698 fnt reflect.Type
699 }
700
701 var (
702 runtMu sync.Mutex
703 runt = map[reflect.Type]runtFuncs{}
704 )
705
706 func (t *T) getRunFunc() (runtFuncs, bool) {
707 ttb := reflect.TypeOf(t.TB)
708
709 runtMu.Lock()
710 defer runtMu.Unlock()
711
712 vfuncs, ok := runt[ttb]
713 if !ok {
714 run, ok := ttb.MethodByName("Run")
715 if ok {
716 mt := run.Type
717 if mt.NumIn() == 3 && mt.NumOut() == 1 && !mt.IsVariadic() &&
718 mt.In(1) == types.String && mt.Out(0) == types.Bool {
719 fnt := mt.In(2)
720 if fnt.Kind() == reflect.Func &&
721 fnt.NumIn() == 1 && fnt.NumOut() == 0 &&
722 fnt.In(0) == mt.In(0) {
723 vfuncs = runtFuncs{
724 run: run.Func,
725 fnt: fnt,
726 }
727 runt[ttb] = vfuncs
728 ok = true
729 }
730 }
731 }
732 if !ok {
733 runt[ttb] = vfuncs
734 }
735 }
736
737 return vfuncs, vfuncs != (runtFuncs{})
738 }
739
740 // Run runs f as a subtest of t called name.
741 //
742 // If t.TB implement a method with the following signature:
743 //
744 // (X) Run(string, func(X)) bool
745 //
746 // it calls it with a function of its own in which it creates a new
747 // instance of [*T] on the fly before calling f with it.
748 //
749 // So if t.TB is a [*testing.T] or a [*testing.B] (which is in normal
750 // cases), let's quote the [testing.T.Run] & [testing.B.Run]
751 // documentation: f is called in a separate goroutine and blocks
752 // until f returns or calls t.Parallel to become a parallel
753 // test. Run reports whether f succeeded (or at least did not fail
754 // before calling t.Parallel). Run may be called simultaneously from
755 // multiple goroutines, but all such calls must return before the
756 // outer test function for t returns.
757 //
758 // If this Run() method is not found, it simply logs name then
759 // executes f using a new [*T] instance in the current goroutine. Note
760 // that it is only done for convenience.
761 //
762 // The t param of f inherits the configuration of the self-reference.
763 //
764 // See also [T.RunAssertRequire],
765 // [github.com/maxatome/go-testdeep/helpers/tdsynctest.Run] and
766 // [github.com/maxatome/go-testdeep/helpers/tdsynctest.RunAssertRequire].
767 func (t *T) Run(name string, f func(t *T)) bool {
768 t.Helper()
769
770 vfuncs, ok := t.getRunFunc()
771 if !ok {
772 t = NewT(t)
773 t.Logf("++++ %s", name)
774 f(t)
775 return !t.Failed()
776 }
777
778 conf := t.Config
779 ret := vfuncs.run.Call([]reflect.Value{
780 reflect.ValueOf(t.TB),
781 reflect.ValueOf(name),
782 reflect.MakeFunc(vfuncs.fnt,
783 func(args []reflect.Value) (results []reflect.Value) {
784 f(NewT(args[0].Interface().(testing.TB), conf))
785 return nil
786 }),
787 })
788
789 return ret[0].Bool()
790 }
791
792 // RunAssertRequire runs f as a subtest of t called name.
793 //
794 // If t.TB implement a method with the following signature:
795 //
796 // (X) Run(string, func(X)) bool
797 //
798 // it calls it with a function of its own in which it creates two new
799 // instances of [*T] using [AssertRequire] on the fly before calling f
800 // with them.
801 //
802 // So if t.TB is a [*testing.T] or a [*testing.B] (which is in normal
803 // cases), let's quote the [testing.T.Run] & [testing.B.Run]
804 // documentation: f is called in a separate goroutine and blocks
805 // until f returns or calls t.Parallel to become a parallel
806 // test. Run reports whether f succeeded (or at least did not fail
807 // before calling t.Parallel). Run may be called simultaneously from
808 // multiple goroutines, but all such calls must return before the
809 // outer test function for t returns.
810 //
811 // If this Run() method is not found, it simply logs name then
812 // executes f using two new instances of [*T] (built with
813 // [AssertRequire]) in the current goroutine. Note that it is only
814 // done for convenience.
815 //
816 // The assert and require params of f inherit the configuration
817 // of the self-reference, except that a failure is never fatal using
818 // assert and always fatal using require.
819 //
820 // See also [T.Run],
821 // [github.com/maxatome/go-testdeep/helpers/tdsynctest.RunAssertRequire]
822 // and [github.com/maxatome/go-testdeep/helpers/tdsynctest.Run].
823 func (t *T) RunAssertRequire(name string, f func(assert, require *T)) bool {
824 t.Helper()
825
826 vfuncs, ok := t.getRunFunc()
827 if !ok {
828 assert, require := AssertRequire(t)
829 t.Logf("++++ %s", name)
830 f(assert, require)
831 return !t.Failed()
832 }
833
834 conf := t.Config
835 ret := vfuncs.run.Call([]reflect.Value{
836 reflect.ValueOf(t.TB),
837 reflect.ValueOf(name),
838 reflect.MakeFunc(vfuncs.fnt,
839 func(args []reflect.Value) (results []reflect.Value) {
840 f(AssertRequire(args[0].Interface().(testing.TB), conf))
841 return nil
842 }),
843 })
844
845 return ret[0].Bool()
846 }
847
848 // RunT runs f as a subtest of t called name.
849 //
850 // Deprecated: RunT has been superseded by [T.Run] method. It is kept
851 // for compatibility.
852 func (t *T) RunT(name string, f func(t *T)) bool {
853 t.Helper()
854 return t.Run(name, f)
855 }
856
857 func getTrace(args ...any) string {
858 var b strings.Builder
859 tdutil.FbuildTestName(&b, args...)
860
861 if b.Len() == 0 {
862 b.WriteString("Stack trace:\n")
863 } else if !strings.HasSuffix(b.String(), "\n") {
864 b.WriteByte('\n')
865 }
866
867 s := stripTrace(trace.Retrieve(1, "testing.tRunner"))
868 if len(s) == 0 {
869 b.WriteString("\tEmpty stack trace")
870 return b.String()
871 }
872
873 s.Dump(&b)
874 return b.String()
875 }
876
877 // LogTrace uses t.TB.Log() to log a stack trace.
878 //
879 // args... are optional and allow to prefix the trace by a
880 // message. If empty, this message defaults to "Stack trace:\n". If
881 // this message does not end with a "\n", one is automatically
882 // added. If len(args) > 1 and the first item of args is a string
883 // and contains a '%' rune then [fmt.Fprintf] is used to compose the
884 // name, else args are passed to [fmt.Fprint].
885 //
886 // See also [T.ErrorTrace] and [T.FatalTrace].
887 func (t *T) LogTrace(args ...any) {
888 t.Helper()
889 t.Log(getTrace(args...))
890 }
891
892 // ErrorTrace uses t.TB.Error() to log a stack trace.
893 //
894 // args... are optional and allow to prefix the trace by a
895 // message. If empty, this message defaults to "Stack trace:\n". If
896 // this message does not end with a "\n", one is automatically
897 // added. If len(args) > 1 and the first item of args is a string
898 // and contains a '%' rune then [fmt.Fprintf] is used to compose the
899 // name, else args are passed to [fmt.Fprint].
900 //
901 // See also [T.LogTrace] and [T.FatalTrace].
902 func (t *T) ErrorTrace(args ...any) {
903 t.Helper()
904 t.Error(getTrace(args...))
905 }
906
907 // FatalTrace uses t.TB.Fatal() to log a stack trace.
908 //
909 // args... are optional and allow to prefix the trace by a
910 // message. If empty, this message defaults to "Stack trace:\n". If
911 // this message does not end with a "\n", one is automatically
912 // added. If len(args) > 1 and the first item of args is a string
913 // and contains a '%' rune then [fmt.Fprintf] is used to compose the
914 // name, else args are passed to [fmt.Fprint].
915 //
916 // See also [T.LogTrace] and [T.ErrorTrace].
917 func (t *T) FatalTrace(args ...any) {
918 t.Helper()
919 t.Fatal(getTrace(args...))
920 }