From 43e17de8392772e11a6e248651697be4aa541ea5 Mon Sep 17 00:00:00 2001 From: Pablo Santiago Blum de Aguiar Date: Wed, 8 Apr 2020 20:35:05 +0200 Subject: [PATCH] Call cleanup functions if explicit teardown is needed Fix #6947 --- AUTHORS | 1 + changelog/6947.bugfix.rst | 1 + src/_pytest/unittest.py | 1 + testing/test_unittest.py | 18 ++++++++++++++++++ 4 files changed, 21 insertions(+) create mode 100644 changelog/6947.bugfix.rst diff --git a/AUTHORS b/AUTHORS index 7c791cde8ca..2d9c11b63f7 100644 --- a/AUTHORS +++ b/AUTHORS @@ -211,6 +211,7 @@ Omar Kohl Omer Hadari Ondřej Súkup Oscar Benjamin +Pablo Aguiar Patrick Hayes Pauli Virtanen Paweł Adamczak diff --git a/changelog/6947.bugfix.rst b/changelog/6947.bugfix.rst new file mode 100644 index 00000000000..f0995f00877 --- /dev/null +++ b/changelog/6947.bugfix.rst @@ -0,0 +1 @@ +Call cleanup functions on test failure. diff --git a/src/_pytest/unittest.py b/src/_pytest/unittest.py index 2047876e5f1..a839b0b545c 100644 --- a/src/_pytest/unittest.py +++ b/src/_pytest/unittest.py @@ -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 diff --git a/testing/test_unittest.py b/testing/test_unittest.py index de51f7bd104..8255be22a24 100644 --- a/testing/test_unittest.py +++ b/testing/test_unittest.py @@ -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( """