testifylint
testifylint copied to clipboard
Detect use of Assertions object with wrong testing.T
For years I've written tests like this:
func TestValueType(t *testing.T) {
t.Parallel()
a := assert.New(t)
for _, tc := range []struct {
test string
val any
exp bool
}{
{"nil", nil, false},
{"true", true, true},
{"false", false, false},
{"int", 42, true},
{"int_zero", 0, false},
} {
t.Run(tc.test, func(t *testing.T) {
t.Parallel()
val := Value(tc.val)
a.Equal(tc.val, val.Value())
a.Equal(tc.exp, val.Truthy())
})
}
}
It was only last week I realized that this breaks the display of test names in failure output, because it's using the a created in the parent function inside the Run function. The solution is to always create new assert.Assertions or require.Assertions objects inside each Run function. I've been busy fixing such cases like so:
@@ -2,7 +2,6 @@
func TestValueType(t *testing.T) {
t.Parallel()
- a := assert.New(t)
for _, tc := range []struct {
test string
@@ -17,6 +16,7 @@
} {
t.Run(tc.test, func(t *testing.T) {
t.Parallel()
+ a := assert.New(t)
val := Value(tc.val)
a.Equal(tc.val, val.Value())
It would be great if testifylint could catch this anti-pattern. Even better if it could fix it! Do-able? I'd be happy to help develop it, given some pointers for how to write analysis tools like this.
Somehow related to https://github.com/Antonboom/testifylint/issues/197