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.
pull/1423/head
Linus Barth 2023-10-16 02:59:15 +02:00 committed by Olivier Mengué
parent 351d2776c6
commit 737a765d89
1 changed files with 15 additions and 11 deletions

View File

@ -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()
})
}