Skip to content

Commit c210213

Browse files
gh-99645: Fix a bug in handling class cleanups in unittest.TestCase (GH-99646)
Now addClassCleanup() uses separate lists for different TestCase subclasses, and doClassCleanups() only cleans up the particular class.
1 parent d15b9f1 commit c210213

File tree

3 files changed

+35
-5
lines changed

3 files changed

+35
-5
lines changed

Lib/test/test_unittest/test_runner.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,33 @@ def testNothing(self):
547547

548548
self.assertEqual(TestableTest._class_cleanups, [])
549549

550+
def test_run_nested_test(self):
551+
ordering = []
552+
553+
class InnerTest(unittest.TestCase):
554+
@classmethod
555+
def setUpClass(cls):
556+
ordering.append('inner setup')
557+
cls.addClassCleanup(ordering.append, 'inner cleanup')
558+
def test(self):
559+
ordering.append('inner test')
560+
561+
class OuterTest(unittest.TestCase):
562+
@classmethod
563+
def setUpClass(cls):
564+
ordering.append('outer setup')
565+
cls.addClassCleanup(ordering.append, 'outer cleanup')
566+
def test(self):
567+
ordering.append('start outer test')
568+
runTests(InnerTest)
569+
ordering.append('end outer test')
570+
571+
runTests(OuterTest)
572+
self.assertEqual(ordering, [
573+
'outer setup', 'start outer test',
574+
'inner setup', 'inner test', 'inner cleanup',
575+
'end outer test', 'outer cleanup'])
576+
550577

551578
class TestModuleCleanUp(unittest.TestCase):
552579
def test_add_and_do_ModuleCleanup(self):

Lib/unittest/case.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -384,11 +384,11 @@ class TestCase(object):
384384
# of difflib. See #11763.
385385
_diffThreshold = 2**16
386386

387-
# Attribute used by TestSuite for classSetUp
388-
389-
_classSetupFailed = False
390-
391-
_class_cleanups = []
387+
def __init_subclass__(cls, *args, **kwargs):
388+
# Attribute used by TestSuite for classSetUp
389+
cls._classSetupFailed = False
390+
cls._class_cleanups = []
391+
super().__init_subclass__(*args, **kwargs)
392392

393393
def __init__(self, methodName='runTest'):
394394
"""Create an instance of the class that will use the named test
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a bug in handling class cleanups in :class:`unittest.TestCase`. Now
2+
``addClassCleanup()`` uses separate lists for different ``TestCase``
3+
subclasses, and ``doClassCleanups()`` only cleans up the particular class.

0 commit comments

Comments
 (0)