Skip to content

Commit 5dc2eed

Browse files
committed
Call cleanup functions if explicit teardown is needed
Not calling cleanup functions after a test fails may affect other tests down the row. This issue was introduced in 04f27d4. When a test fails, a `GetOutOf_testPartExecutor` exception is raised to make `unittest` halt `testPartExecutor`: https://github.com/pytest-dev/pytest/blob/413ca8a4d097ed1a98b2d1012ca7df17aa6837b1/src/_pytest/unittest.py#L206-L228 That prevents `teardown` **and** cleanup functions from being called. That's why `self._needs_explicit_tearDown` is set to `True` to then explicitly call `teardown` later on: https://github.com/pytest-dev/pytest/blob/413ca8a4d097ed1a98b2d1012ca7df17aa6837b1/src/_pytest/unittest.py#L122-L126 But no cleanup functions are called. Hence this PR.
1 parent eb00182 commit 5dc2eed

File tree

4 files changed

+21
-0
lines changed

4 files changed

+21
-0
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ Omar Kohl
211211
Omer Hadari
212212
Ondřej Súkup
213213
Oscar Benjamin
214+
Pablo Aguiar
214215
Patrick Hayes
215216
Pauli Virtanen
216217
Paweł Adamczak

changelog/6947.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Call cleanup functions on test failure.

src/_pytest/unittest.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ def setup(self):
122122
def teardown(self):
123123
if self._needs_explicit_tearDown:
124124
self._testcase.tearDown()
125+
self._testcase.doCleanups()
125126
self._testcase = None
126127
self._obj = None
127128

testing/test_unittest.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -876,6 +876,24 @@ def test_notTornDown():
876876
reprec.assertoutcome(passed=1, failed=1)
877877

878878

879+
def test_call_cleanup_functions_on_test_failure(testdir):
880+
testdir.makepyfile(
881+
"""
882+
import unittest
883+
class TC(unittest.TestCase):
884+
def setUp(self):
885+
self.addCleanup(lambda: print("someCleanup()"))
886+
def test_method(self):
887+
assert False
888+
"""
889+
)
890+
result = testdir.runpytest("-s")
891+
assert result.ret == 1
892+
result.stdout.fnmatch_lines(
893+
["*someCleanup()*", "*test_method*", "*assert False*", "*1 failed*"]
894+
)
895+
896+
879897
def test_issue333_result_clearing(testdir):
880898
testdir.makeconftest(
881899
"""

0 commit comments

Comments
 (0)