bpo-24412: Adds cleanUps for setUpClass and setUpModule. (GH-9190)

This commit is contained in:
Lisa Roach 2018-11-08 18:34:33 -08:00 committed by GitHub
parent 49fa4a9f1e
commit 0f221d09ca
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 783 additions and 18 deletions

View file

@ -84,6 +84,30 @@ class _Outcome(object):
def _id(obj):
return obj
_module_cleanups = []
def addModuleCleanup(function, *args, **kwargs):
"""Same as addCleanup, except the cleanup items are called even if
setUpModule fails (unlike tearDownModule)."""
_module_cleanups.append((function, args, kwargs))
def doModuleCleanups():
"""Execute all module cleanup functions. Normally called for you after
tearDownModule."""
exceptions = []
while _module_cleanups:
function, args, kwargs = _module_cleanups.pop()
try:
function(*args, **kwargs)
except Exception as exc:
exceptions.append(exc)
if exceptions:
# Swallows all but first exception. If a multi-exception handler
# gets written we should use that here instead.
raise exceptions[0]
def skip(reason):
"""
Unconditionally skip a test.
@ -390,6 +414,8 @@ class TestCase(object):
_classSetupFailed = False
_class_cleanups = []
def __init__(self, methodName='runTest'):
"""Create an instance of the class that will use the named test
method when executed. Raises a ValueError if the instance does
@ -445,6 +471,12 @@ class TestCase(object):
Cleanup items are called even if setUp fails (unlike tearDown)."""
self._cleanups.append((function, args, kwargs))
@classmethod
def addClassCleanup(cls, function, *args, **kwargs):
"""Same as addCleanup, except the cleanup items are called even if
setUpClass fails (unlike tearDownClass)."""
cls._class_cleanups.append((function, args, kwargs))
def setUp(self):
"Hook method for setting up the test fixture before exercising it."
pass
@ -651,9 +683,21 @@ class TestCase(object):
function(*args, **kwargs)
# return this for backwards compatibility
# even though we no longer us it internally
# even though we no longer use it internally
return outcome.success
@classmethod
def doClassCleanups(cls):
"""Execute all class cleanup functions. Normally called for you after
tearDownClass."""
cls.tearDown_exceptions = []
while cls._class_cleanups:
function, args, kwargs = cls._class_cleanups.pop()
try:
function(*args, **kwargs)
except Exception as exc:
cls.tearDown_exceptions.append(sys.exc_info())
def __call__(self, *args, **kwds):
return self.run(*args, **kwds)