Skip to content

Commit

Permalink
add syntax sugar for cleanup tasks related to test failures
Browse files Browse the repository at this point in the history
Conditional cleanups are particularly helpful
for logging specific details only when a test fails,
preventing unnecessary clutter in the output of passing tests.
  • Loading branch information
adamluzsi committed Oct 15, 2024
1 parent 752ef40 commit 54654bc
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
8 changes: 8 additions & 0 deletions T.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,3 +296,11 @@ func (t *T) LogPretty(vs ...any) {
func (t *T) Done() <-chan struct{} {
return t.done
}

func (t *T) OnFail(fn func()) {
t.Defer(func() {
if t.Failed() {
fn()
}
})
}
40 changes: 40 additions & 0 deletions T_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -808,3 +808,43 @@ func TestT_Done(t *testing.T) {
assert.Equal(t, atomic.LoadInt32(&done), 1)
})
}

func TestT_OnFail(t *testing.T) {
t.Run("on success", func(t *testing.T) {
dtb := &doubles.TB{}
var done bool
s := testcase.NewSpec(dtb)
s.Test("", func(t *testcase.T) {
t.OnFail(func() { done = true })
})
s.Finish()
dtb.Finish()
assert.Equal(t, false, done)
})
t.Run("on failure", func(t *testing.T) {
dtb := &doubles.TB{}
var done bool
s := testcase.NewSpec(dtb)
s.Test("", func(t *testcase.T) {
t.OnFail(func() { done = true })
t.FailNow()
})
s.Finish()
dtb.Finish()
assert.Equal(t, true, done)
})
t.Run("race", func(t *testing.T) {
dtb := &doubles.TB{}
s := testcase.NewSpec(dtb)
s.Test("", func(t *testcase.T) {
testcase.Race(func() {
t.OnFail(func() {})
}, func() {
t.OnFail(func() {})
})
t.FailNow()
})
s.Finish()
dtb.Finish()
})
}
14 changes: 14 additions & 0 deletions examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1576,3 +1576,17 @@ func ExampleSpec_Spec() {
sharedSuite.AsSuite("x").Benchmark(b)
}
}

func ExampleT_OnFail() {
s := testcase.NewSpec(nil)

s.Before(func(t *testcase.T) {
t.OnFail(func() {
// executes only when a test fails.
})
})

s.Test("", func(t *testcase.T) {
t.FailNow()
})
}

0 comments on commit 54654bc

Please sign in to comment.