diff --git a/suite/interfaces.go b/suite/interfaces.go index fed037d7f..9eef3eeba 100644 --- a/suite/interfaces.go +++ b/suite/interfaces.go @@ -59,6 +59,12 @@ type SetupSubTest interface { SetupSubTest() } +// OnlySubTest has a OnlySubTest method, which will run only the subtest +// with the given name in the suite. +type OnlySubTest interface { + OnlySubTest(name string) bool +} + // TearDownSubTest has a TearDownSubTest method, which will run after // each subtest in the suite have been run. type TearDownSubTest interface { diff --git a/suite/suite.go b/suite/suite.go index 32976ac9f..47dcfa46d 100644 --- a/suite/suite.go +++ b/suite/suite.go @@ -108,6 +108,12 @@ func (suite *Suite) Run(name string, subtest func()) bool { defer recoverAndFailOnPanic(t) + if onlySubTest, ok := suite.s.(OnlySubTest); ok { + if !onlySubTest.OnlySubTest(name) { + t.Skipf(`skipping subtest %q as OnlySubTest returned false`, name) + } + } + if setupSubTest, ok := suite.s.(SetupSubTest); ok { setupSubTest.SetupSubTest() } diff --git a/suite/suite_test.go b/suite/suite_test.go index 1c193aaf2..eadd6446a 100644 --- a/suite/suite_test.go +++ b/suite/suite_test.go @@ -813,3 +813,44 @@ func TestSuiteSignatureValidation(t *testing.T) { assert.True(t, suiteTester.setUp, "SetupSuite should have been executed") assert.True(t, suiteTester.toreDown, "TearDownSuite should have been executed") } + +// OnlySubTestSuite tests the OnlySubTest interface. +type OnlySubTestSuite struct { + Suite + executedSubTests []string +} + +func (s *OnlySubTestSuite) OnlySubTest(name string) bool { + return name == "allowed" +} + +func (s *OnlySubTestSuite) TestSubtests() { + for _, t := range []struct { + testName string + }{ + {"allowed"}, + {"not_allowed"}, + } { + s.Run(t.testName, func() { + s.executedSubTests = append(s.executedSubTests, t.testName) + }) + } +} + +// TestOnlySubTestSuite ensures that only the allowed subtest runs. +func TestOnlySubTestSuite(t *testing.T) { + suiteTester := new(OnlySubTestSuite) + + ok := testing.RunTests(allTestsFilter, []testing.InternalTest{ + { + Name: "only subtest", + F: func(t *testing.T) { + Run(t, suiteTester) + }, + }, + }) + + require.True(t, ok, "Suite should pass") + + assert.Equal(t, []string{"allowed"}, suiteTester.executedSubTests, "Only the allowed subtest should have been executed") +}