From a3503e7ac8341f986450294f3a7e2d0cf3db07df 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 Not calling cleanup functions after a test fails may affect other tests down the row. This issue was introduced in 04f27d4eb469fb9c76fd2d100564a0f7d30028df. 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 commit. --- 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..b6b4c196588 --- /dev/null +++ b/changelog/6947.bugfix.rst @@ -0,0 +1 @@ +Call cleanup functions of `unittest.TestCase` subclasses on test failures. 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( """