Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/smanonr..../lib64/python3..../unittest
File: case.py
"""Test case implementation"""
[0] Fix | Delete
[1] Fix | Delete
import sys
[2] Fix | Delete
import functools
[3] Fix | Delete
import difflib
[4] Fix | Delete
import logging
[5] Fix | Delete
import pprint
[6] Fix | Delete
import re
[7] Fix | Delete
import warnings
[8] Fix | Delete
import collections
[9] Fix | Delete
import contextlib
[10] Fix | Delete
import traceback
[11] Fix | Delete
import types
[12] Fix | Delete
[13] Fix | Delete
from . import result
[14] Fix | Delete
from .util import (strclass, safe_repr, _count_diff_all_purpose,
[15] Fix | Delete
_count_diff_hashable, _common_shorten_repr)
[16] Fix | Delete
[17] Fix | Delete
__unittest = True
[18] Fix | Delete
[19] Fix | Delete
_subtest_msg_sentinel = object()
[20] Fix | Delete
[21] Fix | Delete
DIFF_OMITTED = ('\nDiff is %s characters long. '
[22] Fix | Delete
'Set self.maxDiff to None to see it.')
[23] Fix | Delete
[24] Fix | Delete
class SkipTest(Exception):
[25] Fix | Delete
"""
[26] Fix | Delete
Raise this exception in a test to skip it.
[27] Fix | Delete
[28] Fix | Delete
Usually you can use TestCase.skipTest() or one of the skipping decorators
[29] Fix | Delete
instead of raising this directly.
[30] Fix | Delete
"""
[31] Fix | Delete
[32] Fix | Delete
class _ShouldStop(Exception):
[33] Fix | Delete
"""
[34] Fix | Delete
The test should stop.
[35] Fix | Delete
"""
[36] Fix | Delete
[37] Fix | Delete
class _UnexpectedSuccess(Exception):
[38] Fix | Delete
"""
[39] Fix | Delete
The test was supposed to fail, but it didn't!
[40] Fix | Delete
"""
[41] Fix | Delete
[42] Fix | Delete
[43] Fix | Delete
class _Outcome(object):
[44] Fix | Delete
def __init__(self, result=None):
[45] Fix | Delete
self.expecting_failure = False
[46] Fix | Delete
self.result = result
[47] Fix | Delete
self.result_supports_subtests = hasattr(result, "addSubTest")
[48] Fix | Delete
self.success = True
[49] Fix | Delete
self.skipped = []
[50] Fix | Delete
self.expectedFailure = None
[51] Fix | Delete
self.errors = []
[52] Fix | Delete
[53] Fix | Delete
@contextlib.contextmanager
[54] Fix | Delete
def testPartExecutor(self, test_case, isTest=False):
[55] Fix | Delete
old_success = self.success
[56] Fix | Delete
self.success = True
[57] Fix | Delete
try:
[58] Fix | Delete
yield
[59] Fix | Delete
except KeyboardInterrupt:
[60] Fix | Delete
raise
[61] Fix | Delete
except SkipTest as e:
[62] Fix | Delete
self.success = False
[63] Fix | Delete
self.skipped.append((test_case, str(e)))
[64] Fix | Delete
except _ShouldStop:
[65] Fix | Delete
pass
[66] Fix | Delete
except:
[67] Fix | Delete
exc_info = sys.exc_info()
[68] Fix | Delete
if self.expecting_failure:
[69] Fix | Delete
self.expectedFailure = exc_info
[70] Fix | Delete
else:
[71] Fix | Delete
self.success = False
[72] Fix | Delete
self.errors.append((test_case, exc_info))
[73] Fix | Delete
# explicitly break a reference cycle:
[74] Fix | Delete
# exc_info -> frame -> exc_info
[75] Fix | Delete
exc_info = None
[76] Fix | Delete
else:
[77] Fix | Delete
if self.result_supports_subtests and self.success:
[78] Fix | Delete
self.errors.append((test_case, None))
[79] Fix | Delete
finally:
[80] Fix | Delete
self.success = self.success and old_success
[81] Fix | Delete
[82] Fix | Delete
[83] Fix | Delete
def _id(obj):
[84] Fix | Delete
return obj
[85] Fix | Delete
[86] Fix | Delete
[87] Fix | Delete
_module_cleanups = []
[88] Fix | Delete
def addModuleCleanup(function, /, *args, **kwargs):
[89] Fix | Delete
"""Same as addCleanup, except the cleanup items are called even if
[90] Fix | Delete
setUpModule fails (unlike tearDownModule)."""
[91] Fix | Delete
_module_cleanups.append((function, args, kwargs))
[92] Fix | Delete
[93] Fix | Delete
[94] Fix | Delete
def doModuleCleanups():
[95] Fix | Delete
"""Execute all module cleanup functions. Normally called for you after
[96] Fix | Delete
tearDownModule."""
[97] Fix | Delete
exceptions = []
[98] Fix | Delete
while _module_cleanups:
[99] Fix | Delete
function, args, kwargs = _module_cleanups.pop()
[100] Fix | Delete
try:
[101] Fix | Delete
function(*args, **kwargs)
[102] Fix | Delete
except Exception as exc:
[103] Fix | Delete
exceptions.append(exc)
[104] Fix | Delete
if exceptions:
[105] Fix | Delete
# Swallows all but first exception. If a multi-exception handler
[106] Fix | Delete
# gets written we should use that here instead.
[107] Fix | Delete
raise exceptions[0]
[108] Fix | Delete
[109] Fix | Delete
[110] Fix | Delete
def skip(reason):
[111] Fix | Delete
"""
[112] Fix | Delete
Unconditionally skip a test.
[113] Fix | Delete
"""
[114] Fix | Delete
def decorator(test_item):
[115] Fix | Delete
if not isinstance(test_item, type):
[116] Fix | Delete
@functools.wraps(test_item)
[117] Fix | Delete
def skip_wrapper(*args, **kwargs):
[118] Fix | Delete
raise SkipTest(reason)
[119] Fix | Delete
test_item = skip_wrapper
[120] Fix | Delete
[121] Fix | Delete
test_item.__unittest_skip__ = True
[122] Fix | Delete
test_item.__unittest_skip_why__ = reason
[123] Fix | Delete
return test_item
[124] Fix | Delete
if isinstance(reason, types.FunctionType):
[125] Fix | Delete
test_item = reason
[126] Fix | Delete
reason = ''
[127] Fix | Delete
return decorator(test_item)
[128] Fix | Delete
return decorator
[129] Fix | Delete
[130] Fix | Delete
def skipIf(condition, reason):
[131] Fix | Delete
"""
[132] Fix | Delete
Skip a test if the condition is true.
[133] Fix | Delete
"""
[134] Fix | Delete
if condition:
[135] Fix | Delete
return skip(reason)
[136] Fix | Delete
return _id
[137] Fix | Delete
[138] Fix | Delete
def skipUnless(condition, reason):
[139] Fix | Delete
"""
[140] Fix | Delete
Skip a test unless the condition is true.
[141] Fix | Delete
"""
[142] Fix | Delete
if not condition:
[143] Fix | Delete
return skip(reason)
[144] Fix | Delete
return _id
[145] Fix | Delete
[146] Fix | Delete
def expectedFailure(test_item):
[147] Fix | Delete
test_item.__unittest_expecting_failure__ = True
[148] Fix | Delete
return test_item
[149] Fix | Delete
[150] Fix | Delete
def _is_subtype(expected, basetype):
[151] Fix | Delete
if isinstance(expected, tuple):
[152] Fix | Delete
return all(_is_subtype(e, basetype) for e in expected)
[153] Fix | Delete
return isinstance(expected, type) and issubclass(expected, basetype)
[154] Fix | Delete
[155] Fix | Delete
class _BaseTestCaseContext:
[156] Fix | Delete
[157] Fix | Delete
def __init__(self, test_case):
[158] Fix | Delete
self.test_case = test_case
[159] Fix | Delete
[160] Fix | Delete
def _raiseFailure(self, standardMsg):
[161] Fix | Delete
msg = self.test_case._formatMessage(self.msg, standardMsg)
[162] Fix | Delete
raise self.test_case.failureException(msg)
[163] Fix | Delete
[164] Fix | Delete
class _AssertRaisesBaseContext(_BaseTestCaseContext):
[165] Fix | Delete
[166] Fix | Delete
def __init__(self, expected, test_case, expected_regex=None):
[167] Fix | Delete
_BaseTestCaseContext.__init__(self, test_case)
[168] Fix | Delete
self.expected = expected
[169] Fix | Delete
self.test_case = test_case
[170] Fix | Delete
if expected_regex is not None:
[171] Fix | Delete
expected_regex = re.compile(expected_regex)
[172] Fix | Delete
self.expected_regex = expected_regex
[173] Fix | Delete
self.obj_name = None
[174] Fix | Delete
self.msg = None
[175] Fix | Delete
[176] Fix | Delete
def handle(self, name, args, kwargs):
[177] Fix | Delete
"""
[178] Fix | Delete
If args is empty, assertRaises/Warns is being used as a
[179] Fix | Delete
context manager, so check for a 'msg' kwarg and return self.
[180] Fix | Delete
If args is not empty, call a callable passing positional and keyword
[181] Fix | Delete
arguments.
[182] Fix | Delete
"""
[183] Fix | Delete
try:
[184] Fix | Delete
if not _is_subtype(self.expected, self._base_type):
[185] Fix | Delete
raise TypeError('%s() arg 1 must be %s' %
[186] Fix | Delete
(name, self._base_type_str))
[187] Fix | Delete
if not args:
[188] Fix | Delete
self.msg = kwargs.pop('msg', None)
[189] Fix | Delete
if kwargs:
[190] Fix | Delete
raise TypeError('%r is an invalid keyword argument for '
[191] Fix | Delete
'this function' % (next(iter(kwargs)),))
[192] Fix | Delete
return self
[193] Fix | Delete
[194] Fix | Delete
callable_obj, *args = args
[195] Fix | Delete
try:
[196] Fix | Delete
self.obj_name = callable_obj.__name__
[197] Fix | Delete
except AttributeError:
[198] Fix | Delete
self.obj_name = str(callable_obj)
[199] Fix | Delete
with self:
[200] Fix | Delete
callable_obj(*args, **kwargs)
[201] Fix | Delete
finally:
[202] Fix | Delete
# bpo-23890: manually break a reference cycle
[203] Fix | Delete
self = None
[204] Fix | Delete
[205] Fix | Delete
[206] Fix | Delete
class _AssertRaisesContext(_AssertRaisesBaseContext):
[207] Fix | Delete
"""A context manager used to implement TestCase.assertRaises* methods."""
[208] Fix | Delete
[209] Fix | Delete
_base_type = BaseException
[210] Fix | Delete
_base_type_str = 'an exception type or tuple of exception types'
[211] Fix | Delete
[212] Fix | Delete
def __enter__(self):
[213] Fix | Delete
return self
[214] Fix | Delete
[215] Fix | Delete
def __exit__(self, exc_type, exc_value, tb):
[216] Fix | Delete
if exc_type is None:
[217] Fix | Delete
try:
[218] Fix | Delete
exc_name = self.expected.__name__
[219] Fix | Delete
except AttributeError:
[220] Fix | Delete
exc_name = str(self.expected)
[221] Fix | Delete
if self.obj_name:
[222] Fix | Delete
self._raiseFailure("{} not raised by {}".format(exc_name,
[223] Fix | Delete
self.obj_name))
[224] Fix | Delete
else:
[225] Fix | Delete
self._raiseFailure("{} not raised".format(exc_name))
[226] Fix | Delete
else:
[227] Fix | Delete
traceback.clear_frames(tb)
[228] Fix | Delete
if not issubclass(exc_type, self.expected):
[229] Fix | Delete
# let unexpected exceptions pass through
[230] Fix | Delete
return False
[231] Fix | Delete
# store exception, without traceback, for later retrieval
[232] Fix | Delete
self.exception = exc_value.with_traceback(None)
[233] Fix | Delete
if self.expected_regex is None:
[234] Fix | Delete
return True
[235] Fix | Delete
[236] Fix | Delete
expected_regex = self.expected_regex
[237] Fix | Delete
if not expected_regex.search(str(exc_value)):
[238] Fix | Delete
self._raiseFailure('"{}" does not match "{}"'.format(
[239] Fix | Delete
expected_regex.pattern, str(exc_value)))
[240] Fix | Delete
return True
[241] Fix | Delete
[242] Fix | Delete
[243] Fix | Delete
class _AssertWarnsContext(_AssertRaisesBaseContext):
[244] Fix | Delete
"""A context manager used to implement TestCase.assertWarns* methods."""
[245] Fix | Delete
[246] Fix | Delete
_base_type = Warning
[247] Fix | Delete
_base_type_str = 'a warning type or tuple of warning types'
[248] Fix | Delete
[249] Fix | Delete
def __enter__(self):
[250] Fix | Delete
# The __warningregistry__'s need to be in a pristine state for tests
[251] Fix | Delete
# to work properly.
[252] Fix | Delete
for v in list(sys.modules.values()):
[253] Fix | Delete
if getattr(v, '__warningregistry__', None):
[254] Fix | Delete
v.__warningregistry__ = {}
[255] Fix | Delete
self.warnings_manager = warnings.catch_warnings(record=True)
[256] Fix | Delete
self.warnings = self.warnings_manager.__enter__()
[257] Fix | Delete
warnings.simplefilter("always", self.expected)
[258] Fix | Delete
return self
[259] Fix | Delete
[260] Fix | Delete
def __exit__(self, exc_type, exc_value, tb):
[261] Fix | Delete
self.warnings_manager.__exit__(exc_type, exc_value, tb)
[262] Fix | Delete
if exc_type is not None:
[263] Fix | Delete
# let unexpected exceptions pass through
[264] Fix | Delete
return
[265] Fix | Delete
try:
[266] Fix | Delete
exc_name = self.expected.__name__
[267] Fix | Delete
except AttributeError:
[268] Fix | Delete
exc_name = str(self.expected)
[269] Fix | Delete
first_matching = None
[270] Fix | Delete
for m in self.warnings:
[271] Fix | Delete
w = m.message
[272] Fix | Delete
if not isinstance(w, self.expected):
[273] Fix | Delete
continue
[274] Fix | Delete
if first_matching is None:
[275] Fix | Delete
first_matching = w
[276] Fix | Delete
if (self.expected_regex is not None and
[277] Fix | Delete
not self.expected_regex.search(str(w))):
[278] Fix | Delete
continue
[279] Fix | Delete
# store warning for later retrieval
[280] Fix | Delete
self.warning = w
[281] Fix | Delete
self.filename = m.filename
[282] Fix | Delete
self.lineno = m.lineno
[283] Fix | Delete
return
[284] Fix | Delete
# Now we simply try to choose a helpful failure message
[285] Fix | Delete
if first_matching is not None:
[286] Fix | Delete
self._raiseFailure('"{}" does not match "{}"'.format(
[287] Fix | Delete
self.expected_regex.pattern, str(first_matching)))
[288] Fix | Delete
if self.obj_name:
[289] Fix | Delete
self._raiseFailure("{} not triggered by {}".format(exc_name,
[290] Fix | Delete
self.obj_name))
[291] Fix | Delete
else:
[292] Fix | Delete
self._raiseFailure("{} not triggered".format(exc_name))
[293] Fix | Delete
[294] Fix | Delete
[295] Fix | Delete
[296] Fix | Delete
_LoggingWatcher = collections.namedtuple("_LoggingWatcher",
[297] Fix | Delete
["records", "output"])
[298] Fix | Delete
[299] Fix | Delete
[300] Fix | Delete
class _CapturingHandler(logging.Handler):
[301] Fix | Delete
"""
[302] Fix | Delete
A logging handler capturing all (raw and formatted) logging output.
[303] Fix | Delete
"""
[304] Fix | Delete
[305] Fix | Delete
def __init__(self):
[306] Fix | Delete
logging.Handler.__init__(self)
[307] Fix | Delete
self.watcher = _LoggingWatcher([], [])
[308] Fix | Delete
[309] Fix | Delete
def flush(self):
[310] Fix | Delete
pass
[311] Fix | Delete
[312] Fix | Delete
def emit(self, record):
[313] Fix | Delete
self.watcher.records.append(record)
[314] Fix | Delete
msg = self.format(record)
[315] Fix | Delete
self.watcher.output.append(msg)
[316] Fix | Delete
[317] Fix | Delete
[318] Fix | Delete
[319] Fix | Delete
class _AssertLogsContext(_BaseTestCaseContext):
[320] Fix | Delete
"""A context manager used to implement TestCase.assertLogs()."""
[321] Fix | Delete
[322] Fix | Delete
LOGGING_FORMAT = "%(levelname)s:%(name)s:%(message)s"
[323] Fix | Delete
[324] Fix | Delete
def __init__(self, test_case, logger_name, level):
[325] Fix | Delete
_BaseTestCaseContext.__init__(self, test_case)
[326] Fix | Delete
self.logger_name = logger_name
[327] Fix | Delete
if level:
[328] Fix | Delete
self.level = logging._nameToLevel.get(level, level)
[329] Fix | Delete
else:
[330] Fix | Delete
self.level = logging.INFO
[331] Fix | Delete
self.msg = None
[332] Fix | Delete
[333] Fix | Delete
def __enter__(self):
[334] Fix | Delete
if isinstance(self.logger_name, logging.Logger):
[335] Fix | Delete
logger = self.logger = self.logger_name
[336] Fix | Delete
else:
[337] Fix | Delete
logger = self.logger = logging.getLogger(self.logger_name)
[338] Fix | Delete
formatter = logging.Formatter(self.LOGGING_FORMAT)
[339] Fix | Delete
handler = _CapturingHandler()
[340] Fix | Delete
handler.setFormatter(formatter)
[341] Fix | Delete
self.watcher = handler.watcher
[342] Fix | Delete
self.old_handlers = logger.handlers[:]
[343] Fix | Delete
self.old_level = logger.level
[344] Fix | Delete
self.old_propagate = logger.propagate
[345] Fix | Delete
logger.handlers = [handler]
[346] Fix | Delete
logger.setLevel(self.level)
[347] Fix | Delete
logger.propagate = False
[348] Fix | Delete
return handler.watcher
[349] Fix | Delete
[350] Fix | Delete
def __exit__(self, exc_type, exc_value, tb):
[351] Fix | Delete
self.logger.handlers = self.old_handlers
[352] Fix | Delete
self.logger.propagate = self.old_propagate
[353] Fix | Delete
self.logger.setLevel(self.old_level)
[354] Fix | Delete
if exc_type is not None:
[355] Fix | Delete
# let unexpected exceptions pass through
[356] Fix | Delete
return False
[357] Fix | Delete
if len(self.watcher.records) == 0:
[358] Fix | Delete
self._raiseFailure(
[359] Fix | Delete
"no logs of level {} or higher triggered on {}"
[360] Fix | Delete
.format(logging.getLevelName(self.level), self.logger.name))
[361] Fix | Delete
[362] Fix | Delete
[363] Fix | Delete
class _OrderedChainMap(collections.ChainMap):
[364] Fix | Delete
def __iter__(self):
[365] Fix | Delete
seen = set()
[366] Fix | Delete
for mapping in self.maps:
[367] Fix | Delete
for k in mapping:
[368] Fix | Delete
if k not in seen:
[369] Fix | Delete
seen.add(k)
[370] Fix | Delete
yield k
[371] Fix | Delete
[372] Fix | Delete
[373] Fix | Delete
class TestCase(object):
[374] Fix | Delete
"""A class whose instances are single test cases.
[375] Fix | Delete
[376] Fix | Delete
By default, the test code itself should be placed in a method named
[377] Fix | Delete
'runTest'.
[378] Fix | Delete
[379] Fix | Delete
If the fixture may be used for many test cases, create as
[380] Fix | Delete
many test methods as are needed. When instantiating such a TestCase
[381] Fix | Delete
subclass, specify in the constructor arguments the name of the test method
[382] Fix | Delete
that the instance is to execute.
[383] Fix | Delete
[384] Fix | Delete
Test authors should subclass TestCase for their own tests. Construction
[385] Fix | Delete
and deconstruction of the test's environment ('fixture') can be
[386] Fix | Delete
implemented by overriding the 'setUp' and 'tearDown' methods respectively.
[387] Fix | Delete
[388] Fix | Delete
If it is necessary to override the __init__ method, the base class
[389] Fix | Delete
__init__ method must always be called. It is important that subclasses
[390] Fix | Delete
should not change the signature of their __init__ method, since instances
[391] Fix | Delete
of the classes are instantiated automatically by parts of the framework
[392] Fix | Delete
in order to be run.
[393] Fix | Delete
[394] Fix | Delete
When subclassing TestCase, you can set these attributes:
[395] Fix | Delete
* failureException: determines which exception will be raised when
[396] Fix | Delete
the instance's assertion methods fail; test methods raising this
[397] Fix | Delete
exception will be deemed to have 'failed' rather than 'errored'.
[398] Fix | Delete
* longMessage: determines whether long messages (including repr of
[399] Fix | Delete
objects used in assert methods) will be printed on failure in *addition*
[400] Fix | Delete
to any explicit message passed.
[401] Fix | Delete
* maxDiff: sets the maximum length of a diff in failure messages
[402] Fix | Delete
by assert methods using difflib. It is looked up as an instance
[403] Fix | Delete
attribute so can be configured by individual tests if required.
[404] Fix | Delete
"""
[405] Fix | Delete
[406] Fix | Delete
failureException = AssertionError
[407] Fix | Delete
[408] Fix | Delete
longMessage = True
[409] Fix | Delete
[410] Fix | Delete
maxDiff = 80*8
[411] Fix | Delete
[412] Fix | Delete
# If a string is longer than _diffThreshold, use normal comparison instead
[413] Fix | Delete
# of difflib. See #11763.
[414] Fix | Delete
_diffThreshold = 2**16
[415] Fix | Delete
[416] Fix | Delete
# Attribute used by TestSuite for classSetUp
[417] Fix | Delete
[418] Fix | Delete
_classSetupFailed = False
[419] Fix | Delete
[420] Fix | Delete
_class_cleanups = []
[421] Fix | Delete
[422] Fix | Delete
def __init__(self, methodName='runTest'):
[423] Fix | Delete
"""Create an instance of the class that will use the named test
[424] Fix | Delete
method when executed. Raises a ValueError if the instance does
[425] Fix | Delete
not have a method with the specified name.
[426] Fix | Delete
"""
[427] Fix | Delete
self._testMethodName = methodName
[428] Fix | Delete
self._outcome = None
[429] Fix | Delete
self._testMethodDoc = 'No test'
[430] Fix | Delete
try:
[431] Fix | Delete
testMethod = getattr(self, methodName)
[432] Fix | Delete
except AttributeError:
[433] Fix | Delete
if methodName != 'runTest':
[434] Fix | Delete
# we allow instantiation with no explicit method name
[435] Fix | Delete
# but not an *incorrect* or missing method name
[436] Fix | Delete
raise ValueError("no such test method in %s: %s" %
[437] Fix | Delete
(self.__class__, methodName))
[438] Fix | Delete
else:
[439] Fix | Delete
self._testMethodDoc = testMethod.__doc__
[440] Fix | Delete
self._cleanups = []
[441] Fix | Delete
self._subtest = None
[442] Fix | Delete
[443] Fix | Delete
# Map types to custom assertEqual functions that will compare
[444] Fix | Delete
# instances of said type in more detail to generate a more useful
[445] Fix | Delete
# error message.
[446] Fix | Delete
self._type_equality_funcs = {}
[447] Fix | Delete
self.addTypeEqualityFunc(dict, 'assertDictEqual')
[448] Fix | Delete
self.addTypeEqualityFunc(list, 'assertListEqual')
[449] Fix | Delete
self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
[450] Fix | Delete
self.addTypeEqualityFunc(set, 'assertSetEqual')
[451] Fix | Delete
self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
[452] Fix | Delete
self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
[453] Fix | Delete
[454] Fix | Delete
def addTypeEqualityFunc(self, typeobj, function):
[455] Fix | Delete
"""Add a type specific assertEqual style function to compare a type.
[456] Fix | Delete
[457] Fix | Delete
This method is for use by TestCase subclasses that need to register
[458] Fix | Delete
their own type equality functions to provide nicer error messages.
[459] Fix | Delete
[460] Fix | Delete
Args:
[461] Fix | Delete
typeobj: The data type to call this function on when both values
[462] Fix | Delete
are of the same type in assertEqual().
[463] Fix | Delete
function: The callable taking two arguments and an optional
[464] Fix | Delete
msg= argument that raises self.failureException with a
[465] Fix | Delete
useful error message when the two arguments are not equal.
[466] Fix | Delete
"""
[467] Fix | Delete
self._type_equality_funcs[typeobj] = function
[468] Fix | Delete
[469] Fix | Delete
def addCleanup(*args, **kwargs):
[470] Fix | Delete
"""Add a function, with arguments, to be called when the test is
[471] Fix | Delete
completed. Functions added are called on a LIFO basis and are
[472] Fix | Delete
called after tearDown on test failure or success.
[473] Fix | Delete
[474] Fix | Delete
Cleanup items are called even if setUp fails (unlike tearDown)."""
[475] Fix | Delete
if len(args) >= 2:
[476] Fix | Delete
self, function, *args = args
[477] Fix | Delete
elif not args:
[478] Fix | Delete
raise TypeError("descriptor 'addCleanup' of 'TestCase' object "
[479] Fix | Delete
"needs an argument")
[480] Fix | Delete
elif 'function' in kwargs:
[481] Fix | Delete
function = kwargs.pop('function')
[482] Fix | Delete
self, *args = args
[483] Fix | Delete
import warnings
[484] Fix | Delete
warnings.warn("Passing 'function' as keyword argument is deprecated",
[485] Fix | Delete
DeprecationWarning, stacklevel=2)
[486] Fix | Delete
else:
[487] Fix | Delete
raise TypeError('addCleanup expected at least 1 positional '
[488] Fix | Delete
'argument, got %d' % (len(args)-1))
[489] Fix | Delete
args = tuple(args)
[490] Fix | Delete
[491] Fix | Delete
self._cleanups.append((function, args, kwargs))
[492] Fix | Delete
addCleanup.__text_signature__ = '($self, function, /, *args, **kwargs)'
[493] Fix | Delete
[494] Fix | Delete
@classmethod
[495] Fix | Delete
def addClassCleanup(cls, function, /, *args, **kwargs):
[496] Fix | Delete
"""Same as addCleanup, except the cleanup items are called even if
[497] Fix | Delete
setUpClass fails (unlike tearDownClass)."""
[498] Fix | Delete
cls._class_cleanups.append((function, args, kwargs))
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function