Skip to content

Commit 69b91f4

Browse files
committed
unittest runner: Exit code 5 if no tests were run
As discussed in https://discuss.python.org/t/unittest-fail-if-zero-tests-were-discovered/21498/7 It is common for test runner misconfiguration to fail to find any tests, this should be an error. Fixes: python#62432
1 parent ebba337 commit 69b91f4

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

Lib/test/test_unittest/test_program.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,9 @@ def testExpectedFailure(self):
7171
def testUnexpectedSuccess(self):
7272
pass
7373

74+
class Empty(unittest.TestCase):
75+
pass
76+
7477
class TestLoader(unittest.TestLoader):
7578
"""Test loader that returns a suite containing testsuite."""
7679

@@ -134,12 +137,13 @@ def test_NonExit(self):
134137

135138
def test_Exit(self):
136139
stream = BufferedWriter()
137-
with self.assertRaises(SystemExit):
140+
with self.assertRaises(SystemExit) as cm:
138141
unittest.main(
139142
argv=["foobar"],
140143
testRunner=unittest.TextTestRunner(stream=stream),
141144
exit=True,
142145
testLoader=self.TestLoader(self.FooBar))
146+
self.assertEqual(cm.exception.code, 1)
143147
out = stream.getvalue()
144148
self.assertIn('\nFAIL: testFail ', out)
145149
self.assertIn('\nERROR: testError ', out)
@@ -163,6 +167,17 @@ def test_ExitAsDefault(self):
163167
'expected failures=1, unexpected successes=1)\n')
164168
self.assertTrue(out.endswith(expected))
165169

170+
def test_ExitEmptySuite(self):
171+
stream = BufferedWriter()
172+
with self.assertRaises(SystemExit) as cm:
173+
unittest.main(
174+
argv=["empty"],
175+
testRunner=unittest.TextTestRunner(stream=stream),
176+
testLoader=self.TestLoader(self.Empty))
177+
self.assertEqual(cm.exception.code, 5)
178+
out = stream.getvalue()
179+
self.assertIn('\nNO TESTS RUN\n', out)
180+
166181

167182
class InitialisableProgram(unittest.TestProgram):
168183
exit = False

Lib/unittest/main.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,11 @@ def runTests(self):
273273
testRunner = self.testRunner
274274
self.result = testRunner.run(self.test)
275275
if self.exit:
276-
sys.exit(not self.result.wasSuccessful())
276+
if self.result.testsRun == 0:
277+
sys.exit(5)
278+
elif not self.result.wasSuccessful():
279+
sys.exit(1)
280+
else:
281+
sys.exit(0)
277282

278283
main = TestProgram
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
The :mod:`unittest` runner will now exit with status code 5, if no tests
2+
were run. It is common for test runner misconfiguration to fail to find any
3+
tests, this should be an error.

0 commit comments

Comments
 (0)