Skip to content

Call cleanup functions if explicit teardown is needed #7049

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ Omar Kohl
Omer Hadari
Ondřej Súkup
Oscar Benjamin
Pablo Aguiar
Patrick Hayes
Pauli Virtanen
Paweł Adamczak
Expand Down
1 change: 1 addition & 0 deletions changelog/6947.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Call cleanup functions of `unittest.TestCase` subclasses on test failures.
1 change: 1 addition & 0 deletions src/_pytest/unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ def setup(self):
def teardown(self):
if self._needs_explicit_tearDown:
self._testcase.tearDown()
self._testcase.doCleanups()
self._testcase = None
self._obj = None

Expand Down
18 changes: 18 additions & 0 deletions testing/test_unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,24 @@ def test_notTornDown():
reprec.assertoutcome(passed=1, failed=1)


def test_call_cleanup_functions_on_test_failure(testdir):
testdir.makepyfile(
"""
import unittest
class TC(unittest.TestCase):
def setUp(self):
self.addCleanup(lambda: print("someCleanup()"))
def test_method(self):
assert False
"""
)
result = testdir.runpytest("-s")
assert result.ret == 1
result.stdout.fnmatch_lines(
["*someCleanup()*", "*test_method*", "*assert False*", "*1 failed*"]
)


def test_issue333_result_clearing(testdir):
testdir.makeconftest(
"""
Expand Down