From 737a765d894418ce651c394a418c0a056c8be459 Mon Sep 17 00:00:00 2001 From: Linus Barth Date: Mon, 16 Oct 2023 02:59:15 +0200 Subject: [PATCH] fix: SetupSubTest and TearDownSubTest execution order There were two problems with the order of execution in the Suite.Run() method: - One could not access the correct testing context ("s.T()") inside the SetupSubTest and TearDownSubTest methods. If the testing context was used for e.g. assertions of mocks in the TearDownSubTest, the results would not be "attached" to the correct test in the test output. - The behavior was different to the order of execution for "root" tests (see lines 167-201) regarding the SetupTest and TearDownTest methods. This could confuse users of the library. Also the logic to be deferred was joined together. This was fine beforehand because a panic in the TearDownSubTest would have had no influence on the "suite.SetT(oldT)". Now since a panic in the TearDownSubTest would lead to omitting the "suite.SetT(oldT)" this defer was split into two separate defers. --- suite/suite.go | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/suite/suite.go b/suite/suite.go index 8b4202d..54efd4c 100644 --- a/suite/suite.go +++ b/suite/suite.go @@ -96,19 +96,23 @@ func failOnPanic(t *testing.T, r interface{}) { func (suite *Suite) Run(name string, subtest func()) bool { oldT := suite.T() - if setupSubTest, ok := suite.s.(SetupSubTest); ok { - setupSubTest.SetupSubTest() - } - - defer func() { - suite.SetT(oldT) - if tearDownSubTest, ok := suite.s.(TearDownSubTest); ok { - tearDownSubTest.TearDownSubTest() - } - }() - return oldT.Run(name, func(t *testing.T) { suite.SetT(t) + + defer func() { + suite.SetT(oldT) + }() + + if setupSubTest, ok := suite.s.(SetupSubTest); ok { + setupSubTest.SetupSubTest() + } + + defer func() { + if tearDownSubTest, ok := suite.s.(TearDownSubTest); ok { + tearDownSubTest.TearDownSubTest() + } + }() + subtest() }) }