From 54654bcb0e1993818e97d3044db4298bf15652e3 Mon Sep 17 00:00:00 2001 From: Adam Luzsi Date: Tue, 15 Oct 2024 22:57:12 +0200 Subject: [PATCH] add syntax sugar for cleanup tasks related to test failures Conditional cleanups are particularly helpful for logging specific details only when a test fails, preventing unnecessary clutter in the output of passing tests. --- T.go | 8 ++++++++ T_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ examples_test.go | 14 ++++++++++++++ 3 files changed, 62 insertions(+) diff --git a/T.go b/T.go index 3aaea07..dd6f6cd 100644 --- a/T.go +++ b/T.go @@ -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() + } + }) +} diff --git a/T_test.go b/T_test.go index 1e85028..8821307 100644 --- a/T_test.go +++ b/T_test.go @@ -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() + }) +} diff --git a/examples_test.go b/examples_test.go index f265a57..0ed5ec3 100644 --- a/examples_test.go +++ b/examples_test.go @@ -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() + }) +}