/
t.go
87 lines (74 loc) · 2.1 KB
/
t.go
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
// Copyright (c) 2019, 2020, Maxime Soulé
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
// Package tdutil allows to write unit tests for go-testdeep helpers
// and so provides some helpful functions.
//
// It is not intended to be used in tests outside go-testdeep and its
// helpers perimeter.
package tdutil
import (
"reflect"
"testing"
)
// T can be used in tests, to test [testing.T] behavior as it overrides
// [testing.T.Run] method.
type T struct {
testing.T
name string
}
type tFailedNow struct{}
// NewT returns a new [*T] instance. name is the string returned by
// method Name.
func NewT(name string) *T {
return &T{name: name}
}
// Run is a simplified version of [testing.T.Run] method, without edge
// cases.
func (t *T) Run(name string, f func(*testing.T)) bool {
t.CatchFailNow(func() { f(&t.T) })
return !t.Failed()
}
// Name returns the name of the running test (in fact the one set by [NewT]).
func (t *T) Name() string {
return t.name
}
// LogBuf is an ugly hack allowing to access internal [testing.T] log
// buffer. Keep cool, it is only used for internal unit tests.
func (t *T) LogBuf() string {
return string(reflect.ValueOf(t.T).FieldByName("output").Bytes()) //nolint: govet
}
// FailNow simulates the original [testing.T.FailNow] using
// panic. [T.CatchFailNow] should be used to properly intercept it.
func (t *T) FailNow() {
t.Fail()
panic(tFailedNow{})
}
// Fatal simulates the original [testing.T.Fatal].
func (t *T) Fatal(args ...any) {
t.Helper()
t.Error(args...)
t.FailNow()
}
// Fatal simulates the original [testing.T.Fatalf].
func (t *T) Fatalf(format string, args ...any) {
t.Helper()
t.Errorf(format, args...)
t.FailNow()
}
// CatchFailNow returns true if a [T.FailNow], [T.Fatal] or [T.Fatalf] call
// occurred during the execution of fn.
func (t *T) CatchFailNow(fn func()) (failNowOccurred bool) {
defer func() {
if x := recover(); x != nil {
_, failNowOccurred = x.(tFailedNow)
if !failNowOccurred {
panic(x) // rethrow
}
}
}()
fn()
return
}