Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1 | """Test case implementation""" |
| 2 | |
| 3 | import sys |
| 4 | import functools |
| 5 | import difflib |
Antoine Pitrou | 0715b9f | 2013-09-14 19:45:47 +0200 | [diff] [blame] | 6 | import logging |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 7 | import pprint |
| 8 | import re |
| 9 | import warnings |
Raymond Hettinger | 6e165b3 | 2010-11-27 09:31:37 +0000 | [diff] [blame] | 10 | import collections |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 11 | import contextlib |
Antoine Pitrou | 9681022 | 2014-04-29 01:23:50 +0200 | [diff] [blame] | 12 | import traceback |
Naitree Zhu | d5fd75c | 2019-09-09 22:06:48 +0800 | [diff] [blame] | 13 | import types |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 14 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 15 | from . import result |
Florent Xicluna | c53ae58 | 2011-11-04 08:25:54 +0100 | [diff] [blame] | 16 | from .util import (strclass, safe_repr, _count_diff_all_purpose, |
Serhiy Storchaka | 77622f5 | 2013-09-23 23:07:00 +0300 | [diff] [blame] | 17 | _count_diff_hashable, _common_shorten_repr) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 18 | |
Benjamin Peterson | dccc1fc | 2010-03-22 00:15:53 +0000 | [diff] [blame] | 19 | __unittest = True |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 20 | |
Berker Peksag | 16ea19f | 2016-09-21 19:34:15 +0300 | [diff] [blame] | 21 | _subtest_msg_sentinel = object() |
Michael Foord | 9dad32e | 2010-06-05 13:49:56 +0000 | [diff] [blame] | 22 | |
| 23 | DIFF_OMITTED = ('\nDiff is %s characters long. ' |
| 24 | 'Set self.maxDiff to None to see it.') |
| 25 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 26 | class SkipTest(Exception): |
| 27 | """ |
| 28 | Raise this exception in a test to skip it. |
| 29 | |
Ezio Melotti | 265281a | 2013-03-27 20:11:55 +0200 | [diff] [blame] | 30 | Usually you can use TestCase.skipTest() or one of the skipping decorators |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 31 | instead of raising this directly. |
| 32 | """ |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 33 | |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 34 | class _ShouldStop(Exception): |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 35 | """ |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 36 | The test should stop. |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 37 | """ |
| 38 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 39 | class _UnexpectedSuccess(Exception): |
| 40 | """ |
| 41 | The test was supposed to fail, but it didn't! |
| 42 | """ |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 43 | |
| 44 | |
| 45 | class _Outcome(object): |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 46 | def __init__(self, result=None): |
| 47 | self.expecting_failure = False |
| 48 | self.result = result |
| 49 | self.result_supports_subtests = hasattr(result, "addSubTest") |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 50 | self.success = True |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 51 | self.skipped = [] |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 52 | self.expectedFailure = None |
| 53 | self.errors = [] |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 54 | |
| 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 Stinner | 031bd53 | 2013-12-09 01:52:50 +0100 | [diff] [blame] | 75 | # explicitly break a reference cycle: |
| 76 | # exc_info -> frame -> exc_info |
| 77 | exc_info = None |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 78 | 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 Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 83 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 84 | |
| 85 | def _id(obj): |
| 86 | return obj |
| 87 | |
Lisa Roach | 0f221d0 | 2018-11-08 18:34:33 -0800 | [diff] [blame] | 88 | |
| 89 | _module_cleanups = [] |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 90 | def addModuleCleanup(function, /, *args, **kwargs): |
Lisa Roach | 0f221d0 | 2018-11-08 18:34:33 -0800 | [diff] [blame] | 91 | """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 | |
| 96 | def 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 112 | def skip(reason): |
| 113 | """ |
| 114 | Unconditionally skip a test. |
| 115 | """ |
| 116 | def decorator(test_item): |
Antoine Pitrou | b05ac86 | 2012-04-25 14:56:46 +0200 | [diff] [blame] | 117 | if not isinstance(test_item, type): |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 118 | @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 Zhu | d5fd75c | 2019-09-09 22:06:48 +0800 | [diff] [blame] | 126 | if isinstance(reason, types.FunctionType): |
| 127 | test_item = reason |
| 128 | reason = '' |
| 129 | return decorator(test_item) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 130 | return decorator |
| 131 | |
| 132 | def 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 | |
| 140 | def 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 Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 148 | def expectedFailure(test_item): |
| 149 | test_item.__unittest_expecting_failure__ = True |
| 150 | return test_item |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 151 | |
Serhiy Storchaka | 041dd8e | 2015-05-21 20:15:40 +0300 | [diff] [blame] | 152 | def _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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 156 | |
Antoine Pitrou | 0715b9f | 2013-09-14 19:45:47 +0200 | [diff] [blame] | 157 | class _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 Pitrou | 0715b9f | 2013-09-14 19:45:47 +0200 | [diff] [blame] | 166 | class _AssertRaisesBaseContext(_BaseTestCaseContext): |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 167 | |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 168 | def __init__(self, expected, test_case, expected_regex=None): |
Antoine Pitrou | 0715b9f | 2013-09-14 19:45:47 +0200 | [diff] [blame] | 169 | _BaseTestCaseContext.__init__(self, test_case) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 170 | self.expected = expected |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 171 | self.test_case = test_case |
R David Murray | ef1c267 | 2014-03-25 15:31:50 -0400 | [diff] [blame] | 172 | if expected_regex is not None: |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 173 | expected_regex = re.compile(expected_regex) |
| 174 | self.expected_regex = expected_regex |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 175 | self.obj_name = None |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 176 | self.msg = None |
| 177 | |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 178 | def handle(self, name, args, kwargs): |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 179 | """ |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 180 | If args is empty, assertRaises/Warns is being used as a |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 181 | context manager, so check for a 'msg' kwarg and return self. |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 182 | If args is not empty, call a callable passing positional and keyword |
| 183 | arguments. |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 184 | """ |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 185 | try: |
Victor Stinner | bbd3cf8 | 2017-03-28 00:56:28 +0200 | [diff] [blame] | 186 | 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 Stinner | bbd3cf8 | 2017-03-28 00:56:28 +0200 | [diff] [blame] | 189 | if not args: |
| 190 | self.msg = kwargs.pop('msg', None) |
| 191 | if kwargs: |
Serhiy Storchaka | 77d5781 | 2018-08-19 10:00:11 +0300 | [diff] [blame] | 192 | raise TypeError('%r is an invalid keyword argument for ' |
| 193 | 'this function' % (next(iter(kwargs)),)) |
Victor Stinner | bbd3cf8 | 2017-03-28 00:56:28 +0200 | [diff] [blame] | 194 | 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 Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 206 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 207 | |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 208 | class _AssertRaisesContext(_AssertRaisesBaseContext): |
| 209 | """A context manager used to implement TestCase.assertRaises* methods.""" |
| 210 | |
Serhiy Storchaka | 041dd8e | 2015-05-21 20:15:40 +0300 | [diff] [blame] | 211 | _base_type = BaseException |
| 212 | _base_type_str = 'an exception type or tuple of exception types' |
| 213 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 214 | def __enter__(self): |
Ezio Melotti | 4900823 | 2010-02-08 21:57:48 +0000 | [diff] [blame] | 215 | return self |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 216 | |
| 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 Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 224 | self._raiseFailure("{} not raised by {}".format(exc_name, |
| 225 | self.obj_name)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 226 | else: |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 227 | self._raiseFailure("{} not raised".format(exc_name)) |
Antoine Pitrou | 9681022 | 2014-04-29 01:23:50 +0200 | [diff] [blame] | 228 | else: |
| 229 | traceback.clear_frames(tb) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 230 | if not issubclass(exc_type, self.expected): |
| 231 | # let unexpected exceptions pass through |
| 232 | return False |
Ezio Melotti | 4900823 | 2010-02-08 21:57:48 +0000 | [diff] [blame] | 233 | # store exception, without traceback, for later retrieval |
| 234 | self.exception = exc_value.with_traceback(None) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 235 | if self.expected_regex is None: |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 236 | return True |
| 237 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 238 | expected_regex = self.expected_regex |
| 239 | if not expected_regex.search(str(exc_value)): |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 240 | self._raiseFailure('"{}" does not match "{}"'.format( |
| 241 | expected_regex.pattern, str(exc_value))) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 242 | return True |
| 243 | |
Batuhan TaÅŸkaya | 0361556 | 2020-04-10 17:46:36 +0300 | [diff] [blame^] | 244 | __class_getitem__ = classmethod(types.GenericAlias) |
| 245 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 246 | |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 247 | class _AssertWarnsContext(_AssertRaisesBaseContext): |
| 248 | """A context manager used to implement TestCase.assertWarns* methods.""" |
| 249 | |
Serhiy Storchaka | 041dd8e | 2015-05-21 20:15:40 +0300 | [diff] [blame] | 250 | _base_type = Warning |
| 251 | _base_type_str = 'a warning type or tuple of warning types' |
| 252 | |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 253 | 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 Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 280 | if (self.expected_regex is not None and |
| 281 | not self.expected_regex.search(str(w))): |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 282 | 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 Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 290 | self._raiseFailure('"{}" does not match "{}"'.format( |
| 291 | self.expected_regex.pattern, str(first_matching))) |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 292 | if self.obj_name: |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 293 | self._raiseFailure("{} not triggered by {}".format(exc_name, |
| 294 | self.obj_name)) |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 295 | else: |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 296 | self._raiseFailure("{} not triggered".format(exc_name)) |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 297 | |
| 298 | |
Antoine Pitrou | 0715b9f | 2013-09-14 19:45:47 +0200 | [diff] [blame] | 299 | |
| 300 | _LoggingWatcher = collections.namedtuple("_LoggingWatcher", |
| 301 | ["records", "output"]) |
| 302 | |
| 303 | |
| 304 | class _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 | |
| 323 | class _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 Storchaka | 48fbe52 | 2017-06-23 21:47:39 +0300 | [diff] [blame] | 367 | class _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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 377 | class 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 397 | |
Ezio Melotti | 31797e5 | 2013-03-29 03:42:29 +0200 | [diff] [blame] | 398 | 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 409 | |
| 410 | failureException = AssertionError |
| 411 | |
Michael Foord | 5074df6 | 2010-12-03 00:53:09 +0000 | [diff] [blame] | 412 | longMessage = True |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 413 | |
Michael Foord | 085dfd3 | 2010-06-05 12:17:02 +0000 | [diff] [blame] | 414 | maxDiff = 80*8 |
| 415 | |
Ezio Melotti | edd117f | 2011-04-27 10:20:38 +0300 | [diff] [blame] | 416 | # If a string is longer than _diffThreshold, use normal comparison instead |
| 417 | # of difflib. See #11763. |
| 418 | _diffThreshold = 2**16 |
| 419 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 420 | # Attribute used by TestSuite for classSetUp |
| 421 | |
| 422 | _classSetupFailed = False |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 423 | |
Lisa Roach | 0f221d0 | 2018-11-08 18:34:33 -0800 | [diff] [blame] | 424 | _class_cleanups = [] |
| 425 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 426 | 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 Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 432 | self._outcome = None |
Michael Foord | 32e1d83 | 2011-01-03 17:00:11 +0000 | [diff] [blame] | 433 | self._testMethodDoc = 'No test' |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 434 | try: |
| 435 | testMethod = getattr(self, methodName) |
| 436 | except AttributeError: |
Michael Foord | 32e1d83 | 2011-01-03 17:00:11 +0000 | [diff] [blame] | 437 | 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 444 | self._cleanups = [] |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 445 | self._subtest = None |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 446 | |
| 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 Peterson | 34b2b26 | 2011-07-12 19:21:42 -0500 | [diff] [blame] | 450 | self._type_equality_funcs = {} |
Michael Foord | 8ca6d98 | 2010-11-20 15:34:26 +0000 | [diff] [blame] | 451 | 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 457 | |
| 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 Peterson | 8f326b2 | 2009-12-13 02:10:36 +0000 | [diff] [blame] | 471 | self._type_equality_funcs[typeobj] = function |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 472 | |
Serhiy Storchaka | 142566c | 2019-06-05 18:22:31 +0300 | [diff] [blame] | 473 | def addCleanup(self, function, /, *args, **kwargs): |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 474 | """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 Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 481 | @classmethod |
| 482 | def addClassCleanup(cls, function, /, *args, **kwargs): |
Lisa Roach | 0f221d0 | 2018-11-08 18:34:33 -0800 | [diff] [blame] | 483 | """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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 487 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 495 | @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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 503 | def countTestCases(self): |
| 504 | return 1 |
| 505 | |
| 506 | def defaultTestResult(self): |
| 507 | return result.TestResult() |
| 508 | |
| 509 | def shortDescription(self): |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 510 | """Returns a one-line description of the test, or None if no |
| 511 | description has been provided. |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 512 | |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 513 | The default implementation of this method returns the first line of |
| 514 | the specified test method's docstring. |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 515 | """ |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 516 | doc = self._testMethodDoc |
Steve Cirelli | 032de73 | 2020-02-03 02:06:50 -0500 | [diff] [blame] | 517 | return doc.strip().split("\n")[0].strip() if doc else None |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 518 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 519 | |
| 520 | def id(self): |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 521 | return "%s.%s" % (strclass(self.__class__), self._testMethodName) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 522 | |
| 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 529 | def __hash__(self): |
| 530 | return hash((type(self), self._testMethodName)) |
| 531 | |
| 532 | def __str__(self): |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 533 | return "%s (%s)" % (self._testMethodName, strclass(self.__class__)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 534 | |
| 535 | def __repr__(self): |
| 536 | return "<%s testMethod=%s>" % \ |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 537 | (strclass(self.__class__), self._testMethodName) |
| 538 | |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 539 | def _addSkip(self, result, test_case, reason): |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 540 | addSkip = getattr(result, 'addSkip', None) |
| 541 | if addSkip is not None: |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 542 | addSkip(test_case, reason) |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 543 | else: |
| 544 | warnings.warn("TestResult has no addSkip method, skips not reported", |
| 545 | RuntimeWarning, 2) |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 546 | result.addSuccess(test_case) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 547 | |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 548 | @contextlib.contextmanager |
Berker Peksag | 16ea19f | 2016-09-21 19:34:15 +0300 | [diff] [blame] | 549 | def subTest(self, msg=_subtest_msg_sentinel, **params): |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 550 | """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 Oliveira | da2bf9f | 2018-10-12 07:35:55 -0300 | [diff] [blame] | 556 | if self._outcome is None or not self._outcome.result_supports_subtests: |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 557 | yield |
| 558 | return |
| 559 | parent = self._subtest |
| 560 | if parent is None: |
Serhiy Storchaka | 48fbe52 | 2017-06-23 21:47:39 +0300 | [diff] [blame] | 561 | params_map = _OrderedChainMap(params) |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 562 | else: |
| 563 | params_map = parent.params.new_child(params) |
| 564 | self._subtest = _SubTest(self, msg, params_map) |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 565 | try: |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 566 | 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 Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 613 | |
Andrew Svetlov | 4dd3e3f | 2019-05-29 12:33:59 +0300 | [diff] [blame] | 614 | 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 626 | 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 634 | result.startTest(self) |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 635 | |
| 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 640 | try: |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 641 | skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') |
| 642 | or getattr(testMethod, '__unittest_skip_why__', '')) |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 643 | self._addSkip(result, self, skip_why) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 644 | finally: |
| 645 | result.stopTest(self) |
| 646 | return |
Robert Collins | ed599b7 | 2015-08-28 10:34:51 +1200 | [diff] [blame] | 647 | 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 Stinner | 031bd53 | 2013-12-09 01:52:50 +0100 | [diff] [blame] | 652 | outcome = _Outcome(result) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 653 | try: |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 654 | self._outcome = outcome |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 655 | |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 656 | with outcome.testPartExecutor(self): |
Andrew Svetlov | 4dd3e3f | 2019-05-29 12:33:59 +0300 | [diff] [blame] | 657 | self._callSetUp() |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 658 | if outcome.success: |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 659 | outcome.expecting_failure = expecting_failure |
| 660 | with outcome.testPartExecutor(self, isTest=True): |
Andrew Svetlov | 4dd3e3f | 2019-05-29 12:33:59 +0300 | [diff] [blame] | 661 | self._callTestMethod(testMethod) |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 662 | outcome.expecting_failure = False |
| 663 | with outcome.testPartExecutor(self): |
Andrew Svetlov | 4dd3e3f | 2019-05-29 12:33:59 +0300 | [diff] [blame] | 664 | self._callTearDown() |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 665 | |
| 666 | self.doCleanups() |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 667 | for test, reason in outcome.skipped: |
| 668 | self._addSkip(result, test, reason) |
| 669 | self._feedErrorsToResult(result, outcome.errors) |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 670 | if outcome.success: |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 671 | if expecting_failure: |
| 672 | if outcome.expectedFailure: |
| 673 | self._addExpectedFailure(result, outcome.expectedFailure) |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 674 | else: |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 675 | self._addUnexpectedSuccess(result) |
| 676 | else: |
| 677 | result.addSuccess(self) |
Michael Foord | 1341bb0 | 2011-03-14 19:01:46 -0400 | [diff] [blame] | 678 | return result |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 679 | 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 Stinner | 031bd53 | 2013-12-09 01:52:50 +0100 | [diff] [blame] | 686 | # 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 695 | def doCleanups(self): |
| 696 | """Execute all cleanup functions. Normally called for you after |
| 697 | tearDown.""" |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 698 | outcome = self._outcome or _Outcome() |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 699 | while self._cleanups: |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 700 | function, args, kwargs = self._cleanups.pop() |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 701 | with outcome.testPartExecutor(self): |
Andrew Svetlov | 4dd3e3f | 2019-05-29 12:33:59 +0300 | [diff] [blame] | 702 | self._callCleanup(function, *args, **kwargs) |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 703 | |
| 704 | # return this for backwards compatibility |
Lisa Roach | 0f221d0 | 2018-11-08 18:34:33 -0800 | [diff] [blame] | 705 | # even though we no longer use it internally |
Michael Foord | b3468f7 | 2010-12-19 03:19:47 +0000 | [diff] [blame] | 706 | return outcome.success |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 707 | |
Lisa Roach | 0f221d0 | 2018-11-08 18:34:33 -0800 | [diff] [blame] | 708 | @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 Galindo | 293dd23 | 2019-11-19 21:34:03 +0000 | [diff] [blame] | 717 | except Exception: |
Lisa Roach | 0f221d0 | 2018-11-08 18:34:33 -0800 | [diff] [blame] | 718 | cls.tearDown_exceptions.append(sys.exc_info()) |
| 719 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 720 | 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 Foord | b874874 | 2010-06-10 16:16:08 +0000 | [diff] [blame] | 728 | while self._cleanups: |
| 729 | function, args, kwargs = self._cleanups.pop(-1) |
| 730 | function(*args, **kwargs) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 731 | |
| 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 Melotti | 3044fa7 | 2010-12-18 17:31:58 +0000 | [diff] [blame] | 741 | """Check that the expression is false.""" |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 742 | if expr: |
Ezio Melotti | 3044fa7 | 2010-12-18 17:31:58 +0000 | [diff] [blame] | 743 | msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 744 | raise self.failureException(msg) |
| 745 | |
| 746 | def assertTrue(self, expr, msg=None): |
Ezio Melotti | 3044fa7 | 2010-12-18 17:31:58 +0000 | [diff] [blame] | 747 | """Check that the expression is true.""" |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 748 | if not expr: |
Ezio Melotti | 3044fa7 | 2010-12-18 17:31:58 +0000 | [diff] [blame] | 749 | msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 750 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 766 | 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 772 | |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 773 | 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 Svetlov | 737fb89 | 2012-12-18 21:14:22 +0200 | [diff] [blame] | 777 | raised, it will not be caught, and the test case will be |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 778 | deemed to have suffered an error, exactly as for an |
| 779 | unexpected exception. |
| 780 | |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 781 | If called with the callable and arguments omitted, will return a |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 782 | context object used like this:: |
| 783 | |
Michael Foord | 1c42b12 | 2010-02-05 22:58:21 +0000 | [diff] [blame] | 784 | with self.assertRaises(SomeException): |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 785 | do_something() |
Michael Foord | 1c42b12 | 2010-02-05 22:58:21 +0000 | [diff] [blame] | 786 | |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 787 | An optional keyword argument 'msg' can be provided when assertRaises |
| 788 | is used as a context object. |
| 789 | |
Michael Foord | 1c42b12 | 2010-02-05 22:58:21 +0000 | [diff] [blame] | 790 | The context manager keeps a reference to the exception as |
Ezio Melotti | 4900823 | 2010-02-08 21:57:48 +0000 | [diff] [blame] | 791 | the 'exception' attribute. This allows you to inspect the |
Michael Foord | 1c42b12 | 2010-02-05 22:58:21 +0000 | [diff] [blame] | 792 | exception after the assertion:: |
| 793 | |
| 794 | with self.assertRaises(SomeException) as cm: |
| 795 | do_something() |
Ezio Melotti | 4900823 | 2010-02-08 21:57:48 +0000 | [diff] [blame] | 796 | the_exception = cm.exception |
Michael Foord | b57ac6d | 2010-02-05 23:26:29 +0000 | [diff] [blame] | 797 | self.assertEqual(the_exception.error_code, 3) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 798 | """ |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 799 | context = _AssertRaisesContext(expected_exception, self) |
Victor Stinner | bbd3cf8 | 2017-03-28 00:56:28 +0200 | [diff] [blame] | 800 | try: |
| 801 | return context.handle('assertRaises', args, kwargs) |
| 802 | finally: |
| 803 | # bpo-23890: manually break a reference cycle |
| 804 | context = None |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 805 | |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 806 | def assertWarns(self, expected_warning, *args, **kwargs): |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 807 | """Fail unless a warning of class warnClass is triggered |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 808 | by the callable when invoked with specified positional and |
| 809 | keyword arguments. If a different type of warning is |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 810 | 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 Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 814 | If called with the callable and arguments omitted, will return a |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 815 | context object used like this:: |
| 816 | |
| 817 | with self.assertWarns(SomeWarning): |
| 818 | do_something() |
| 819 | |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 820 | An optional keyword argument 'msg' can be provided when assertWarns |
| 821 | is used as a context object. |
| 822 | |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 823 | 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 Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 834 | context = _AssertWarnsContext(expected_warning, self) |
| 835 | return context.handle('assertWarns', args, kwargs) |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 836 | |
Antoine Pitrou | 0715b9f | 2013-09-14 19:45:47 +0200 | [diff] [blame] | 837 | 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 859 | 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 Peterson | 34b2b26 | 2011-07-12 19:21:42 -0500 | [diff] [blame] | 879 | if isinstance(asserter, str): |
| 880 | asserter = getattr(self, asserter) |
Benjamin Peterson | 8f326b2 | 2009-12-13 02:10:36 +0000 | [diff] [blame] | 881 | return asserter |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 882 | |
| 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 Storchaka | 77622f5 | 2013-09-23 23:07:00 +0300 | [diff] [blame] | 888 | standardMsg = '%s != %s' % _common_shorten_repr(first, second) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 889 | 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 Melotti | 90eea97 | 2012-11-08 11:08:39 +0200 | [diff] [blame] | 900 | """Fail if the two objects are equal as determined by the '!=' |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 901 | operator. |
| 902 | """ |
| 903 | if not first != second: |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 904 | msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first), |
| 905 | safe_repr(second))) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 906 | raise self.failureException(msg) |
| 907 | |
Michael Foord | 321d059 | 2010-11-02 13:44:51 +0000 | [diff] [blame] | 908 | def assertAlmostEqual(self, first, second, places=None, msg=None, |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 909 | delta=None): |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 910 | """Fail if the two objects are unequal as determined by their |
| 911 | difference rounded to the given number of decimal places |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 912 | (default 7) and comparing to zero, or by comparing that the |
Ron | 032a648 | 2017-10-18 20:01:23 +0300 | [diff] [blame] | 913 | difference between the two objects is more than the given |
| 914 | delta. |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 915 | |
| 916 | Note that decimal places (from zero) are usually not the same |
Martin Panter | eb99570 | 2016-07-28 01:11:04 +0000 | [diff] [blame] | 917 | as significant digits (measured from the most significant digit). |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 918 | |
| 919 | If the two objects compare equal then they will automatically |
| 920 | compare almost equal. |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 921 | """ |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 922 | if first == second: |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 923 | # shortcut |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 924 | return |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 925 | if delta is not None and places is not None: |
| 926 | raise TypeError("specify delta or places not both") |
| 927 | |
Giampaolo Rodola | 5d7a8d0 | 2017-05-01 18:18:56 +0200 | [diff] [blame] | 928 | diff = abs(first - second) |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 929 | if delta is not None: |
Giampaolo Rodola | 5d7a8d0 | 2017-05-01 18:18:56 +0200 | [diff] [blame] | 930 | if diff <= delta: |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 931 | return |
| 932 | |
Giampaolo Rodola | 5d7a8d0 | 2017-05-01 18:18:56 +0200 | [diff] [blame] | 933 | 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 Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 938 | else: |
| 939 | if places is None: |
| 940 | places = 7 |
| 941 | |
Giampaolo Rodola | 5d7a8d0 | 2017-05-01 18:18:56 +0200 | [diff] [blame] | 942 | if round(diff, places) == 0: |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 943 | return |
| 944 | |
Giampaolo Rodola | 5d7a8d0 | 2017-05-01 18:18:56 +0200 | [diff] [blame] | 945 | standardMsg = '%s != %s within %r places (%s difference)' % ( |
| 946 | safe_repr(first), |
| 947 | safe_repr(second), |
| 948 | places, |
| 949 | safe_repr(diff)) |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 950 | msg = self._formatMessage(msg, standardMsg) |
| 951 | raise self.failureException(msg) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 952 | |
Michael Foord | 321d059 | 2010-11-02 13:44:51 +0000 | [diff] [blame] | 953 | def assertNotAlmostEqual(self, first, second, places=None, msg=None, |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 954 | delta=None): |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 955 | """Fail if the two objects are equal as determined by their |
| 956 | difference rounded to the given number of decimal places |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 957 | (default 7) and comparing to zero, or by comparing that the |
Ron | 032a648 | 2017-10-18 20:01:23 +0300 | [diff] [blame] | 958 | difference between the two objects is less than the given delta. |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 959 | |
| 960 | Note that decimal places (from zero) are usually not the same |
Martin Panter | eb99570 | 2016-07-28 01:11:04 +0000 | [diff] [blame] | 961 | as significant digits (measured from the most significant digit). |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 962 | |
| 963 | Objects that are equal automatically fail. |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 964 | """ |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 965 | if delta is not None and places is not None: |
| 966 | raise TypeError("specify delta or places not both") |
Giampaolo Rodola | 5d7a8d0 | 2017-05-01 18:18:56 +0200 | [diff] [blame] | 967 | diff = abs(first - second) |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 968 | if delta is not None: |
Giampaolo Rodola | 5d7a8d0 | 2017-05-01 18:18:56 +0200 | [diff] [blame] | 969 | if not (first == second) and diff > delta: |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 970 | return |
Giampaolo Rodola | 5d7a8d0 | 2017-05-01 18:18:56 +0200 | [diff] [blame] | 971 | 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 Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 976 | else: |
| 977 | if places is None: |
| 978 | places = 7 |
Giampaolo Rodola | 5d7a8d0 | 2017-05-01 18:18:56 +0200 | [diff] [blame] | 979 | if not (first == second) and round(diff, places) != 0: |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 980 | return |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 981 | standardMsg = '%s == %s within %r places' % (safe_repr(first), |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 982 | safe_repr(second), |
| 983 | places) |
| 984 | |
| 985 | msg = self._formatMessage(msg, standardMsg) |
| 986 | raise self.failureException(msg) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 987 | |
Michael Foord | 085dfd3 | 2010-06-05 12:17:02 +0000 | [diff] [blame] | 988 | def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 989 | """An equality assertion for ordered sequences (like lists and tuples). |
| 990 | |
R. David Murray | ad13f22 | 2010-01-29 22:17:58 +0000 | [diff] [blame] | 991 | For the purposes of this function, a valid ordered sequence type is one |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 992 | 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 Peterson | b29614e | 2012-10-09 11:16:03 -0400 | [diff] [blame] | 1002 | if seq_type is not None: |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1003 | seq_type_name = seq_type.__name__ |
| 1004 | if not isinstance(seq1, seq_type): |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1005 | raise self.failureException('First sequence is not a %s: %s' |
| 1006 | % (seq_type_name, safe_repr(seq1))) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1007 | if not isinstance(seq2, seq_type): |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1008 | raise self.failureException('Second sequence is not a %s: %s' |
| 1009 | % (seq_type_name, safe_repr(seq2))) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1010 | 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 Storchaka | 77622f5 | 2013-09-23 23:07:00 +0300 | [diff] [blame] | 1031 | differing = '%ss differ: %s != %s\n' % ( |
| 1032 | (seq_type_name.capitalize(),) + |
| 1033 | _common_shorten_repr(seq1, seq2)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1034 | |
| 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 Storchaka | 685fbed | 2016-04-25 08:58:25 +0300 | [diff] [blame] | 1052 | ((i,) + _common_shorten_repr(item1, item2))) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1053 | 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 Storchaka | 685fbed | 2016-04-25 08:58:25 +0300 | [diff] [blame] | 1065 | (len2, safe_repr(seq1[len2]))) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1066 | 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 Storchaka | 685fbed | 2016-04-25 08:58:25 +0300 | [diff] [blame] | 1074 | (len1, safe_repr(seq2[len1]))) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1075 | except (TypeError, IndexError, NotImplementedError): |
| 1076 | differing += ('Unable to index element %d ' |
| 1077 | 'of second %s\n' % (len1, seq_type_name)) |
Michael Foord | 2034d9a | 2010-06-05 11:27:52 +0000 | [diff] [blame] | 1078 | standardMsg = differing |
| 1079 | diffMsg = '\n' + '\n'.join( |
Benjamin Peterson | 6e8c757 | 2009-10-04 20:19:21 +0000 | [diff] [blame] | 1080 | difflib.ndiff(pprint.pformat(seq1).splitlines(), |
| 1081 | pprint.pformat(seq2).splitlines())) |
Michael Foord | 085dfd3 | 2010-06-05 12:17:02 +0000 | [diff] [blame] | 1082 | |
| 1083 | standardMsg = self._truncateMessage(standardMsg, diffMsg) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1084 | msg = self._formatMessage(msg, standardMsg) |
| 1085 | self.fail(msg) |
| 1086 | |
Michael Foord | 085dfd3 | 2010-06-05 12:17:02 +0000 | [diff] [blame] | 1087 | 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 Foord | 9dad32e | 2010-06-05 13:49:56 +0000 | [diff] [blame] | 1091 | return message + (DIFF_OMITTED % len(diff)) |
Michael Foord | 085dfd3 | 2010-06-05 12:17:02 +0000 | [diff] [blame] | 1092 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1093 | 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 Foord | 91c9da3 | 2010-03-20 17:21:27 +0000 | [diff] [blame] | 1125 | assertSetEqual uses ducktyping to support different types of sets, and |
| 1126 | is optimized for sets specifically (parameters must support a |
| 1127 | difference method). |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1128 | """ |
| 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1162 | standardMsg = '%s not found in %s' % (safe_repr(member), |
| 1163 | safe_repr(container)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1164 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1169 | standardMsg = '%s unexpectedly found in %s' % (safe_repr(member), |
| 1170 | safe_repr(container)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1171 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1176 | standardMsg = '%s is not %s' % (safe_repr(expr1), |
| 1177 | safe_repr(expr2)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1178 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1183 | standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1184 | self.fail(self._formatMessage(msg, standardMsg)) |
| 1185 | |
| 1186 | def assertDictEqual(self, d1, d2, msg=None): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1187 | self.assertIsInstance(d1, dict, 'First argument is not a dictionary') |
| 1188 | self.assertIsInstance(d2, dict, 'Second argument is not a dictionary') |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1189 | |
| 1190 | if d1 != d2: |
Serhiy Storchaka | 77622f5 | 2013-09-23 23:07:00 +0300 | [diff] [blame] | 1191 | standardMsg = '%s != %s' % _common_shorten_repr(d1, d2) |
Michael Foord | 085dfd3 | 2010-06-05 12:17:02 +0000 | [diff] [blame] | 1192 | diff = ('\n' + '\n'.join(difflib.ndiff( |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1193 | pprint.pformat(d1).splitlines(), |
| 1194 | pprint.pformat(d2).splitlines()))) |
Michael Foord | cb11b25 | 2010-06-05 13:14:43 +0000 | [diff] [blame] | 1195 | standardMsg = self._truncateMessage(standardMsg, diff) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1196 | self.fail(self._formatMessage(msg, standardMsg)) |
| 1197 | |
Ezio Melotti | 0f53501 | 2011-04-03 18:02:13 +0300 | [diff] [blame] | 1198 | 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 Hettinger | 57bd00a | 2010-12-24 21:51:48 +0000 | [diff] [blame] | 1227 | def assertCountEqual(self, first, second, msg=None): |
jkleint | 39baace | 2019-04-23 01:34:29 -0700 | [diff] [blame] | 1228 | """Asserts that two iterables have the same elements, the same number of |
| 1229 | times, without regard to order. |
Michael Foord | 8442a60 | 2010-03-20 16:58:04 +0000 | [diff] [blame] | 1230 | |
Raymond Hettinger | 57bd00a | 2010-12-24 21:51:48 +0000 | [diff] [blame] | 1231 | self.assertEqual(Counter(list(first)), |
| 1232 | Counter(list(second))) |
Michael Foord | 8442a60 | 2010-03-20 16:58:04 +0000 | [diff] [blame] | 1233 | |
Raymond Hettinger | 57bd00a | 2010-12-24 21:51:48 +0000 | [diff] [blame] | 1234 | Example: |
Michael Foord | 8442a60 | 2010-03-20 16:58:04 +0000 | [diff] [blame] | 1235 | - [0, 1, 1] and [1, 0, 1] compare equal. |
| 1236 | - [0, 0, 1] and [0, 1] compare unequal. |
Raymond Hettinger | 57bd00a | 2010-12-24 21:51:48 +0000 | [diff] [blame] | 1237 | |
Michael Foord | 8442a60 | 2010-03-20 16:58:04 +0000 | [diff] [blame] | 1238 | """ |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1239 | first_seq, second_seq = list(first), list(second) |
Michael Foord | 8442a60 | 2010-03-20 16:58:04 +0000 | [diff] [blame] | 1240 | try: |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1241 | first = collections.Counter(first_seq) |
| 1242 | second = collections.Counter(second_seq) |
Michael Foord | 8442a60 | 2010-03-20 16:58:04 +0000 | [diff] [blame] | 1243 | except TypeError: |
Raymond Hettinger | 6518f5e | 2010-12-24 00:52:54 +0000 | [diff] [blame] | 1244 | # Handle case with unhashable elements |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1245 | differences = _count_diff_all_purpose(first_seq, second_seq) |
Michael Foord | 8442a60 | 2010-03-20 16:58:04 +0000 | [diff] [blame] | 1246 | else: |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1247 | if first == second: |
Raymond Hettinger | 6e165b3 | 2010-11-27 09:31:37 +0000 | [diff] [blame] | 1248 | return |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1249 | differences = _count_diff_hashable(first_seq, second_seq) |
Michael Foord | 8442a60 | 2010-03-20 16:58:04 +0000 | [diff] [blame] | 1250 | |
Raymond Hettinger | 93e233d | 2010-12-24 10:02:22 +0000 | [diff] [blame] | 1251 | if differences: |
| 1252 | standardMsg = 'Element counts were not equal:\n' |
Raymond Hettinger | 57bd00a | 2010-12-24 21:51:48 +0000 | [diff] [blame] | 1253 | lines = ['First has %d, Second has %d: %r' % diff for diff in differences] |
Raymond Hettinger | 93e233d | 2010-12-24 10:02:22 +0000 | [diff] [blame] | 1254 | diffMsg = '\n'.join(lines) |
| 1255 | standardMsg = self._truncateMessage(standardMsg, diffMsg) |
| 1256 | msg = self._formatMessage(msg, standardMsg) |
| 1257 | self.fail(msg) |
Michael Foord | 8442a60 | 2010-03-20 16:58:04 +0000 | [diff] [blame] | 1258 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1259 | def assertMultiLineEqual(self, first, second, msg=None): |
| 1260 | """Assert that two multi-line strings are equal.""" |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1261 | self.assertIsInstance(first, str, 'First argument is not a string') |
| 1262 | self.assertIsInstance(second, str, 'Second argument is not a string') |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1263 | |
| 1264 | if first != second: |
Ezio Melotti | edd117f | 2011-04-27 10:20:38 +0300 | [diff] [blame] | 1265 | # 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 Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 1269 | firstlines = first.splitlines(keepends=True) |
| 1270 | secondlines = second.splitlines(keepends=True) |
Michael Foord | c653ce3 | 2010-07-10 13:52:22 +0000 | [diff] [blame] | 1271 | if len(firstlines) == 1 and first.strip('\r\n') == first: |
| 1272 | firstlines = [first + '\n'] |
| 1273 | secondlines = [second + '\n'] |
Serhiy Storchaka | 77622f5 | 2013-09-23 23:07:00 +0300 | [diff] [blame] | 1274 | standardMsg = '%s != %s' % _common_shorten_repr(first, second) |
Michael Foord | c653ce3 | 2010-07-10 13:52:22 +0000 | [diff] [blame] | 1275 | diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines)) |
Michael Foord | cb11b25 | 2010-06-05 13:14:43 +0000 | [diff] [blame] | 1276 | standardMsg = self._truncateMessage(standardMsg, diff) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1277 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1282 | standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1283 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1288 | standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1289 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1294 | standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1295 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1300 | standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1301 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1306 | standardMsg = '%s is not None' % (safe_repr(obj),) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1307 | 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 Peterson | 6e8c757 | 2009-10-04 20:19:21 +0000 | [diff] [blame] | 1315 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1319 | standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls) |
Benjamin Peterson | 6e8c757 | 2009-10-04 20:19:21 +0000 | [diff] [blame] | 1320 | 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 Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1325 | standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls) |
Benjamin Peterson | 6e8c757 | 2009-10-04 20:19:21 +0000 | [diff] [blame] | 1326 | self.fail(self._formatMessage(msg, standardMsg)) |
| 1327 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1328 | def assertRaisesRegex(self, expected_exception, expected_regex, |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 1329 | *args, **kwargs): |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1330 | """Asserts that the message in a raised exception matches a regex. |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1331 | |
| 1332 | Args: |
| 1333 | expected_exception: Exception class expected to be raised. |
Serhiy Storchaka | 0b5e61d | 2017-10-04 20:09:49 +0300 | [diff] [blame] | 1334 | expected_regex: Regex (re.Pattern object or string) expected |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1335 | to be found in error message. |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 1336 | args: Function to be called and extra positional args. |
| 1337 | kwargs: Extra kwargs. |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 1338 | msg: Optional message used in case of failure. Can only be used |
| 1339 | when assertRaisesRegex is used as a context manager. |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1340 | """ |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 1341 | context = _AssertRaisesContext(expected_exception, self, expected_regex) |
| 1342 | return context.handle('assertRaisesRegex', args, kwargs) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1343 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1344 | def assertWarnsRegex(self, expected_warning, expected_regex, |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 1345 | *args, **kwargs): |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 1346 | """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 Storchaka | 0b5e61d | 2017-10-04 20:09:49 +0300 | [diff] [blame] | 1353 | expected_regex: Regex (re.Pattern object or string) expected |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 1354 | to be found in error message. |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 1355 | args: Function to be called and extra positional args. |
| 1356 | kwargs: Extra kwargs. |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 1357 | msg: Optional message used in case of failure. Can only be used |
| 1358 | when assertWarnsRegex is used as a context manager. |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 1359 | """ |
Serhiy Storchaka | df573d6 | 2015-05-16 16:29:50 +0300 | [diff] [blame] | 1360 | context = _AssertWarnsContext(expected_warning, self, expected_regex) |
| 1361 | return context.handle('assertWarnsRegex', args, kwargs) |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 1362 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1363 | def assertRegex(self, text, expected_regex, msg=None): |
Michael Foord | e3ef5f1 | 2010-05-08 16:46:14 +0000 | [diff] [blame] | 1364 | """Fail the test unless the text matches the regular expression.""" |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1365 | if isinstance(expected_regex, (str, bytes)): |
Gregory P. Smith | ed16bf4 | 2010-12-16 19:23:05 +0000 | [diff] [blame] | 1366 | assert expected_regex, "expected_regex must not be empty." |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1367 | expected_regex = re.compile(expected_regex) |
| 1368 | if not expected_regex.search(text): |
Robert Collins | be6caca | 2015-08-20 11:13:09 +1200 | [diff] [blame] | 1369 | 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1373 | raise self.failureException(msg) |
| 1374 | |
Ezio Melotti | 8f77630 | 2010-12-10 02:32:05 +0000 | [diff] [blame] | 1375 | def assertNotRegex(self, text, unexpected_regex, msg=None): |
Michael Foord | e3ef5f1 | 2010-05-08 16:46:14 +0000 | [diff] [blame] | 1376 | """Fail the test if the text matches the regular expression.""" |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1377 | if isinstance(unexpected_regex, (str, bytes)): |
| 1378 | unexpected_regex = re.compile(unexpected_regex) |
| 1379 | match = unexpected_regex.search(text) |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 1380 | if match: |
Robert Collins | be6caca | 2015-08-20 11:13:09 +1200 | [diff] [blame] | 1381 | 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 Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 1387 | raise self.failureException(msg) |
| 1388 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1389 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1390 | 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 Melotti | 361467e | 2011-04-03 17:37:58 +0300 | [diff] [blame] | 1398 | # see #9424 |
Ezio Melotti | 0f53501 | 2011-04-03 18:02:13 +0300 | [diff] [blame] | 1399 | 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 Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1406 | assertRaisesRegexp = _deprecate(assertRaisesRegex) |
| 1407 | assertRegexpMatches = _deprecate(assertRegex) |
Robert Collins | be6caca | 2015-08-20 11:13:09 +1200 | [diff] [blame] | 1408 | assertNotRegexpMatches = _deprecate(assertNotRegex) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1409 | |
| 1410 | |
| 1411 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1412 | class 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 Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1451 | def __hash__(self): |
| 1452 | return hash((type(self), self._setUpFunc, self._tearDownFunc, |
| 1453 | self._testFunc, self._description)) |
| 1454 | |
| 1455 | def __str__(self): |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1456 | return "%s (%s)" % (strclass(self.__class__), |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1457 | self._testFunc.__name__) |
| 1458 | |
| 1459 | def __repr__(self): |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 1460 | return "<%s tec=%s>" % (strclass(self.__class__), |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1461 | 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 Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 1468 | |
| 1469 | |
| 1470 | class _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 Peksag | 16ea19f | 2016-09-21 19:34:15 +0300 | [diff] [blame] | 1484 | if self._message is not _subtest_msg_sentinel: |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 1485 | parts.append("[{}]".format(self._message)) |
| 1486 | if self.params: |
| 1487 | params_desc = ', '.join( |
| 1488 | "{}={!r}".format(k, v) |
Serhiy Storchaka | 48fbe52 | 2017-06-23 21:47:39 +0300 | [diff] [blame] | 1489 | for (k, v) in self.params.items()) |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 1490 | 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()) |