blob: d0ee561a3ae93a95358be9dba304237399661f33 [file] [log] [blame]
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001"""Test case implementation"""
2
3import sys
4import functools
5import difflib
Antoine Pitrou0715b9f2013-09-14 19:45:47 +02006import logging
Benjamin Petersonbed7d042009-07-19 21:01:52 +00007import pprint
8import re
9import warnings
Raymond Hettinger6e165b32010-11-27 09:31:37 +000010import collections
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010011import contextlib
Antoine Pitrou96810222014-04-29 01:23:50 +020012import traceback
Naitree Zhud5fd75c2019-09-09 22:06:48 +080013import types
Benjamin Petersonbed7d042009-07-19 21:01:52 +000014
Benjamin Peterson847a4112010-03-14 15:04:17 +000015from . import result
Florent Xiclunac53ae582011-11-04 08:25:54 +010016from .util import (strclass, safe_repr, _count_diff_all_purpose,
Serhiy Storchaka77622f52013-09-23 23:07:00 +030017 _count_diff_hashable, _common_shorten_repr)
Benjamin Petersonbed7d042009-07-19 21:01:52 +000018
Benjamin Petersondccc1fc2010-03-22 00:15:53 +000019__unittest = True
Benjamin Petersonbed7d042009-07-19 21:01:52 +000020
Berker Peksag16ea19f2016-09-21 19:34:15 +030021_subtest_msg_sentinel = object()
Michael Foord9dad32e2010-06-05 13:49:56 +000022
23DIFF_OMITTED = ('\nDiff is %s characters long. '
24 'Set self.maxDiff to None to see it.')
25
Benjamin Petersonbed7d042009-07-19 21:01:52 +000026class SkipTest(Exception):
27 """
28 Raise this exception in a test to skip it.
29
Ezio Melotti265281a2013-03-27 20:11:55 +020030 Usually you can use TestCase.skipTest() or one of the skipping decorators
Benjamin Petersonbed7d042009-07-19 21:01:52 +000031 instead of raising this directly.
32 """
Benjamin Petersonbed7d042009-07-19 21:01:52 +000033
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010034class _ShouldStop(Exception):
Benjamin Petersonbed7d042009-07-19 21:01:52 +000035 """
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010036 The test should stop.
Benjamin Petersonbed7d042009-07-19 21:01:52 +000037 """
38
Benjamin Petersonbed7d042009-07-19 21:01:52 +000039class _UnexpectedSuccess(Exception):
40 """
41 The test was supposed to fail, but it didn't!
42 """
Michael Foordb3468f72010-12-19 03:19:47 +000043
44
45class _Outcome(object):
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010046 def __init__(self, result=None):
47 self.expecting_failure = False
48 self.result = result
49 self.result_supports_subtests = hasattr(result, "addSubTest")
Michael Foordb3468f72010-12-19 03:19:47 +000050 self.success = True
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010051 self.skipped = []
Michael Foordb3468f72010-12-19 03:19:47 +000052 self.expectedFailure = None
53 self.errors = []
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010054
55 @contextlib.contextmanager
56 def testPartExecutor(self, test_case, isTest=False):
57 old_success = self.success
58 self.success = True
59 try:
60 yield
61 except KeyboardInterrupt:
62 raise
63 except SkipTest as e:
64 self.success = False
65 self.skipped.append((test_case, str(e)))
66 except _ShouldStop:
67 pass
68 except:
69 exc_info = sys.exc_info()
70 if self.expecting_failure:
71 self.expectedFailure = exc_info
72 else:
73 self.success = False
74 self.errors.append((test_case, exc_info))
Victor Stinner031bd532013-12-09 01:52:50 +010075 # explicitly break a reference cycle:
76 # exc_info -> frame -> exc_info
77 exc_info = None
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010078 else:
79 if self.result_supports_subtests and self.success:
80 self.errors.append((test_case, None))
81 finally:
82 self.success = self.success and old_success
Michael Foordb3468f72010-12-19 03:19:47 +000083
Benjamin Petersonbed7d042009-07-19 21:01:52 +000084
85def _id(obj):
86 return obj
87
Lisa Roach0f221d02018-11-08 18:34:33 -080088
89_module_cleanups = []
Serhiy Storchaka2085bd02019-06-01 11:00:15 +030090def addModuleCleanup(function, /, *args, **kwargs):
Lisa Roach0f221d02018-11-08 18:34:33 -080091 """Same as addCleanup, except the cleanup items are called even if
92 setUpModule fails (unlike tearDownModule)."""
93 _module_cleanups.append((function, args, kwargs))
94
95
96def doModuleCleanups():
97 """Execute all module cleanup functions. Normally called for you after
98 tearDownModule."""
99 exceptions = []
100 while _module_cleanups:
101 function, args, kwargs = _module_cleanups.pop()
102 try:
103 function(*args, **kwargs)
104 except Exception as exc:
105 exceptions.append(exc)
106 if exceptions:
107 # Swallows all but first exception. If a multi-exception handler
108 # gets written we should use that here instead.
109 raise exceptions[0]
110
111
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000112def skip(reason):
113 """
114 Unconditionally skip a test.
115 """
116 def decorator(test_item):
Antoine Pitroub05ac862012-04-25 14:56:46 +0200117 if not isinstance(test_item, type):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000118 @functools.wraps(test_item)
119 def skip_wrapper(*args, **kwargs):
120 raise SkipTest(reason)
121 test_item = skip_wrapper
122
123 test_item.__unittest_skip__ = True
124 test_item.__unittest_skip_why__ = reason
125 return test_item
Naitree Zhud5fd75c2019-09-09 22:06:48 +0800126 if isinstance(reason, types.FunctionType):
127 test_item = reason
128 reason = ''
129 return decorator(test_item)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000130 return decorator
131
132def skipIf(condition, reason):
133 """
134 Skip a test if the condition is true.
135 """
136 if condition:
137 return skip(reason)
138 return _id
139
140def skipUnless(condition, reason):
141 """
142 Skip a test unless the condition is true.
143 """
144 if not condition:
145 return skip(reason)
146 return _id
147
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100148def expectedFailure(test_item):
149 test_item.__unittest_expecting_failure__ = True
150 return test_item
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000151
Serhiy Storchaka041dd8e2015-05-21 20:15:40 +0300152def _is_subtype(expected, basetype):
153 if isinstance(expected, tuple):
154 return all(_is_subtype(e, basetype) for e in expected)
155 return isinstance(expected, type) and issubclass(expected, basetype)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000156
Antoine Pitrou0715b9f2013-09-14 19:45:47 +0200157class _BaseTestCaseContext:
158
159 def __init__(self, test_case):
160 self.test_case = test_case
161
162 def _raiseFailure(self, standardMsg):
163 msg = self.test_case._formatMessage(self.msg, standardMsg)
164 raise self.test_case.failureException(msg)
165
Antoine Pitrou0715b9f2013-09-14 19:45:47 +0200166class _AssertRaisesBaseContext(_BaseTestCaseContext):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000167
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300168 def __init__(self, expected, test_case, expected_regex=None):
Antoine Pitrou0715b9f2013-09-14 19:45:47 +0200169 _BaseTestCaseContext.__init__(self, test_case)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000170 self.expected = expected
Ezio Melottib4dc2502011-05-06 15:01:41 +0300171 self.test_case = test_case
R David Murrayef1c2672014-03-25 15:31:50 -0400172 if expected_regex is not None:
Ezio Melottied3a7d22010-12-01 02:32:32 +0000173 expected_regex = re.compile(expected_regex)
174 self.expected_regex = expected_regex
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300175 self.obj_name = None
Ezio Melottib4dc2502011-05-06 15:01:41 +0300176 self.msg = None
177
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300178 def handle(self, name, args, kwargs):
Ezio Melottib4dc2502011-05-06 15:01:41 +0300179 """
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300180 If args is empty, assertRaises/Warns is being used as a
Ezio Melottib4dc2502011-05-06 15:01:41 +0300181 context manager, so check for a 'msg' kwarg and return self.
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300182 If args is not empty, call a callable passing positional and keyword
183 arguments.
Ezio Melottib4dc2502011-05-06 15:01:41 +0300184 """
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300185 try:
Victor Stinnerbbd3cf82017-03-28 00:56:28 +0200186 if not _is_subtype(self.expected, self._base_type):
187 raise TypeError('%s() arg 1 must be %s' %
188 (name, self._base_type_str))
Victor Stinnerbbd3cf82017-03-28 00:56:28 +0200189 if not args:
190 self.msg = kwargs.pop('msg', None)
191 if kwargs:
Serhiy Storchaka77d57812018-08-19 10:00:11 +0300192 raise TypeError('%r is an invalid keyword argument for '
193 'this function' % (next(iter(kwargs)),))
Victor Stinnerbbd3cf82017-03-28 00:56:28 +0200194 return self
195
196 callable_obj, *args = args
197 try:
198 self.obj_name = callable_obj.__name__
199 except AttributeError:
200 self.obj_name = str(callable_obj)
201 with self:
202 callable_obj(*args, **kwargs)
203 finally:
204 # bpo-23890: manually break a reference cycle
205 self = None
Ezio Melottib4dc2502011-05-06 15:01:41 +0300206
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000207
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000208class _AssertRaisesContext(_AssertRaisesBaseContext):
209 """A context manager used to implement TestCase.assertRaises* methods."""
210
Serhiy Storchaka041dd8e2015-05-21 20:15:40 +0300211 _base_type = BaseException
212 _base_type_str = 'an exception type or tuple of exception types'
213
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000214 def __enter__(self):
Ezio Melotti49008232010-02-08 21:57:48 +0000215 return self
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000216
217 def __exit__(self, exc_type, exc_value, tb):
218 if exc_type is None:
219 try:
220 exc_name = self.expected.__name__
221 except AttributeError:
222 exc_name = str(self.expected)
223 if self.obj_name:
Ezio Melottib4dc2502011-05-06 15:01:41 +0300224 self._raiseFailure("{} not raised by {}".format(exc_name,
225 self.obj_name))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000226 else:
Ezio Melottib4dc2502011-05-06 15:01:41 +0300227 self._raiseFailure("{} not raised".format(exc_name))
Antoine Pitrou96810222014-04-29 01:23:50 +0200228 else:
229 traceback.clear_frames(tb)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000230 if not issubclass(exc_type, self.expected):
231 # let unexpected exceptions pass through
232 return False
Ezio Melotti49008232010-02-08 21:57:48 +0000233 # store exception, without traceback, for later retrieval
234 self.exception = exc_value.with_traceback(None)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000235 if self.expected_regex is None:
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000236 return True
237
Ezio Melottied3a7d22010-12-01 02:32:32 +0000238 expected_regex = self.expected_regex
239 if not expected_regex.search(str(exc_value)):
Ezio Melottib4dc2502011-05-06 15:01:41 +0300240 self._raiseFailure('"{}" does not match "{}"'.format(
241 expected_regex.pattern, str(exc_value)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000242 return True
243
Batuhan TaÅŸkaya03615562020-04-10 17:46:36 +0300244 __class_getitem__ = classmethod(types.GenericAlias)
245
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000246
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000247class _AssertWarnsContext(_AssertRaisesBaseContext):
248 """A context manager used to implement TestCase.assertWarns* methods."""
249
Serhiy Storchaka041dd8e2015-05-21 20:15:40 +0300250 _base_type = Warning
251 _base_type_str = 'a warning type or tuple of warning types'
252
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000253 def __enter__(self):
254 # The __warningregistry__'s need to be in a pristine state for tests
255 # to work properly.
256 for v in sys.modules.values():
257 if getattr(v, '__warningregistry__', None):
258 v.__warningregistry__ = {}
259 self.warnings_manager = warnings.catch_warnings(record=True)
260 self.warnings = self.warnings_manager.__enter__()
261 warnings.simplefilter("always", self.expected)
262 return self
263
264 def __exit__(self, exc_type, exc_value, tb):
265 self.warnings_manager.__exit__(exc_type, exc_value, tb)
266 if exc_type is not None:
267 # let unexpected exceptions pass through
268 return
269 try:
270 exc_name = self.expected.__name__
271 except AttributeError:
272 exc_name = str(self.expected)
273 first_matching = None
274 for m in self.warnings:
275 w = m.message
276 if not isinstance(w, self.expected):
277 continue
278 if first_matching is None:
279 first_matching = w
Ezio Melottied3a7d22010-12-01 02:32:32 +0000280 if (self.expected_regex is not None and
281 not self.expected_regex.search(str(w))):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000282 continue
283 # store warning for later retrieval
284 self.warning = w
285 self.filename = m.filename
286 self.lineno = m.lineno
287 return
288 # Now we simply try to choose a helpful failure message
289 if first_matching is not None:
Ezio Melottib4dc2502011-05-06 15:01:41 +0300290 self._raiseFailure('"{}" does not match "{}"'.format(
291 self.expected_regex.pattern, str(first_matching)))
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000292 if self.obj_name:
Ezio Melottib4dc2502011-05-06 15:01:41 +0300293 self._raiseFailure("{} not triggered by {}".format(exc_name,
294 self.obj_name))
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000295 else:
Ezio Melottib4dc2502011-05-06 15:01:41 +0300296 self._raiseFailure("{} not triggered".format(exc_name))
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000297
298
Antoine Pitrou0715b9f2013-09-14 19:45:47 +0200299
300_LoggingWatcher = collections.namedtuple("_LoggingWatcher",
301 ["records", "output"])
302
303
304class _CapturingHandler(logging.Handler):
305 """
306 A logging handler capturing all (raw and formatted) logging output.
307 """
308
309 def __init__(self):
310 logging.Handler.__init__(self)
311 self.watcher = _LoggingWatcher([], [])
312
313 def flush(self):
314 pass
315
316 def emit(self, record):
317 self.watcher.records.append(record)
318 msg = self.format(record)
319 self.watcher.output.append(msg)
320
321
322
323class _AssertLogsContext(_BaseTestCaseContext):
324 """A context manager used to implement TestCase.assertLogs()."""
325
326 LOGGING_FORMAT = "%(levelname)s:%(name)s:%(message)s"
327
328 def __init__(self, test_case, logger_name, level):
329 _BaseTestCaseContext.__init__(self, test_case)
330 self.logger_name = logger_name
331 if level:
332 self.level = logging._nameToLevel.get(level, level)
333 else:
334 self.level = logging.INFO
335 self.msg = None
336
337 def __enter__(self):
338 if isinstance(self.logger_name, logging.Logger):
339 logger = self.logger = self.logger_name
340 else:
341 logger = self.logger = logging.getLogger(self.logger_name)
342 formatter = logging.Formatter(self.LOGGING_FORMAT)
343 handler = _CapturingHandler()
344 handler.setFormatter(formatter)
345 self.watcher = handler.watcher
346 self.old_handlers = logger.handlers[:]
347 self.old_level = logger.level
348 self.old_propagate = logger.propagate
349 logger.handlers = [handler]
350 logger.setLevel(self.level)
351 logger.propagate = False
352 return handler.watcher
353
354 def __exit__(self, exc_type, exc_value, tb):
355 self.logger.handlers = self.old_handlers
356 self.logger.propagate = self.old_propagate
357 self.logger.setLevel(self.old_level)
358 if exc_type is not None:
359 # let unexpected exceptions pass through
360 return False
361 if len(self.watcher.records) == 0:
362 self._raiseFailure(
363 "no logs of level {} or higher triggered on {}"
364 .format(logging.getLevelName(self.level), self.logger.name))
365
366
Serhiy Storchaka48fbe522017-06-23 21:47:39 +0300367class _OrderedChainMap(collections.ChainMap):
368 def __iter__(self):
369 seen = set()
370 for mapping in self.maps:
371 for k in mapping:
372 if k not in seen:
373 seen.add(k)
374 yield k
375
376
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000377class TestCase(object):
378 """A class whose instances are single test cases.
379
380 By default, the test code itself should be placed in a method named
381 'runTest'.
382
383 If the fixture may be used for many test cases, create as
384 many test methods as are needed. When instantiating such a TestCase
385 subclass, specify in the constructor arguments the name of the test method
386 that the instance is to execute.
387
388 Test authors should subclass TestCase for their own tests. Construction
389 and deconstruction of the test's environment ('fixture') can be
390 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
391
392 If it is necessary to override the __init__ method, the base class
393 __init__ method must always be called. It is important that subclasses
394 should not change the signature of their __init__ method, since instances
395 of the classes are instantiated automatically by parts of the framework
396 in order to be run.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000397
Ezio Melotti31797e52013-03-29 03:42:29 +0200398 When subclassing TestCase, you can set these attributes:
399 * failureException: determines which exception will be raised when
400 the instance's assertion methods fail; test methods raising this
401 exception will be deemed to have 'failed' rather than 'errored'.
402 * longMessage: determines whether long messages (including repr of
403 objects used in assert methods) will be printed on failure in *addition*
404 to any explicit message passed.
405 * maxDiff: sets the maximum length of a diff in failure messages
406 by assert methods using difflib. It is looked up as an instance
407 attribute so can be configured by individual tests if required.
408 """
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000409
410 failureException = AssertionError
411
Michael Foord5074df62010-12-03 00:53:09 +0000412 longMessage = True
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000413
Michael Foord085dfd32010-06-05 12:17:02 +0000414 maxDiff = 80*8
415
Ezio Melottiedd117f2011-04-27 10:20:38 +0300416 # If a string is longer than _diffThreshold, use normal comparison instead
417 # of difflib. See #11763.
418 _diffThreshold = 2**16
419
Benjamin Peterson847a4112010-03-14 15:04:17 +0000420 # Attribute used by TestSuite for classSetUp
421
422 _classSetupFailed = False
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000423
Lisa Roach0f221d02018-11-08 18:34:33 -0800424 _class_cleanups = []
425
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000426 def __init__(self, methodName='runTest'):
427 """Create an instance of the class that will use the named test
428 method when executed. Raises a ValueError if the instance does
429 not have a method with the specified name.
430 """
431 self._testMethodName = methodName
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100432 self._outcome = None
Michael Foord32e1d832011-01-03 17:00:11 +0000433 self._testMethodDoc = 'No test'
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000434 try:
435 testMethod = getattr(self, methodName)
436 except AttributeError:
Michael Foord32e1d832011-01-03 17:00:11 +0000437 if methodName != 'runTest':
438 # we allow instantiation with no explicit method name
439 # but not an *incorrect* or missing method name
440 raise ValueError("no such test method in %s: %s" %
441 (self.__class__, methodName))
442 else:
443 self._testMethodDoc = testMethod.__doc__
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000444 self._cleanups = []
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100445 self._subtest = None
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000446
447 # Map types to custom assertEqual functions that will compare
448 # instances of said type in more detail to generate a more useful
449 # error message.
Benjamin Peterson34b2b262011-07-12 19:21:42 -0500450 self._type_equality_funcs = {}
Michael Foord8ca6d982010-11-20 15:34:26 +0000451 self.addTypeEqualityFunc(dict, 'assertDictEqual')
452 self.addTypeEqualityFunc(list, 'assertListEqual')
453 self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
454 self.addTypeEqualityFunc(set, 'assertSetEqual')
455 self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
456 self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000457
458 def addTypeEqualityFunc(self, typeobj, function):
459 """Add a type specific assertEqual style function to compare a type.
460
461 This method is for use by TestCase subclasses that need to register
462 their own type equality functions to provide nicer error messages.
463
464 Args:
465 typeobj: The data type to call this function on when both values
466 are of the same type in assertEqual().
467 function: The callable taking two arguments and an optional
468 msg= argument that raises self.failureException with a
469 useful error message when the two arguments are not equal.
470 """
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000471 self._type_equality_funcs[typeobj] = function
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000472
Serhiy Storchaka142566c2019-06-05 18:22:31 +0300473 def addCleanup(self, function, /, *args, **kwargs):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000474 """Add a function, with arguments, to be called when the test is
475 completed. Functions added are called on a LIFO basis and are
476 called after tearDown on test failure or success.
477
478 Cleanup items are called even if setUp fails (unlike tearDown)."""
479 self._cleanups.append((function, args, kwargs))
480
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300481 @classmethod
482 def addClassCleanup(cls, function, /, *args, **kwargs):
Lisa Roach0f221d02018-11-08 18:34:33 -0800483 """Same as addCleanup, except the cleanup items are called even if
484 setUpClass fails (unlike tearDownClass)."""
485 cls._class_cleanups.append((function, args, kwargs))
486
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000487 def setUp(self):
488 "Hook method for setting up the test fixture before exercising it."
489 pass
490
491 def tearDown(self):
492 "Hook method for deconstructing the test fixture after testing it."
493 pass
494
Benjamin Peterson847a4112010-03-14 15:04:17 +0000495 @classmethod
496 def setUpClass(cls):
497 "Hook method for setting up class fixture before running tests in the class."
498
499 @classmethod
500 def tearDownClass(cls):
501 "Hook method for deconstructing the class fixture after running all tests in the class."
502
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000503 def countTestCases(self):
504 return 1
505
506 def defaultTestResult(self):
507 return result.TestResult()
508
509 def shortDescription(self):
Michael Foord34c94622010-02-10 15:51:42 +0000510 """Returns a one-line description of the test, or None if no
511 description has been provided.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000512
Michael Foord34c94622010-02-10 15:51:42 +0000513 The default implementation of this method returns the first line of
514 the specified test method's docstring.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000515 """
Michael Foord34c94622010-02-10 15:51:42 +0000516 doc = self._testMethodDoc
Steve Cirelli032de732020-02-03 02:06:50 -0500517 return doc.strip().split("\n")[0].strip() if doc else None
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000518
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000519
520 def id(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000521 return "%s.%s" % (strclass(self.__class__), self._testMethodName)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000522
523 def __eq__(self, other):
524 if type(self) is not type(other):
525 return NotImplemented
526
527 return self._testMethodName == other._testMethodName
528
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000529 def __hash__(self):
530 return hash((type(self), self._testMethodName))
531
532 def __str__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000533 return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000534
535 def __repr__(self):
536 return "<%s testMethod=%s>" % \
Benjamin Peterson847a4112010-03-14 15:04:17 +0000537 (strclass(self.__class__), self._testMethodName)
538
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100539 def _addSkip(self, result, test_case, reason):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000540 addSkip = getattr(result, 'addSkip', None)
541 if addSkip is not None:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100542 addSkip(test_case, reason)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000543 else:
544 warnings.warn("TestResult has no addSkip method, skips not reported",
545 RuntimeWarning, 2)
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100546 result.addSuccess(test_case)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000547
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100548 @contextlib.contextmanager
Berker Peksag16ea19f2016-09-21 19:34:15 +0300549 def subTest(self, msg=_subtest_msg_sentinel, **params):
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100550 """Return a context manager that will return the enclosed block
551 of code in a subtest identified by the optional message and
552 keyword parameters. A failure in the subtest marks the test
553 case as failed but resumes execution at the end of the enclosed
554 block, allowing further test code to be executed.
555 """
Bruno Oliveirada2bf9f2018-10-12 07:35:55 -0300556 if self._outcome is None or not self._outcome.result_supports_subtests:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100557 yield
558 return
559 parent = self._subtest
560 if parent is None:
Serhiy Storchaka48fbe522017-06-23 21:47:39 +0300561 params_map = _OrderedChainMap(params)
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100562 else:
563 params_map = parent.params.new_child(params)
564 self._subtest = _SubTest(self, msg, params_map)
Michael Foordb3468f72010-12-19 03:19:47 +0000565 try:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100566 with self._outcome.testPartExecutor(self._subtest, isTest=True):
567 yield
568 if not self._outcome.success:
569 result = self._outcome.result
570 if result is not None and result.failfast:
571 raise _ShouldStop
572 elif self._outcome.expectedFailure:
573 # If the test is expecting a failure, we really want to
574 # stop now and register the expected failure.
575 raise _ShouldStop
576 finally:
577 self._subtest = parent
578
579 def _feedErrorsToResult(self, result, errors):
580 for test, exc_info in errors:
581 if isinstance(test, _SubTest):
582 result.addSubTest(test.test_case, test, exc_info)
583 elif exc_info is not None:
584 if issubclass(exc_info[0], self.failureException):
585 result.addFailure(test, exc_info)
586 else:
587 result.addError(test, exc_info)
588
589 def _addExpectedFailure(self, result, exc_info):
590 try:
591 addExpectedFailure = result.addExpectedFailure
592 except AttributeError:
593 warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
594 RuntimeWarning)
595 result.addSuccess(self)
596 else:
597 addExpectedFailure(self, exc_info)
598
599 def _addUnexpectedSuccess(self, result):
600 try:
601 addUnexpectedSuccess = result.addUnexpectedSuccess
602 except AttributeError:
603 warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failure",
604 RuntimeWarning)
605 # We need to pass an actual exception and traceback to addFailure,
606 # otherwise the legacy result can choke.
607 try:
608 raise _UnexpectedSuccess from None
609 except _UnexpectedSuccess:
610 result.addFailure(self, sys.exc_info())
611 else:
612 addUnexpectedSuccess(self)
Michael Foordb3468f72010-12-19 03:19:47 +0000613
Andrew Svetlov4dd3e3f2019-05-29 12:33:59 +0300614 def _callSetUp(self):
615 self.setUp()
616
617 def _callTestMethod(self, method):
618 method()
619
620 def _callTearDown(self):
621 self.tearDown()
622
623 def _callCleanup(self, function, /, *args, **kwargs):
624 function(*args, **kwargs)
625
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000626 def run(self, result=None):
627 orig_result = result
628 if result is None:
629 result = self.defaultTestResult()
630 startTestRun = getattr(result, 'startTestRun', None)
631 if startTestRun is not None:
632 startTestRun()
633
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000634 result.startTest(self)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000635
636 testMethod = getattr(self, self._testMethodName)
637 if (getattr(self.__class__, "__unittest_skip__", False) or
638 getattr(testMethod, "__unittest_skip__", False)):
639 # If the class or method was skipped.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000640 try:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000641 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
642 or getattr(testMethod, '__unittest_skip_why__', ''))
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100643 self._addSkip(result, self, skip_why)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000644 finally:
645 result.stopTest(self)
646 return
Robert Collinsed599b72015-08-28 10:34:51 +1200647 expecting_failure_method = getattr(testMethod,
648 "__unittest_expecting_failure__", False)
649 expecting_failure_class = getattr(self,
650 "__unittest_expecting_failure__", False)
651 expecting_failure = expecting_failure_class or expecting_failure_method
Victor Stinner031bd532013-12-09 01:52:50 +0100652 outcome = _Outcome(result)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000653 try:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100654 self._outcome = outcome
Michael Foordb3468f72010-12-19 03:19:47 +0000655
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100656 with outcome.testPartExecutor(self):
Andrew Svetlov4dd3e3f2019-05-29 12:33:59 +0300657 self._callSetUp()
Michael Foordb3468f72010-12-19 03:19:47 +0000658 if outcome.success:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100659 outcome.expecting_failure = expecting_failure
660 with outcome.testPartExecutor(self, isTest=True):
Andrew Svetlov4dd3e3f2019-05-29 12:33:59 +0300661 self._callTestMethod(testMethod)
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100662 outcome.expecting_failure = False
663 with outcome.testPartExecutor(self):
Andrew Svetlov4dd3e3f2019-05-29 12:33:59 +0300664 self._callTearDown()
Michael Foordb3468f72010-12-19 03:19:47 +0000665
666 self.doCleanups()
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100667 for test, reason in outcome.skipped:
668 self._addSkip(result, test, reason)
669 self._feedErrorsToResult(result, outcome.errors)
Michael Foordb3468f72010-12-19 03:19:47 +0000670 if outcome.success:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100671 if expecting_failure:
672 if outcome.expectedFailure:
673 self._addExpectedFailure(result, outcome.expectedFailure)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000674 else:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100675 self._addUnexpectedSuccess(result)
676 else:
677 result.addSuccess(self)
Michael Foord1341bb02011-03-14 19:01:46 -0400678 return result
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000679 finally:
680 result.stopTest(self)
681 if orig_result is None:
682 stopTestRun = getattr(result, 'stopTestRun', None)
683 if stopTestRun is not None:
684 stopTestRun()
685
Victor Stinner031bd532013-12-09 01:52:50 +0100686 # explicitly break reference cycles:
687 # outcome.errors -> frame -> outcome -> outcome.errors
688 # outcome.expectedFailure -> frame -> outcome -> outcome.expectedFailure
689 outcome.errors.clear()
690 outcome.expectedFailure = None
691
692 # clear the outcome, no more needed
693 self._outcome = None
694
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000695 def doCleanups(self):
696 """Execute all cleanup functions. Normally called for you after
697 tearDown."""
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100698 outcome = self._outcome or _Outcome()
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000699 while self._cleanups:
Michael Foordb3468f72010-12-19 03:19:47 +0000700 function, args, kwargs = self._cleanups.pop()
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100701 with outcome.testPartExecutor(self):
Andrew Svetlov4dd3e3f2019-05-29 12:33:59 +0300702 self._callCleanup(function, *args, **kwargs)
Michael Foordb3468f72010-12-19 03:19:47 +0000703
704 # return this for backwards compatibility
Lisa Roach0f221d02018-11-08 18:34:33 -0800705 # even though we no longer use it internally
Michael Foordb3468f72010-12-19 03:19:47 +0000706 return outcome.success
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000707
Lisa Roach0f221d02018-11-08 18:34:33 -0800708 @classmethod
709 def doClassCleanups(cls):
710 """Execute all class cleanup functions. Normally called for you after
711 tearDownClass."""
712 cls.tearDown_exceptions = []
713 while cls._class_cleanups:
714 function, args, kwargs = cls._class_cleanups.pop()
715 try:
716 function(*args, **kwargs)
Pablo Galindo293dd232019-11-19 21:34:03 +0000717 except Exception:
Lisa Roach0f221d02018-11-08 18:34:33 -0800718 cls.tearDown_exceptions.append(sys.exc_info())
719
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000720 def __call__(self, *args, **kwds):
721 return self.run(*args, **kwds)
722
723 def debug(self):
724 """Run the test without collecting errors in a TestResult"""
725 self.setUp()
726 getattr(self, self._testMethodName)()
727 self.tearDown()
Michael Foordb8748742010-06-10 16:16:08 +0000728 while self._cleanups:
729 function, args, kwargs = self._cleanups.pop(-1)
730 function(*args, **kwargs)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000731
732 def skipTest(self, reason):
733 """Skip this test."""
734 raise SkipTest(reason)
735
736 def fail(self, msg=None):
737 """Fail immediately, with the given message."""
738 raise self.failureException(msg)
739
740 def assertFalse(self, expr, msg=None):
Ezio Melotti3044fa72010-12-18 17:31:58 +0000741 """Check that the expression is false."""
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000742 if expr:
Ezio Melotti3044fa72010-12-18 17:31:58 +0000743 msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000744 raise self.failureException(msg)
745
746 def assertTrue(self, expr, msg=None):
Ezio Melotti3044fa72010-12-18 17:31:58 +0000747 """Check that the expression is true."""
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000748 if not expr:
Ezio Melotti3044fa72010-12-18 17:31:58 +0000749 msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000750 raise self.failureException(msg)
751
752 def _formatMessage(self, msg, standardMsg):
753 """Honour the longMessage attribute when generating failure messages.
754 If longMessage is False this means:
755 * Use only an explicit message if it is provided
756 * Otherwise use the standard message for the assert
757
758 If longMessage is True:
759 * Use the standard message
760 * If an explicit message is provided, plus ' : ' and the explicit message
761 """
762 if not self.longMessage:
763 return msg or standardMsg
764 if msg is None:
765 return standardMsg
Benjamin Peterson847a4112010-03-14 15:04:17 +0000766 try:
767 # don't switch to '{}' formatting in Python 2.X
768 # it changes the way unicode input is handled
769 return '%s : %s' % (standardMsg, msg)
770 except UnicodeDecodeError:
771 return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000772
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300773 def assertRaises(self, expected_exception, *args, **kwargs):
774 """Fail unless an exception of class expected_exception is raised
775 by the callable when invoked with specified positional and
776 keyword arguments. If a different type of exception is
Andrew Svetlov737fb892012-12-18 21:14:22 +0200777 raised, it will not be caught, and the test case will be
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000778 deemed to have suffered an error, exactly as for an
779 unexpected exception.
780
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300781 If called with the callable and arguments omitted, will return a
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000782 context object used like this::
783
Michael Foord1c42b122010-02-05 22:58:21 +0000784 with self.assertRaises(SomeException):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000785 do_something()
Michael Foord1c42b122010-02-05 22:58:21 +0000786
Ezio Melottib4dc2502011-05-06 15:01:41 +0300787 An optional keyword argument 'msg' can be provided when assertRaises
788 is used as a context object.
789
Michael Foord1c42b122010-02-05 22:58:21 +0000790 The context manager keeps a reference to the exception as
Ezio Melotti49008232010-02-08 21:57:48 +0000791 the 'exception' attribute. This allows you to inspect the
Michael Foord1c42b122010-02-05 22:58:21 +0000792 exception after the assertion::
793
794 with self.assertRaises(SomeException) as cm:
795 do_something()
Ezio Melotti49008232010-02-08 21:57:48 +0000796 the_exception = cm.exception
Michael Foordb57ac6d2010-02-05 23:26:29 +0000797 self.assertEqual(the_exception.error_code, 3)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000798 """
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300799 context = _AssertRaisesContext(expected_exception, self)
Victor Stinnerbbd3cf82017-03-28 00:56:28 +0200800 try:
801 return context.handle('assertRaises', args, kwargs)
802 finally:
803 # bpo-23890: manually break a reference cycle
804 context = None
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000805
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300806 def assertWarns(self, expected_warning, *args, **kwargs):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000807 """Fail unless a warning of class warnClass is triggered
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300808 by the callable when invoked with specified positional and
809 keyword arguments. If a different type of warning is
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000810 triggered, it will not be handled: depending on the other
811 warning filtering rules in effect, it might be silenced, printed
812 out, or raised as an exception.
813
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300814 If called with the callable and arguments omitted, will return a
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000815 context object used like this::
816
817 with self.assertWarns(SomeWarning):
818 do_something()
819
Ezio Melottib4dc2502011-05-06 15:01:41 +0300820 An optional keyword argument 'msg' can be provided when assertWarns
821 is used as a context object.
822
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000823 The context manager keeps a reference to the first matching
824 warning as the 'warning' attribute; similarly, the 'filename'
825 and 'lineno' attributes give you information about the line
826 of Python code from which the warning was triggered.
827 This allows you to inspect the warning after the assertion::
828
829 with self.assertWarns(SomeWarning) as cm:
830 do_something()
831 the_warning = cm.warning
832 self.assertEqual(the_warning.some_attribute, 147)
833 """
Serhiy Storchakadf573d62015-05-16 16:29:50 +0300834 context = _AssertWarnsContext(expected_warning, self)
835 return context.handle('assertWarns', args, kwargs)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000836
Antoine Pitrou0715b9f2013-09-14 19:45:47 +0200837 def assertLogs(self, logger=None, level=None):
838 """Fail unless a log message of level *level* or higher is emitted
839 on *logger_name* or its children. If omitted, *level* defaults to
840 INFO and *logger* defaults to the root logger.
841
842 This method must be used as a context manager, and will yield
843 a recording object with two attributes: `output` and `records`.
844 At the end of the context manager, the `output` attribute will
845 be a list of the matching formatted log messages and the
846 `records` attribute will be a list of the corresponding LogRecord
847 objects.
848
849 Example::
850
851 with self.assertLogs('foo', level='INFO') as cm:
852 logging.getLogger('foo').info('first message')
853 logging.getLogger('foo.bar').error('second message')
854 self.assertEqual(cm.output, ['INFO:foo:first message',
855 'ERROR:foo.bar:second message'])
856 """
857 return _AssertLogsContext(self, logger, level)
858
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000859 def _getAssertEqualityFunc(self, first, second):
860 """Get a detailed comparison function for the types of the two args.
861
862 Returns: A callable accepting (first, second, msg=None) that will
863 raise a failure exception if first != second with a useful human
864 readable error message for those types.
865 """
866 #
867 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
868 # and vice versa. I opted for the conservative approach in case
869 # subclasses are not intended to be compared in detail to their super
870 # class instances using a type equality func. This means testing
871 # subtypes won't automagically use the detailed comparison. Callers
872 # should use their type specific assertSpamEqual method to compare
873 # subclasses if the detailed comparison is desired and appropriate.
874 # See the discussion in http://bugs.python.org/issue2578.
875 #
876 if type(first) is type(second):
877 asserter = self._type_equality_funcs.get(type(first))
878 if asserter is not None:
Benjamin Peterson34b2b262011-07-12 19:21:42 -0500879 if isinstance(asserter, str):
880 asserter = getattr(self, asserter)
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000881 return asserter
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000882
883 return self._baseAssertEqual
884
885 def _baseAssertEqual(self, first, second, msg=None):
886 """The default assertEqual implementation, not type specific."""
887 if not first == second:
Serhiy Storchaka77622f52013-09-23 23:07:00 +0300888 standardMsg = '%s != %s' % _common_shorten_repr(first, second)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000889 msg = self._formatMessage(msg, standardMsg)
890 raise self.failureException(msg)
891
892 def assertEqual(self, first, second, msg=None):
893 """Fail if the two objects are unequal as determined by the '=='
894 operator.
895 """
896 assertion_func = self._getAssertEqualityFunc(first, second)
897 assertion_func(first, second, msg=msg)
898
899 def assertNotEqual(self, first, second, msg=None):
Ezio Melotti90eea972012-11-08 11:08:39 +0200900 """Fail if the two objects are equal as determined by the '!='
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000901 operator.
902 """
903 if not first != second:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000904 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
905 safe_repr(second)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000906 raise self.failureException(msg)
907
Michael Foord321d0592010-11-02 13:44:51 +0000908 def assertAlmostEqual(self, first, second, places=None, msg=None,
Benjamin Petersonb48af542010-04-11 20:43:16 +0000909 delta=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000910 """Fail if the two objects are unequal as determined by their
911 difference rounded to the given number of decimal places
Benjamin Petersonb48af542010-04-11 20:43:16 +0000912 (default 7) and comparing to zero, or by comparing that the
Ron032a6482017-10-18 20:01:23 +0300913 difference between the two objects is more than the given
914 delta.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000915
916 Note that decimal places (from zero) are usually not the same
Martin Pantereb995702016-07-28 01:11:04 +0000917 as significant digits (measured from the most significant digit).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000918
919 If the two objects compare equal then they will automatically
920 compare almost equal.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000921 """
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000922 if first == second:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000923 # shortcut
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000924 return
Benjamin Petersonb48af542010-04-11 20:43:16 +0000925 if delta is not None and places is not None:
926 raise TypeError("specify delta or places not both")
927
Giampaolo Rodola5d7a8d02017-05-01 18:18:56 +0200928 diff = abs(first - second)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000929 if delta is not None:
Giampaolo Rodola5d7a8d02017-05-01 18:18:56 +0200930 if diff <= delta:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000931 return
932
Giampaolo Rodola5d7a8d02017-05-01 18:18:56 +0200933 standardMsg = '%s != %s within %s delta (%s difference)' % (
934 safe_repr(first),
935 safe_repr(second),
936 safe_repr(delta),
937 safe_repr(diff))
Benjamin Petersonb48af542010-04-11 20:43:16 +0000938 else:
939 if places is None:
940 places = 7
941
Giampaolo Rodola5d7a8d02017-05-01 18:18:56 +0200942 if round(diff, places) == 0:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000943 return
944
Giampaolo Rodola5d7a8d02017-05-01 18:18:56 +0200945 standardMsg = '%s != %s within %r places (%s difference)' % (
946 safe_repr(first),
947 safe_repr(second),
948 places,
949 safe_repr(diff))
Benjamin Petersonb48af542010-04-11 20:43:16 +0000950 msg = self._formatMessage(msg, standardMsg)
951 raise self.failureException(msg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000952
Michael Foord321d0592010-11-02 13:44:51 +0000953 def assertNotAlmostEqual(self, first, second, places=None, msg=None,
Benjamin Petersonb48af542010-04-11 20:43:16 +0000954 delta=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000955 """Fail if the two objects are equal as determined by their
956 difference rounded to the given number of decimal places
Benjamin Petersonb48af542010-04-11 20:43:16 +0000957 (default 7) and comparing to zero, or by comparing that the
Ron032a6482017-10-18 20:01:23 +0300958 difference between the two objects is less than the given delta.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000959
960 Note that decimal places (from zero) are usually not the same
Martin Pantereb995702016-07-28 01:11:04 +0000961 as significant digits (measured from the most significant digit).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000962
963 Objects that are equal automatically fail.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000964 """
Benjamin Petersonb48af542010-04-11 20:43:16 +0000965 if delta is not None and places is not None:
966 raise TypeError("specify delta or places not both")
Giampaolo Rodola5d7a8d02017-05-01 18:18:56 +0200967 diff = abs(first - second)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000968 if delta is not None:
Giampaolo Rodola5d7a8d02017-05-01 18:18:56 +0200969 if not (first == second) and diff > delta:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000970 return
Giampaolo Rodola5d7a8d02017-05-01 18:18:56 +0200971 standardMsg = '%s == %s within %s delta (%s difference)' % (
972 safe_repr(first),
973 safe_repr(second),
974 safe_repr(delta),
975 safe_repr(diff))
Benjamin Petersonb48af542010-04-11 20:43:16 +0000976 else:
977 if places is None:
978 places = 7
Giampaolo Rodola5d7a8d02017-05-01 18:18:56 +0200979 if not (first == second) and round(diff, places) != 0:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000980 return
Benjamin Peterson847a4112010-03-14 15:04:17 +0000981 standardMsg = '%s == %s within %r places' % (safe_repr(first),
Benjamin Petersonb48af542010-04-11 20:43:16 +0000982 safe_repr(second),
983 places)
984
985 msg = self._formatMessage(msg, standardMsg)
986 raise self.failureException(msg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000987
Michael Foord085dfd32010-06-05 12:17:02 +0000988 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000989 """An equality assertion for ordered sequences (like lists and tuples).
990
R. David Murrayad13f222010-01-29 22:17:58 +0000991 For the purposes of this function, a valid ordered sequence type is one
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000992 which can be indexed, has a length, and has an equality operator.
993
994 Args:
995 seq1: The first sequence to compare.
996 seq2: The second sequence to compare.
997 seq_type: The expected datatype of the sequences, or None if no
998 datatype should be enforced.
999 msg: Optional message to use on failure instead of a list of
1000 differences.
1001 """
Benjamin Petersonb29614e2012-10-09 11:16:03 -04001002 if seq_type is not None:
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001003 seq_type_name = seq_type.__name__
1004 if not isinstance(seq1, seq_type):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001005 raise self.failureException('First sequence is not a %s: %s'
1006 % (seq_type_name, safe_repr(seq1)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001007 if not isinstance(seq2, seq_type):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001008 raise self.failureException('Second sequence is not a %s: %s'
1009 % (seq_type_name, safe_repr(seq2)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001010 else:
1011 seq_type_name = "sequence"
1012
1013 differing = None
1014 try:
1015 len1 = len(seq1)
1016 except (TypeError, NotImplementedError):
1017 differing = 'First %s has no length. Non-sequence?' % (
1018 seq_type_name)
1019
1020 if differing is None:
1021 try:
1022 len2 = len(seq2)
1023 except (TypeError, NotImplementedError):
1024 differing = 'Second %s has no length. Non-sequence?' % (
1025 seq_type_name)
1026
1027 if differing is None:
1028 if seq1 == seq2:
1029 return
1030
Serhiy Storchaka77622f52013-09-23 23:07:00 +03001031 differing = '%ss differ: %s != %s\n' % (
1032 (seq_type_name.capitalize(),) +
1033 _common_shorten_repr(seq1, seq2))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001034
1035 for i in range(min(len1, len2)):
1036 try:
1037 item1 = seq1[i]
1038 except (TypeError, IndexError, NotImplementedError):
1039 differing += ('\nUnable to index element %d of first %s\n' %
1040 (i, seq_type_name))
1041 break
1042
1043 try:
1044 item2 = seq2[i]
1045 except (TypeError, IndexError, NotImplementedError):
1046 differing += ('\nUnable to index element %d of second %s\n' %
1047 (i, seq_type_name))
1048 break
1049
1050 if item1 != item2:
1051 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
Serhiy Storchaka685fbed2016-04-25 08:58:25 +03001052 ((i,) + _common_shorten_repr(item1, item2)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001053 break
1054 else:
1055 if (len1 == len2 and seq_type is None and
1056 type(seq1) != type(seq2)):
1057 # The sequences are the same, but have differing types.
1058 return
1059
1060 if len1 > len2:
1061 differing += ('\nFirst %s contains %d additional '
1062 'elements.\n' % (seq_type_name, len1 - len2))
1063 try:
1064 differing += ('First extra element %d:\n%s\n' %
Serhiy Storchaka685fbed2016-04-25 08:58:25 +03001065 (len2, safe_repr(seq1[len2])))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001066 except (TypeError, IndexError, NotImplementedError):
1067 differing += ('Unable to index element %d '
1068 'of first %s\n' % (len2, seq_type_name))
1069 elif len1 < len2:
1070 differing += ('\nSecond %s contains %d additional '
1071 'elements.\n' % (seq_type_name, len2 - len1))
1072 try:
1073 differing += ('First extra element %d:\n%s\n' %
Serhiy Storchaka685fbed2016-04-25 08:58:25 +03001074 (len1, safe_repr(seq2[len1])))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001075 except (TypeError, IndexError, NotImplementedError):
1076 differing += ('Unable to index element %d '
1077 'of second %s\n' % (len1, seq_type_name))
Michael Foord2034d9a2010-06-05 11:27:52 +00001078 standardMsg = differing
1079 diffMsg = '\n' + '\n'.join(
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001080 difflib.ndiff(pprint.pformat(seq1).splitlines(),
1081 pprint.pformat(seq2).splitlines()))
Michael Foord085dfd32010-06-05 12:17:02 +00001082
1083 standardMsg = self._truncateMessage(standardMsg, diffMsg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001084 msg = self._formatMessage(msg, standardMsg)
1085 self.fail(msg)
1086
Michael Foord085dfd32010-06-05 12:17:02 +00001087 def _truncateMessage(self, message, diff):
1088 max_diff = self.maxDiff
1089 if max_diff is None or len(diff) <= max_diff:
1090 return message + diff
Michael Foord9dad32e2010-06-05 13:49:56 +00001091 return message + (DIFF_OMITTED % len(diff))
Michael Foord085dfd32010-06-05 12:17:02 +00001092
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001093 def assertListEqual(self, list1, list2, msg=None):
1094 """A list-specific equality assertion.
1095
1096 Args:
1097 list1: The first list to compare.
1098 list2: The second list to compare.
1099 msg: Optional message to use on failure instead of a list of
1100 differences.
1101
1102 """
1103 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
1104
1105 def assertTupleEqual(self, tuple1, tuple2, msg=None):
1106 """A tuple-specific equality assertion.
1107
1108 Args:
1109 tuple1: The first tuple to compare.
1110 tuple2: The second tuple to compare.
1111 msg: Optional message to use on failure instead of a list of
1112 differences.
1113 """
1114 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
1115
1116 def assertSetEqual(self, set1, set2, msg=None):
1117 """A set-specific equality assertion.
1118
1119 Args:
1120 set1: The first set to compare.
1121 set2: The second set to compare.
1122 msg: Optional message to use on failure instead of a list of
1123 differences.
1124
Michael Foord91c9da32010-03-20 17:21:27 +00001125 assertSetEqual uses ducktyping to support different types of sets, and
1126 is optimized for sets specifically (parameters must support a
1127 difference method).
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001128 """
1129 try:
1130 difference1 = set1.difference(set2)
1131 except TypeError as e:
1132 self.fail('invalid type when attempting set difference: %s' % e)
1133 except AttributeError as e:
1134 self.fail('first argument does not support set difference: %s' % e)
1135
1136 try:
1137 difference2 = set2.difference(set1)
1138 except TypeError as e:
1139 self.fail('invalid type when attempting set difference: %s' % e)
1140 except AttributeError as e:
1141 self.fail('second argument does not support set difference: %s' % e)
1142
1143 if not (difference1 or difference2):
1144 return
1145
1146 lines = []
1147 if difference1:
1148 lines.append('Items in the first set but not the second:')
1149 for item in difference1:
1150 lines.append(repr(item))
1151 if difference2:
1152 lines.append('Items in the second set but not the first:')
1153 for item in difference2:
1154 lines.append(repr(item))
1155
1156 standardMsg = '\n'.join(lines)
1157 self.fail(self._formatMessage(msg, standardMsg))
1158
1159 def assertIn(self, member, container, msg=None):
1160 """Just like self.assertTrue(a in b), but with a nicer default message."""
1161 if member not in container:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001162 standardMsg = '%s not found in %s' % (safe_repr(member),
1163 safe_repr(container))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001164 self.fail(self._formatMessage(msg, standardMsg))
1165
1166 def assertNotIn(self, member, container, msg=None):
1167 """Just like self.assertTrue(a not in b), but with a nicer default message."""
1168 if member in container:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001169 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
1170 safe_repr(container))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001171 self.fail(self._formatMessage(msg, standardMsg))
1172
1173 def assertIs(self, expr1, expr2, msg=None):
1174 """Just like self.assertTrue(a is b), but with a nicer default message."""
1175 if expr1 is not expr2:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001176 standardMsg = '%s is not %s' % (safe_repr(expr1),
1177 safe_repr(expr2))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001178 self.fail(self._formatMessage(msg, standardMsg))
1179
1180 def assertIsNot(self, expr1, expr2, msg=None):
1181 """Just like self.assertTrue(a is not b), but with a nicer default message."""
1182 if expr1 is expr2:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001183 standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001184 self.fail(self._formatMessage(msg, standardMsg))
1185
1186 def assertDictEqual(self, d1, d2, msg=None):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001187 self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
1188 self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001189
1190 if d1 != d2:
Serhiy Storchaka77622f52013-09-23 23:07:00 +03001191 standardMsg = '%s != %s' % _common_shorten_repr(d1, d2)
Michael Foord085dfd32010-06-05 12:17:02 +00001192 diff = ('\n' + '\n'.join(difflib.ndiff(
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001193 pprint.pformat(d1).splitlines(),
1194 pprint.pformat(d2).splitlines())))
Michael Foordcb11b252010-06-05 13:14:43 +00001195 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001196 self.fail(self._formatMessage(msg, standardMsg))
1197
Ezio Melotti0f535012011-04-03 18:02:13 +03001198 def assertDictContainsSubset(self, subset, dictionary, msg=None):
1199 """Checks whether dictionary is a superset of subset."""
1200 warnings.warn('assertDictContainsSubset is deprecated',
1201 DeprecationWarning)
1202 missing = []
1203 mismatched = []
1204 for key, value in subset.items():
1205 if key not in dictionary:
1206 missing.append(key)
1207 elif value != dictionary[key]:
1208 mismatched.append('%s, expected: %s, actual: %s' %
1209 (safe_repr(key), safe_repr(value),
1210 safe_repr(dictionary[key])))
1211
1212 if not (missing or mismatched):
1213 return
1214
1215 standardMsg = ''
1216 if missing:
1217 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
1218 missing)
1219 if mismatched:
1220 if standardMsg:
1221 standardMsg += '; '
1222 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
1223
1224 self.fail(self._formatMessage(msg, standardMsg))
1225
1226
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001227 def assertCountEqual(self, first, second, msg=None):
jkleint39baace2019-04-23 01:34:29 -07001228 """Asserts that two iterables have the same elements, the same number of
1229 times, without regard to order.
Michael Foord8442a602010-03-20 16:58:04 +00001230
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001231 self.assertEqual(Counter(list(first)),
1232 Counter(list(second)))
Michael Foord8442a602010-03-20 16:58:04 +00001233
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001234 Example:
Michael Foord8442a602010-03-20 16:58:04 +00001235 - [0, 1, 1] and [1, 0, 1] compare equal.
1236 - [0, 0, 1] and [0, 1] compare unequal.
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001237
Michael Foord8442a602010-03-20 16:58:04 +00001238 """
Michael Foorde180d392011-01-28 19:51:48 +00001239 first_seq, second_seq = list(first), list(second)
Michael Foord8442a602010-03-20 16:58:04 +00001240 try:
Michael Foorde180d392011-01-28 19:51:48 +00001241 first = collections.Counter(first_seq)
1242 second = collections.Counter(second_seq)
Michael Foord8442a602010-03-20 16:58:04 +00001243 except TypeError:
Raymond Hettinger6518f5e2010-12-24 00:52:54 +00001244 # Handle case with unhashable elements
Michael Foorde180d392011-01-28 19:51:48 +00001245 differences = _count_diff_all_purpose(first_seq, second_seq)
Michael Foord8442a602010-03-20 16:58:04 +00001246 else:
Michael Foorde180d392011-01-28 19:51:48 +00001247 if first == second:
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001248 return
Michael Foorde180d392011-01-28 19:51:48 +00001249 differences = _count_diff_hashable(first_seq, second_seq)
Michael Foord8442a602010-03-20 16:58:04 +00001250
Raymond Hettinger93e233d2010-12-24 10:02:22 +00001251 if differences:
1252 standardMsg = 'Element counts were not equal:\n'
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001253 lines = ['First has %d, Second has %d: %r' % diff for diff in differences]
Raymond Hettinger93e233d2010-12-24 10:02:22 +00001254 diffMsg = '\n'.join(lines)
1255 standardMsg = self._truncateMessage(standardMsg, diffMsg)
1256 msg = self._formatMessage(msg, standardMsg)
1257 self.fail(msg)
Michael Foord8442a602010-03-20 16:58:04 +00001258
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001259 def assertMultiLineEqual(self, first, second, msg=None):
1260 """Assert that two multi-line strings are equal."""
Ezio Melottib3aedd42010-11-20 19:04:17 +00001261 self.assertIsInstance(first, str, 'First argument is not a string')
1262 self.assertIsInstance(second, str, 'Second argument is not a string')
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001263
1264 if first != second:
Ezio Melottiedd117f2011-04-27 10:20:38 +03001265 # don't use difflib if the strings are too long
1266 if (len(first) > self._diffThreshold or
1267 len(second) > self._diffThreshold):
1268 self._baseAssertEqual(first, second, msg)
Ezio Melottid8b509b2011-09-28 17:37:55 +03001269 firstlines = first.splitlines(keepends=True)
1270 secondlines = second.splitlines(keepends=True)
Michael Foordc653ce32010-07-10 13:52:22 +00001271 if len(firstlines) == 1 and first.strip('\r\n') == first:
1272 firstlines = [first + '\n']
1273 secondlines = [second + '\n']
Serhiy Storchaka77622f52013-09-23 23:07:00 +03001274 standardMsg = '%s != %s' % _common_shorten_repr(first, second)
Michael Foordc653ce32010-07-10 13:52:22 +00001275 diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
Michael Foordcb11b252010-06-05 13:14:43 +00001276 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001277 self.fail(self._formatMessage(msg, standardMsg))
1278
1279 def assertLess(self, a, b, msg=None):
1280 """Just like self.assertTrue(a < b), but with a nicer default message."""
1281 if not a < b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001282 standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001283 self.fail(self._formatMessage(msg, standardMsg))
1284
1285 def assertLessEqual(self, a, b, msg=None):
1286 """Just like self.assertTrue(a <= b), but with a nicer default message."""
1287 if not a <= b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001288 standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001289 self.fail(self._formatMessage(msg, standardMsg))
1290
1291 def assertGreater(self, a, b, msg=None):
1292 """Just like self.assertTrue(a > b), but with a nicer default message."""
1293 if not a > b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001294 standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001295 self.fail(self._formatMessage(msg, standardMsg))
1296
1297 def assertGreaterEqual(self, a, b, msg=None):
1298 """Just like self.assertTrue(a >= b), but with a nicer default message."""
1299 if not a >= b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001300 standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001301 self.fail(self._formatMessage(msg, standardMsg))
1302
1303 def assertIsNone(self, obj, msg=None):
1304 """Same as self.assertTrue(obj is None), with a nicer default message."""
1305 if obj is not None:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001306 standardMsg = '%s is not None' % (safe_repr(obj),)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001307 self.fail(self._formatMessage(msg, standardMsg))
1308
1309 def assertIsNotNone(self, obj, msg=None):
1310 """Included for symmetry with assertIsNone."""
1311 if obj is None:
1312 standardMsg = 'unexpectedly None'
1313 self.fail(self._formatMessage(msg, standardMsg))
1314
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001315 def assertIsInstance(self, obj, cls, msg=None):
1316 """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
1317 default message."""
1318 if not isinstance(obj, cls):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001319 standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001320 self.fail(self._formatMessage(msg, standardMsg))
1321
1322 def assertNotIsInstance(self, obj, cls, msg=None):
1323 """Included for symmetry with assertIsInstance."""
1324 if isinstance(obj, cls):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001325 standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001326 self.fail(self._formatMessage(msg, standardMsg))
1327
Ezio Melottied3a7d22010-12-01 02:32:32 +00001328 def assertRaisesRegex(self, expected_exception, expected_regex,
Serhiy Storchakadf573d62015-05-16 16:29:50 +03001329 *args, **kwargs):
Ezio Melottied3a7d22010-12-01 02:32:32 +00001330 """Asserts that the message in a raised exception matches a regex.
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001331
1332 Args:
1333 expected_exception: Exception class expected to be raised.
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +03001334 expected_regex: Regex (re.Pattern object or string) expected
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001335 to be found in error message.
Serhiy Storchakadf573d62015-05-16 16:29:50 +03001336 args: Function to be called and extra positional args.
1337 kwargs: Extra kwargs.
Ezio Melottib4dc2502011-05-06 15:01:41 +03001338 msg: Optional message used in case of failure. Can only be used
1339 when assertRaisesRegex is used as a context manager.
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001340 """
Serhiy Storchakadf573d62015-05-16 16:29:50 +03001341 context = _AssertRaisesContext(expected_exception, self, expected_regex)
1342 return context.handle('assertRaisesRegex', args, kwargs)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001343
Ezio Melottied3a7d22010-12-01 02:32:32 +00001344 def assertWarnsRegex(self, expected_warning, expected_regex,
Serhiy Storchakadf573d62015-05-16 16:29:50 +03001345 *args, **kwargs):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001346 """Asserts that the message in a triggered warning matches a regexp.
1347 Basic functioning is similar to assertWarns() with the addition
1348 that only warnings whose messages also match the regular expression
1349 are considered successful matches.
1350
1351 Args:
1352 expected_warning: Warning class expected to be triggered.
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +03001353 expected_regex: Regex (re.Pattern object or string) expected
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001354 to be found in error message.
Serhiy Storchakadf573d62015-05-16 16:29:50 +03001355 args: Function to be called and extra positional args.
1356 kwargs: Extra kwargs.
Ezio Melottib4dc2502011-05-06 15:01:41 +03001357 msg: Optional message used in case of failure. Can only be used
1358 when assertWarnsRegex is used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001359 """
Serhiy Storchakadf573d62015-05-16 16:29:50 +03001360 context = _AssertWarnsContext(expected_warning, self, expected_regex)
1361 return context.handle('assertWarnsRegex', args, kwargs)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001362
Ezio Melottied3a7d22010-12-01 02:32:32 +00001363 def assertRegex(self, text, expected_regex, msg=None):
Michael Foorde3ef5f12010-05-08 16:46:14 +00001364 """Fail the test unless the text matches the regular expression."""
Ezio Melottied3a7d22010-12-01 02:32:32 +00001365 if isinstance(expected_regex, (str, bytes)):
Gregory P. Smithed16bf42010-12-16 19:23:05 +00001366 assert expected_regex, "expected_regex must not be empty."
Ezio Melottied3a7d22010-12-01 02:32:32 +00001367 expected_regex = re.compile(expected_regex)
1368 if not expected_regex.search(text):
Robert Collinsbe6caca2015-08-20 11:13:09 +12001369 standardMsg = "Regex didn't match: %r not found in %r" % (
1370 expected_regex.pattern, text)
1371 # _formatMessage ensures the longMessage option is respected
1372 msg = self._formatMessage(msg, standardMsg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001373 raise self.failureException(msg)
1374
Ezio Melotti8f776302010-12-10 02:32:05 +00001375 def assertNotRegex(self, text, unexpected_regex, msg=None):
Michael Foorde3ef5f12010-05-08 16:46:14 +00001376 """Fail the test if the text matches the regular expression."""
Ezio Melottied3a7d22010-12-01 02:32:32 +00001377 if isinstance(unexpected_regex, (str, bytes)):
1378 unexpected_regex = re.compile(unexpected_regex)
1379 match = unexpected_regex.search(text)
Benjamin Petersonb48af542010-04-11 20:43:16 +00001380 if match:
Robert Collinsbe6caca2015-08-20 11:13:09 +12001381 standardMsg = 'Regex matched: %r matches %r in %r' % (
1382 text[match.start() : match.end()],
1383 unexpected_regex.pattern,
1384 text)
1385 # _formatMessage ensures the longMessage option is respected
1386 msg = self._formatMessage(msg, standardMsg)
Benjamin Petersonb48af542010-04-11 20:43:16 +00001387 raise self.failureException(msg)
1388
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001389
Ezio Melottied3a7d22010-12-01 02:32:32 +00001390 def _deprecate(original_func):
1391 def deprecated_func(*args, **kwargs):
1392 warnings.warn(
1393 'Please use {0} instead.'.format(original_func.__name__),
1394 DeprecationWarning, 2)
1395 return original_func(*args, **kwargs)
1396 return deprecated_func
1397
Ezio Melotti361467e2011-04-03 17:37:58 +03001398 # see #9424
Ezio Melotti0f535012011-04-03 18:02:13 +03001399 failUnlessEqual = assertEquals = _deprecate(assertEqual)
1400 failIfEqual = assertNotEquals = _deprecate(assertNotEqual)
1401 failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)
1402 failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
1403 failUnless = assert_ = _deprecate(assertTrue)
1404 failUnlessRaises = _deprecate(assertRaises)
1405 failIf = _deprecate(assertFalse)
Ezio Melottied3a7d22010-12-01 02:32:32 +00001406 assertRaisesRegexp = _deprecate(assertRaisesRegex)
1407 assertRegexpMatches = _deprecate(assertRegex)
Robert Collinsbe6caca2015-08-20 11:13:09 +12001408 assertNotRegexpMatches = _deprecate(assertNotRegex)
Ezio Melottied3a7d22010-12-01 02:32:32 +00001409
1410
1411
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001412class FunctionTestCase(TestCase):
1413 """A test case that wraps a test function.
1414
1415 This is useful for slipping pre-existing test functions into the
1416 unittest framework. Optionally, set-up and tidy-up functions can be
1417 supplied. As with TestCase, the tidy-up ('tearDown') function will
1418 always be called if the set-up ('setUp') function ran successfully.
1419 """
1420
1421 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1422 super(FunctionTestCase, self).__init__()
1423 self._setUpFunc = setUp
1424 self._tearDownFunc = tearDown
1425 self._testFunc = testFunc
1426 self._description = description
1427
1428 def setUp(self):
1429 if self._setUpFunc is not None:
1430 self._setUpFunc()
1431
1432 def tearDown(self):
1433 if self._tearDownFunc is not None:
1434 self._tearDownFunc()
1435
1436 def runTest(self):
1437 self._testFunc()
1438
1439 def id(self):
1440 return self._testFunc.__name__
1441
1442 def __eq__(self, other):
1443 if not isinstance(other, self.__class__):
1444 return NotImplemented
1445
1446 return self._setUpFunc == other._setUpFunc and \
1447 self._tearDownFunc == other._tearDownFunc and \
1448 self._testFunc == other._testFunc and \
1449 self._description == other._description
1450
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001451 def __hash__(self):
1452 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1453 self._testFunc, self._description))
1454
1455 def __str__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001456 return "%s (%s)" % (strclass(self.__class__),
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001457 self._testFunc.__name__)
1458
1459 def __repr__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001460 return "<%s tec=%s>" % (strclass(self.__class__),
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001461 self._testFunc)
1462
1463 def shortDescription(self):
1464 if self._description is not None:
1465 return self._description
1466 doc = self._testFunc.__doc__
1467 return doc and doc.split("\n")[0].strip() or None
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001468
1469
1470class _SubTest(TestCase):
1471
1472 def __init__(self, test_case, message, params):
1473 super().__init__()
1474 self._message = message
1475 self.test_case = test_case
1476 self.params = params
1477 self.failureException = test_case.failureException
1478
1479 def runTest(self):
1480 raise NotImplementedError("subtests cannot be run directly")
1481
1482 def _subDescription(self):
1483 parts = []
Berker Peksag16ea19f2016-09-21 19:34:15 +03001484 if self._message is not _subtest_msg_sentinel:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001485 parts.append("[{}]".format(self._message))
1486 if self.params:
1487 params_desc = ', '.join(
1488 "{}={!r}".format(k, v)
Serhiy Storchaka48fbe522017-06-23 21:47:39 +03001489 for (k, v) in self.params.items())
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001490 parts.append("({})".format(params_desc))
1491 return " ".join(parts) or '(<subtest>)'
1492
1493 def id(self):
1494 return "{} {}".format(self.test_case.id(), self._subDescription())
1495
1496 def shortDescription(self):
1497 """Returns a one-line description of the subtest, or None if no
1498 description has been provided.
1499 """
1500 return self.test_case.shortDescription()
1501
1502 def __str__(self):
1503 return "{} {}".format(self.test_case, self._subDescription())