| 1 | n/a | """Test case implementation""" |
|---|
| 2 | n/a | |
|---|
| 3 | n/a | import sys |
|---|
| 4 | n/a | import functools |
|---|
| 5 | n/a | import difflib |
|---|
| 6 | n/a | import logging |
|---|
| 7 | n/a | import pprint |
|---|
| 8 | n/a | import re |
|---|
| 9 | n/a | import warnings |
|---|
| 10 | n/a | import collections |
|---|
| 11 | n/a | import contextlib |
|---|
| 12 | n/a | import traceback |
|---|
| 13 | n/a | |
|---|
| 14 | n/a | from . import result |
|---|
| 15 | n/a | from .util import (strclass, safe_repr, _count_diff_all_purpose, |
|---|
| 16 | n/a | _count_diff_hashable, _common_shorten_repr) |
|---|
| 17 | n/a | |
|---|
| 18 | n/a | __unittest = True |
|---|
| 19 | n/a | |
|---|
| 20 | n/a | _subtest_msg_sentinel = object() |
|---|
| 21 | n/a | |
|---|
| 22 | n/a | DIFF_OMITTED = ('\nDiff is %s characters long. ' |
|---|
| 23 | n/a | 'Set self.maxDiff to None to see it.') |
|---|
| 24 | n/a | |
|---|
| 25 | n/a | class SkipTest(Exception): |
|---|
| 26 | n/a | """ |
|---|
| 27 | n/a | Raise this exception in a test to skip it. |
|---|
| 28 | n/a | |
|---|
| 29 | n/a | Usually you can use TestCase.skipTest() or one of the skipping decorators |
|---|
| 30 | n/a | instead of raising this directly. |
|---|
| 31 | n/a | """ |
|---|
| 32 | n/a | |
|---|
| 33 | n/a | class _ShouldStop(Exception): |
|---|
| 34 | n/a | """ |
|---|
| 35 | n/a | The test should stop. |
|---|
| 36 | n/a | """ |
|---|
| 37 | n/a | |
|---|
| 38 | n/a | class _UnexpectedSuccess(Exception): |
|---|
| 39 | n/a | """ |
|---|
| 40 | n/a | The test was supposed to fail, but it didn't! |
|---|
| 41 | n/a | """ |
|---|
| 42 | n/a | |
|---|
| 43 | n/a | |
|---|
| 44 | n/a | class _Outcome(object): |
|---|
| 45 | n/a | def __init__(self, result=None): |
|---|
| 46 | n/a | self.expecting_failure = False |
|---|
| 47 | n/a | self.result = result |
|---|
| 48 | n/a | self.result_supports_subtests = hasattr(result, "addSubTest") |
|---|
| 49 | n/a | self.success = True |
|---|
| 50 | n/a | self.skipped = [] |
|---|
| 51 | n/a | self.expectedFailure = None |
|---|
| 52 | n/a | self.errors = [] |
|---|
| 53 | n/a | |
|---|
| 54 | n/a | @contextlib.contextmanager |
|---|
| 55 | n/a | def testPartExecutor(self, test_case, isTest=False): |
|---|
| 56 | n/a | old_success = self.success |
|---|
| 57 | n/a | self.success = True |
|---|
| 58 | n/a | try: |
|---|
| 59 | n/a | yield |
|---|
| 60 | n/a | except KeyboardInterrupt: |
|---|
| 61 | n/a | raise |
|---|
| 62 | n/a | except SkipTest as e: |
|---|
| 63 | n/a | self.success = False |
|---|
| 64 | n/a | self.skipped.append((test_case, str(e))) |
|---|
| 65 | n/a | except _ShouldStop: |
|---|
| 66 | n/a | pass |
|---|
| 67 | n/a | except: |
|---|
| 68 | n/a | exc_info = sys.exc_info() |
|---|
| 69 | n/a | if self.expecting_failure: |
|---|
| 70 | n/a | self.expectedFailure = exc_info |
|---|
| 71 | n/a | else: |
|---|
| 72 | n/a | self.success = False |
|---|
| 73 | n/a | self.errors.append((test_case, exc_info)) |
|---|
| 74 | n/a | # explicitly break a reference cycle: |
|---|
| 75 | n/a | # exc_info -> frame -> exc_info |
|---|
| 76 | n/a | exc_info = None |
|---|
| 77 | n/a | else: |
|---|
| 78 | n/a | if self.result_supports_subtests and self.success: |
|---|
| 79 | n/a | self.errors.append((test_case, None)) |
|---|
| 80 | n/a | finally: |
|---|
| 81 | n/a | self.success = self.success and old_success |
|---|
| 82 | n/a | |
|---|
| 83 | n/a | |
|---|
| 84 | n/a | def _id(obj): |
|---|
| 85 | n/a | return obj |
|---|
| 86 | n/a | |
|---|
| 87 | n/a | def skip(reason): |
|---|
| 88 | n/a | """ |
|---|
| 89 | n/a | Unconditionally skip a test. |
|---|
| 90 | n/a | """ |
|---|
| 91 | n/a | def decorator(test_item): |
|---|
| 92 | n/a | if not isinstance(test_item, type): |
|---|
| 93 | n/a | @functools.wraps(test_item) |
|---|
| 94 | n/a | def skip_wrapper(*args, **kwargs): |
|---|
| 95 | n/a | raise SkipTest(reason) |
|---|
| 96 | n/a | test_item = skip_wrapper |
|---|
| 97 | n/a | |
|---|
| 98 | n/a | test_item.__unittest_skip__ = True |
|---|
| 99 | n/a | test_item.__unittest_skip_why__ = reason |
|---|
| 100 | n/a | return test_item |
|---|
| 101 | n/a | return decorator |
|---|
| 102 | n/a | |
|---|
| 103 | n/a | def skipIf(condition, reason): |
|---|
| 104 | n/a | """ |
|---|
| 105 | n/a | Skip a test if the condition is true. |
|---|
| 106 | n/a | """ |
|---|
| 107 | n/a | if condition: |
|---|
| 108 | n/a | return skip(reason) |
|---|
| 109 | n/a | return _id |
|---|
| 110 | n/a | |
|---|
| 111 | n/a | def skipUnless(condition, reason): |
|---|
| 112 | n/a | """ |
|---|
| 113 | n/a | Skip a test unless the condition is true. |
|---|
| 114 | n/a | """ |
|---|
| 115 | n/a | if not condition: |
|---|
| 116 | n/a | return skip(reason) |
|---|
| 117 | n/a | return _id |
|---|
| 118 | n/a | |
|---|
| 119 | n/a | def expectedFailure(test_item): |
|---|
| 120 | n/a | test_item.__unittest_expecting_failure__ = True |
|---|
| 121 | n/a | return test_item |
|---|
| 122 | n/a | |
|---|
| 123 | n/a | def _is_subtype(expected, basetype): |
|---|
| 124 | n/a | if isinstance(expected, tuple): |
|---|
| 125 | n/a | return all(_is_subtype(e, basetype) for e in expected) |
|---|
| 126 | n/a | return isinstance(expected, type) and issubclass(expected, basetype) |
|---|
| 127 | n/a | |
|---|
| 128 | n/a | class _BaseTestCaseContext: |
|---|
| 129 | n/a | |
|---|
| 130 | n/a | def __init__(self, test_case): |
|---|
| 131 | n/a | self.test_case = test_case |
|---|
| 132 | n/a | |
|---|
| 133 | n/a | def _raiseFailure(self, standardMsg): |
|---|
| 134 | n/a | msg = self.test_case._formatMessage(self.msg, standardMsg) |
|---|
| 135 | n/a | raise self.test_case.failureException(msg) |
|---|
| 136 | n/a | |
|---|
| 137 | n/a | class _AssertRaisesBaseContext(_BaseTestCaseContext): |
|---|
| 138 | n/a | |
|---|
| 139 | n/a | def __init__(self, expected, test_case, expected_regex=None): |
|---|
| 140 | n/a | _BaseTestCaseContext.__init__(self, test_case) |
|---|
| 141 | n/a | self.expected = expected |
|---|
| 142 | n/a | self.test_case = test_case |
|---|
| 143 | n/a | if expected_regex is not None: |
|---|
| 144 | n/a | expected_regex = re.compile(expected_regex) |
|---|
| 145 | n/a | self.expected_regex = expected_regex |
|---|
| 146 | n/a | self.obj_name = None |
|---|
| 147 | n/a | self.msg = None |
|---|
| 148 | n/a | |
|---|
| 149 | n/a | def handle(self, name, args, kwargs): |
|---|
| 150 | n/a | """ |
|---|
| 151 | n/a | If args is empty, assertRaises/Warns is being used as a |
|---|
| 152 | n/a | context manager, so check for a 'msg' kwarg and return self. |
|---|
| 153 | n/a | If args is not empty, call a callable passing positional and keyword |
|---|
| 154 | n/a | arguments. |
|---|
| 155 | n/a | """ |
|---|
| 156 | n/a | if not _is_subtype(self.expected, self._base_type): |
|---|
| 157 | n/a | raise TypeError('%s() arg 1 must be %s' % |
|---|
| 158 | n/a | (name, self._base_type_str)) |
|---|
| 159 | n/a | if args and args[0] is None: |
|---|
| 160 | n/a | warnings.warn("callable is None", |
|---|
| 161 | n/a | DeprecationWarning, 3) |
|---|
| 162 | n/a | args = () |
|---|
| 163 | n/a | if not args: |
|---|
| 164 | n/a | self.msg = kwargs.pop('msg', None) |
|---|
| 165 | n/a | if kwargs: |
|---|
| 166 | n/a | warnings.warn('%r is an invalid keyword argument for ' |
|---|
| 167 | n/a | 'this function' % next(iter(kwargs)), |
|---|
| 168 | n/a | DeprecationWarning, 3) |
|---|
| 169 | n/a | return self |
|---|
| 170 | n/a | |
|---|
| 171 | n/a | callable_obj, *args = args |
|---|
| 172 | n/a | try: |
|---|
| 173 | n/a | self.obj_name = callable_obj.__name__ |
|---|
| 174 | n/a | except AttributeError: |
|---|
| 175 | n/a | self.obj_name = str(callable_obj) |
|---|
| 176 | n/a | with self: |
|---|
| 177 | n/a | callable_obj(*args, **kwargs) |
|---|
| 178 | n/a | |
|---|
| 179 | n/a | |
|---|
| 180 | n/a | class _AssertRaisesContext(_AssertRaisesBaseContext): |
|---|
| 181 | n/a | """A context manager used to implement TestCase.assertRaises* methods.""" |
|---|
| 182 | n/a | |
|---|
| 183 | n/a | _base_type = BaseException |
|---|
| 184 | n/a | _base_type_str = 'an exception type or tuple of exception types' |
|---|
| 185 | n/a | |
|---|
| 186 | n/a | def __enter__(self): |
|---|
| 187 | n/a | return self |
|---|
| 188 | n/a | |
|---|
| 189 | n/a | def __exit__(self, exc_type, exc_value, tb): |
|---|
| 190 | n/a | if exc_type is None: |
|---|
| 191 | n/a | try: |
|---|
| 192 | n/a | exc_name = self.expected.__name__ |
|---|
| 193 | n/a | except AttributeError: |
|---|
| 194 | n/a | exc_name = str(self.expected) |
|---|
| 195 | n/a | if self.obj_name: |
|---|
| 196 | n/a | self._raiseFailure("{} not raised by {}".format(exc_name, |
|---|
| 197 | n/a | self.obj_name)) |
|---|
| 198 | n/a | else: |
|---|
| 199 | n/a | self._raiseFailure("{} not raised".format(exc_name)) |
|---|
| 200 | n/a | else: |
|---|
| 201 | n/a | traceback.clear_frames(tb) |
|---|
| 202 | n/a | if not issubclass(exc_type, self.expected): |
|---|
| 203 | n/a | # let unexpected exceptions pass through |
|---|
| 204 | n/a | return False |
|---|
| 205 | n/a | # store exception, without traceback, for later retrieval |
|---|
| 206 | n/a | self.exception = exc_value.with_traceback(None) |
|---|
| 207 | n/a | if self.expected_regex is None: |
|---|
| 208 | n/a | return True |
|---|
| 209 | n/a | |
|---|
| 210 | n/a | expected_regex = self.expected_regex |
|---|
| 211 | n/a | if not expected_regex.search(str(exc_value)): |
|---|
| 212 | n/a | self._raiseFailure('"{}" does not match "{}"'.format( |
|---|
| 213 | n/a | expected_regex.pattern, str(exc_value))) |
|---|
| 214 | n/a | return True |
|---|
| 215 | n/a | |
|---|
| 216 | n/a | |
|---|
| 217 | n/a | class _AssertWarnsContext(_AssertRaisesBaseContext): |
|---|
| 218 | n/a | """A context manager used to implement TestCase.assertWarns* methods.""" |
|---|
| 219 | n/a | |
|---|
| 220 | n/a | _base_type = Warning |
|---|
| 221 | n/a | _base_type_str = 'a warning type or tuple of warning types' |
|---|
| 222 | n/a | |
|---|
| 223 | n/a | def __enter__(self): |
|---|
| 224 | n/a | # The __warningregistry__'s need to be in a pristine state for tests |
|---|
| 225 | n/a | # to work properly. |
|---|
| 226 | n/a | for v in sys.modules.values(): |
|---|
| 227 | n/a | if getattr(v, '__warningregistry__', None): |
|---|
| 228 | n/a | v.__warningregistry__ = {} |
|---|
| 229 | n/a | self.warnings_manager = warnings.catch_warnings(record=True) |
|---|
| 230 | n/a | self.warnings = self.warnings_manager.__enter__() |
|---|
| 231 | n/a | warnings.simplefilter("always", self.expected) |
|---|
| 232 | n/a | return self |
|---|
| 233 | n/a | |
|---|
| 234 | n/a | def __exit__(self, exc_type, exc_value, tb): |
|---|
| 235 | n/a | self.warnings_manager.__exit__(exc_type, exc_value, tb) |
|---|
| 236 | n/a | if exc_type is not None: |
|---|
| 237 | n/a | # let unexpected exceptions pass through |
|---|
| 238 | n/a | return |
|---|
| 239 | n/a | try: |
|---|
| 240 | n/a | exc_name = self.expected.__name__ |
|---|
| 241 | n/a | except AttributeError: |
|---|
| 242 | n/a | exc_name = str(self.expected) |
|---|
| 243 | n/a | first_matching = None |
|---|
| 244 | n/a | for m in self.warnings: |
|---|
| 245 | n/a | w = m.message |
|---|
| 246 | n/a | if not isinstance(w, self.expected): |
|---|
| 247 | n/a | continue |
|---|
| 248 | n/a | if first_matching is None: |
|---|
| 249 | n/a | first_matching = w |
|---|
| 250 | n/a | if (self.expected_regex is not None and |
|---|
| 251 | n/a | not self.expected_regex.search(str(w))): |
|---|
| 252 | n/a | continue |
|---|
| 253 | n/a | # store warning for later retrieval |
|---|
| 254 | n/a | self.warning = w |
|---|
| 255 | n/a | self.filename = m.filename |
|---|
| 256 | n/a | self.lineno = m.lineno |
|---|
| 257 | n/a | return |
|---|
| 258 | n/a | # Now we simply try to choose a helpful failure message |
|---|
| 259 | n/a | if first_matching is not None: |
|---|
| 260 | n/a | self._raiseFailure('"{}" does not match "{}"'.format( |
|---|
| 261 | n/a | self.expected_regex.pattern, str(first_matching))) |
|---|
| 262 | n/a | if self.obj_name: |
|---|
| 263 | n/a | self._raiseFailure("{} not triggered by {}".format(exc_name, |
|---|
| 264 | n/a | self.obj_name)) |
|---|
| 265 | n/a | else: |
|---|
| 266 | n/a | self._raiseFailure("{} not triggered".format(exc_name)) |
|---|
| 267 | n/a | |
|---|
| 268 | n/a | |
|---|
| 269 | n/a | |
|---|
| 270 | n/a | _LoggingWatcher = collections.namedtuple("_LoggingWatcher", |
|---|
| 271 | n/a | ["records", "output"]) |
|---|
| 272 | n/a | |
|---|
| 273 | n/a | |
|---|
| 274 | n/a | class _CapturingHandler(logging.Handler): |
|---|
| 275 | n/a | """ |
|---|
| 276 | n/a | A logging handler capturing all (raw and formatted) logging output. |
|---|
| 277 | n/a | """ |
|---|
| 278 | n/a | |
|---|
| 279 | n/a | def __init__(self): |
|---|
| 280 | n/a | logging.Handler.__init__(self) |
|---|
| 281 | n/a | self.watcher = _LoggingWatcher([], []) |
|---|
| 282 | n/a | |
|---|
| 283 | n/a | def flush(self): |
|---|
| 284 | n/a | pass |
|---|
| 285 | n/a | |
|---|
| 286 | n/a | def emit(self, record): |
|---|
| 287 | n/a | self.watcher.records.append(record) |
|---|
| 288 | n/a | msg = self.format(record) |
|---|
| 289 | n/a | self.watcher.output.append(msg) |
|---|
| 290 | n/a | |
|---|
| 291 | n/a | |
|---|
| 292 | n/a | |
|---|
| 293 | n/a | class _AssertLogsContext(_BaseTestCaseContext): |
|---|
| 294 | n/a | """A context manager used to implement TestCase.assertLogs().""" |
|---|
| 295 | n/a | |
|---|
| 296 | n/a | LOGGING_FORMAT = "%(levelname)s:%(name)s:%(message)s" |
|---|
| 297 | n/a | |
|---|
| 298 | n/a | def __init__(self, test_case, logger_name, level): |
|---|
| 299 | n/a | _BaseTestCaseContext.__init__(self, test_case) |
|---|
| 300 | n/a | self.logger_name = logger_name |
|---|
| 301 | n/a | if level: |
|---|
| 302 | n/a | self.level = logging._nameToLevel.get(level, level) |
|---|
| 303 | n/a | else: |
|---|
| 304 | n/a | self.level = logging.INFO |
|---|
| 305 | n/a | self.msg = None |
|---|
| 306 | n/a | |
|---|
| 307 | n/a | def __enter__(self): |
|---|
| 308 | n/a | if isinstance(self.logger_name, logging.Logger): |
|---|
| 309 | n/a | logger = self.logger = self.logger_name |
|---|
| 310 | n/a | else: |
|---|
| 311 | n/a | logger = self.logger = logging.getLogger(self.logger_name) |
|---|
| 312 | n/a | formatter = logging.Formatter(self.LOGGING_FORMAT) |
|---|
| 313 | n/a | handler = _CapturingHandler() |
|---|
| 314 | n/a | handler.setFormatter(formatter) |
|---|
| 315 | n/a | self.watcher = handler.watcher |
|---|
| 316 | n/a | self.old_handlers = logger.handlers[:] |
|---|
| 317 | n/a | self.old_level = logger.level |
|---|
| 318 | n/a | self.old_propagate = logger.propagate |
|---|
| 319 | n/a | logger.handlers = [handler] |
|---|
| 320 | n/a | logger.setLevel(self.level) |
|---|
| 321 | n/a | logger.propagate = False |
|---|
| 322 | n/a | return handler.watcher |
|---|
| 323 | n/a | |
|---|
| 324 | n/a | def __exit__(self, exc_type, exc_value, tb): |
|---|
| 325 | n/a | self.logger.handlers = self.old_handlers |
|---|
| 326 | n/a | self.logger.propagate = self.old_propagate |
|---|
| 327 | n/a | self.logger.setLevel(self.old_level) |
|---|
| 328 | n/a | if exc_type is not None: |
|---|
| 329 | n/a | # let unexpected exceptions pass through |
|---|
| 330 | n/a | return False |
|---|
| 331 | n/a | if len(self.watcher.records) == 0: |
|---|
| 332 | n/a | self._raiseFailure( |
|---|
| 333 | n/a | "no logs of level {} or higher triggered on {}" |
|---|
| 334 | n/a | .format(logging.getLevelName(self.level), self.logger.name)) |
|---|
| 335 | n/a | |
|---|
| 336 | n/a | |
|---|
| 337 | n/a | class TestCase(object): |
|---|
| 338 | n/a | """A class whose instances are single test cases. |
|---|
| 339 | n/a | |
|---|
| 340 | n/a | By default, the test code itself should be placed in a method named |
|---|
| 341 | n/a | 'runTest'. |
|---|
| 342 | n/a | |
|---|
| 343 | n/a | If the fixture may be used for many test cases, create as |
|---|
| 344 | n/a | many test methods as are needed. When instantiating such a TestCase |
|---|
| 345 | n/a | subclass, specify in the constructor arguments the name of the test method |
|---|
| 346 | n/a | that the instance is to execute. |
|---|
| 347 | n/a | |
|---|
| 348 | n/a | Test authors should subclass TestCase for their own tests. Construction |
|---|
| 349 | n/a | and deconstruction of the test's environment ('fixture') can be |
|---|
| 350 | n/a | implemented by overriding the 'setUp' and 'tearDown' methods respectively. |
|---|
| 351 | n/a | |
|---|
| 352 | n/a | If it is necessary to override the __init__ method, the base class |
|---|
| 353 | n/a | __init__ method must always be called. It is important that subclasses |
|---|
| 354 | n/a | should not change the signature of their __init__ method, since instances |
|---|
| 355 | n/a | of the classes are instantiated automatically by parts of the framework |
|---|
| 356 | n/a | in order to be run. |
|---|
| 357 | n/a | |
|---|
| 358 | n/a | When subclassing TestCase, you can set these attributes: |
|---|
| 359 | n/a | * failureException: determines which exception will be raised when |
|---|
| 360 | n/a | the instance's assertion methods fail; test methods raising this |
|---|
| 361 | n/a | exception will be deemed to have 'failed' rather than 'errored'. |
|---|
| 362 | n/a | * longMessage: determines whether long messages (including repr of |
|---|
| 363 | n/a | objects used in assert methods) will be printed on failure in *addition* |
|---|
| 364 | n/a | to any explicit message passed. |
|---|
| 365 | n/a | * maxDiff: sets the maximum length of a diff in failure messages |
|---|
| 366 | n/a | by assert methods using difflib. It is looked up as an instance |
|---|
| 367 | n/a | attribute so can be configured by individual tests if required. |
|---|
| 368 | n/a | """ |
|---|
| 369 | n/a | |
|---|
| 370 | n/a | failureException = AssertionError |
|---|
| 371 | n/a | |
|---|
| 372 | n/a | longMessage = True |
|---|
| 373 | n/a | |
|---|
| 374 | n/a | maxDiff = 80*8 |
|---|
| 375 | n/a | |
|---|
| 376 | n/a | # If a string is longer than _diffThreshold, use normal comparison instead |
|---|
| 377 | n/a | # of difflib. See #11763. |
|---|
| 378 | n/a | _diffThreshold = 2**16 |
|---|
| 379 | n/a | |
|---|
| 380 | n/a | # Attribute used by TestSuite for classSetUp |
|---|
| 381 | n/a | |
|---|
| 382 | n/a | _classSetupFailed = False |
|---|
| 383 | n/a | |
|---|
| 384 | n/a | def __init__(self, methodName='runTest'): |
|---|
| 385 | n/a | """Create an instance of the class that will use the named test |
|---|
| 386 | n/a | method when executed. Raises a ValueError if the instance does |
|---|
| 387 | n/a | not have a method with the specified name. |
|---|
| 388 | n/a | """ |
|---|
| 389 | n/a | self._testMethodName = methodName |
|---|
| 390 | n/a | self._outcome = None |
|---|
| 391 | n/a | self._testMethodDoc = 'No test' |
|---|
| 392 | n/a | try: |
|---|
| 393 | n/a | testMethod = getattr(self, methodName) |
|---|
| 394 | n/a | except AttributeError: |
|---|
| 395 | n/a | if methodName != 'runTest': |
|---|
| 396 | n/a | # we allow instantiation with no explicit method name |
|---|
| 397 | n/a | # but not an *incorrect* or missing method name |
|---|
| 398 | n/a | raise ValueError("no such test method in %s: %s" % |
|---|
| 399 | n/a | (self.__class__, methodName)) |
|---|
| 400 | n/a | else: |
|---|
| 401 | n/a | self._testMethodDoc = testMethod.__doc__ |
|---|
| 402 | n/a | self._cleanups = [] |
|---|
| 403 | n/a | self._subtest = None |
|---|
| 404 | n/a | |
|---|
| 405 | n/a | # Map types to custom assertEqual functions that will compare |
|---|
| 406 | n/a | # instances of said type in more detail to generate a more useful |
|---|
| 407 | n/a | # error message. |
|---|
| 408 | n/a | self._type_equality_funcs = {} |
|---|
| 409 | n/a | self.addTypeEqualityFunc(dict, 'assertDictEqual') |
|---|
| 410 | n/a | self.addTypeEqualityFunc(list, 'assertListEqual') |
|---|
| 411 | n/a | self.addTypeEqualityFunc(tuple, 'assertTupleEqual') |
|---|
| 412 | n/a | self.addTypeEqualityFunc(set, 'assertSetEqual') |
|---|
| 413 | n/a | self.addTypeEqualityFunc(frozenset, 'assertSetEqual') |
|---|
| 414 | n/a | self.addTypeEqualityFunc(str, 'assertMultiLineEqual') |
|---|
| 415 | n/a | |
|---|
| 416 | n/a | def addTypeEqualityFunc(self, typeobj, function): |
|---|
| 417 | n/a | """Add a type specific assertEqual style function to compare a type. |
|---|
| 418 | n/a | |
|---|
| 419 | n/a | This method is for use by TestCase subclasses that need to register |
|---|
| 420 | n/a | their own type equality functions to provide nicer error messages. |
|---|
| 421 | n/a | |
|---|
| 422 | n/a | Args: |
|---|
| 423 | n/a | typeobj: The data type to call this function on when both values |
|---|
| 424 | n/a | are of the same type in assertEqual(). |
|---|
| 425 | n/a | function: The callable taking two arguments and an optional |
|---|
| 426 | n/a | msg= argument that raises self.failureException with a |
|---|
| 427 | n/a | useful error message when the two arguments are not equal. |
|---|
| 428 | n/a | """ |
|---|
| 429 | n/a | self._type_equality_funcs[typeobj] = function |
|---|
| 430 | n/a | |
|---|
| 431 | n/a | def addCleanup(self, function, *args, **kwargs): |
|---|
| 432 | n/a | """Add a function, with arguments, to be called when the test is |
|---|
| 433 | n/a | completed. Functions added are called on a LIFO basis and are |
|---|
| 434 | n/a | called after tearDown on test failure or success. |
|---|
| 435 | n/a | |
|---|
| 436 | n/a | Cleanup items are called even if setUp fails (unlike tearDown).""" |
|---|
| 437 | n/a | self._cleanups.append((function, args, kwargs)) |
|---|
| 438 | n/a | |
|---|
| 439 | n/a | def setUp(self): |
|---|
| 440 | n/a | "Hook method for setting up the test fixture before exercising it." |
|---|
| 441 | n/a | pass |
|---|
| 442 | n/a | |
|---|
| 443 | n/a | def tearDown(self): |
|---|
| 444 | n/a | "Hook method for deconstructing the test fixture after testing it." |
|---|
| 445 | n/a | pass |
|---|
| 446 | n/a | |
|---|
| 447 | n/a | @classmethod |
|---|
| 448 | n/a | def setUpClass(cls): |
|---|
| 449 | n/a | "Hook method for setting up class fixture before running tests in the class." |
|---|
| 450 | n/a | |
|---|
| 451 | n/a | @classmethod |
|---|
| 452 | n/a | def tearDownClass(cls): |
|---|
| 453 | n/a | "Hook method for deconstructing the class fixture after running all tests in the class." |
|---|
| 454 | n/a | |
|---|
| 455 | n/a | def countTestCases(self): |
|---|
| 456 | n/a | return 1 |
|---|
| 457 | n/a | |
|---|
| 458 | n/a | def defaultTestResult(self): |
|---|
| 459 | n/a | return result.TestResult() |
|---|
| 460 | n/a | |
|---|
| 461 | n/a | def shortDescription(self): |
|---|
| 462 | n/a | """Returns a one-line description of the test, or None if no |
|---|
| 463 | n/a | description has been provided. |
|---|
| 464 | n/a | |
|---|
| 465 | n/a | The default implementation of this method returns the first line of |
|---|
| 466 | n/a | the specified test method's docstring. |
|---|
| 467 | n/a | """ |
|---|
| 468 | n/a | doc = self._testMethodDoc |
|---|
| 469 | n/a | return doc and doc.split("\n")[0].strip() or None |
|---|
| 470 | n/a | |
|---|
| 471 | n/a | |
|---|
| 472 | n/a | def id(self): |
|---|
| 473 | n/a | return "%s.%s" % (strclass(self.__class__), self._testMethodName) |
|---|
| 474 | n/a | |
|---|
| 475 | n/a | def __eq__(self, other): |
|---|
| 476 | n/a | if type(self) is not type(other): |
|---|
| 477 | n/a | return NotImplemented |
|---|
| 478 | n/a | |
|---|
| 479 | n/a | return self._testMethodName == other._testMethodName |
|---|
| 480 | n/a | |
|---|
| 481 | n/a | def __hash__(self): |
|---|
| 482 | n/a | return hash((type(self), self._testMethodName)) |
|---|
| 483 | n/a | |
|---|
| 484 | n/a | def __str__(self): |
|---|
| 485 | n/a | return "%s (%s)" % (self._testMethodName, strclass(self.__class__)) |
|---|
| 486 | n/a | |
|---|
| 487 | n/a | def __repr__(self): |
|---|
| 488 | n/a | return "<%s testMethod=%s>" % \ |
|---|
| 489 | n/a | (strclass(self.__class__), self._testMethodName) |
|---|
| 490 | n/a | |
|---|
| 491 | n/a | def _addSkip(self, result, test_case, reason): |
|---|
| 492 | n/a | addSkip = getattr(result, 'addSkip', None) |
|---|
| 493 | n/a | if addSkip is not None: |
|---|
| 494 | n/a | addSkip(test_case, reason) |
|---|
| 495 | n/a | else: |
|---|
| 496 | n/a | warnings.warn("TestResult has no addSkip method, skips not reported", |
|---|
| 497 | n/a | RuntimeWarning, 2) |
|---|
| 498 | n/a | result.addSuccess(test_case) |
|---|
| 499 | n/a | |
|---|
| 500 | n/a | @contextlib.contextmanager |
|---|
| 501 | n/a | def subTest(self, msg=_subtest_msg_sentinel, **params): |
|---|
| 502 | n/a | """Return a context manager that will return the enclosed block |
|---|
| 503 | n/a | of code in a subtest identified by the optional message and |
|---|
| 504 | n/a | keyword parameters. A failure in the subtest marks the test |
|---|
| 505 | n/a | case as failed but resumes execution at the end of the enclosed |
|---|
| 506 | n/a | block, allowing further test code to be executed. |
|---|
| 507 | n/a | """ |
|---|
| 508 | n/a | if not self._outcome.result_supports_subtests: |
|---|
| 509 | n/a | yield |
|---|
| 510 | n/a | return |
|---|
| 511 | n/a | parent = self._subtest |
|---|
| 512 | n/a | if parent is None: |
|---|
| 513 | n/a | params_map = collections.ChainMap(params) |
|---|
| 514 | n/a | else: |
|---|
| 515 | n/a | params_map = parent.params.new_child(params) |
|---|
| 516 | n/a | self._subtest = _SubTest(self, msg, params_map) |
|---|
| 517 | n/a | try: |
|---|
| 518 | n/a | with self._outcome.testPartExecutor(self._subtest, isTest=True): |
|---|
| 519 | n/a | yield |
|---|
| 520 | n/a | if not self._outcome.success: |
|---|
| 521 | n/a | result = self._outcome.result |
|---|
| 522 | n/a | if result is not None and result.failfast: |
|---|
| 523 | n/a | raise _ShouldStop |
|---|
| 524 | n/a | elif self._outcome.expectedFailure: |
|---|
| 525 | n/a | # If the test is expecting a failure, we really want to |
|---|
| 526 | n/a | # stop now and register the expected failure. |
|---|
| 527 | n/a | raise _ShouldStop |
|---|
| 528 | n/a | finally: |
|---|
| 529 | n/a | self._subtest = parent |
|---|
| 530 | n/a | |
|---|
| 531 | n/a | def _feedErrorsToResult(self, result, errors): |
|---|
| 532 | n/a | for test, exc_info in errors: |
|---|
| 533 | n/a | if isinstance(test, _SubTest): |
|---|
| 534 | n/a | result.addSubTest(test.test_case, test, exc_info) |
|---|
| 535 | n/a | elif exc_info is not None: |
|---|
| 536 | n/a | if issubclass(exc_info[0], self.failureException): |
|---|
| 537 | n/a | result.addFailure(test, exc_info) |
|---|
| 538 | n/a | else: |
|---|
| 539 | n/a | result.addError(test, exc_info) |
|---|
| 540 | n/a | |
|---|
| 541 | n/a | def _addExpectedFailure(self, result, exc_info): |
|---|
| 542 | n/a | try: |
|---|
| 543 | n/a | addExpectedFailure = result.addExpectedFailure |
|---|
| 544 | n/a | except AttributeError: |
|---|
| 545 | n/a | warnings.warn("TestResult has no addExpectedFailure method, reporting as passes", |
|---|
| 546 | n/a | RuntimeWarning) |
|---|
| 547 | n/a | result.addSuccess(self) |
|---|
| 548 | n/a | else: |
|---|
| 549 | n/a | addExpectedFailure(self, exc_info) |
|---|
| 550 | n/a | |
|---|
| 551 | n/a | def _addUnexpectedSuccess(self, result): |
|---|
| 552 | n/a | try: |
|---|
| 553 | n/a | addUnexpectedSuccess = result.addUnexpectedSuccess |
|---|
| 554 | n/a | except AttributeError: |
|---|
| 555 | n/a | warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failure", |
|---|
| 556 | n/a | RuntimeWarning) |
|---|
| 557 | n/a | # We need to pass an actual exception and traceback to addFailure, |
|---|
| 558 | n/a | # otherwise the legacy result can choke. |
|---|
| 559 | n/a | try: |
|---|
| 560 | n/a | raise _UnexpectedSuccess from None |
|---|
| 561 | n/a | except _UnexpectedSuccess: |
|---|
| 562 | n/a | result.addFailure(self, sys.exc_info()) |
|---|
| 563 | n/a | else: |
|---|
| 564 | n/a | addUnexpectedSuccess(self) |
|---|
| 565 | n/a | |
|---|
| 566 | n/a | def run(self, result=None): |
|---|
| 567 | n/a | orig_result = result |
|---|
| 568 | n/a | if result is None: |
|---|
| 569 | n/a | result = self.defaultTestResult() |
|---|
| 570 | n/a | startTestRun = getattr(result, 'startTestRun', None) |
|---|
| 571 | n/a | if startTestRun is not None: |
|---|
| 572 | n/a | startTestRun() |
|---|
| 573 | n/a | |
|---|
| 574 | n/a | result.startTest(self) |
|---|
| 575 | n/a | |
|---|
| 576 | n/a | testMethod = getattr(self, self._testMethodName) |
|---|
| 577 | n/a | if (getattr(self.__class__, "__unittest_skip__", False) or |
|---|
| 578 | n/a | getattr(testMethod, "__unittest_skip__", False)): |
|---|
| 579 | n/a | # If the class or method was skipped. |
|---|
| 580 | n/a | try: |
|---|
| 581 | n/a | skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') |
|---|
| 582 | n/a | or getattr(testMethod, '__unittest_skip_why__', '')) |
|---|
| 583 | n/a | self._addSkip(result, self, skip_why) |
|---|
| 584 | n/a | finally: |
|---|
| 585 | n/a | result.stopTest(self) |
|---|
| 586 | n/a | return |
|---|
| 587 | n/a | expecting_failure_method = getattr(testMethod, |
|---|
| 588 | n/a | "__unittest_expecting_failure__", False) |
|---|
| 589 | n/a | expecting_failure_class = getattr(self, |
|---|
| 590 | n/a | "__unittest_expecting_failure__", False) |
|---|
| 591 | n/a | expecting_failure = expecting_failure_class or expecting_failure_method |
|---|
| 592 | n/a | outcome = _Outcome(result) |
|---|
| 593 | n/a | try: |
|---|
| 594 | n/a | self._outcome = outcome |
|---|
| 595 | n/a | |
|---|
| 596 | n/a | with outcome.testPartExecutor(self): |
|---|
| 597 | n/a | self.setUp() |
|---|
| 598 | n/a | if outcome.success: |
|---|
| 599 | n/a | outcome.expecting_failure = expecting_failure |
|---|
| 600 | n/a | with outcome.testPartExecutor(self, isTest=True): |
|---|
| 601 | n/a | testMethod() |
|---|
| 602 | n/a | outcome.expecting_failure = False |
|---|
| 603 | n/a | with outcome.testPartExecutor(self): |
|---|
| 604 | n/a | self.tearDown() |
|---|
| 605 | n/a | |
|---|
| 606 | n/a | self.doCleanups() |
|---|
| 607 | n/a | for test, reason in outcome.skipped: |
|---|
| 608 | n/a | self._addSkip(result, test, reason) |
|---|
| 609 | n/a | self._feedErrorsToResult(result, outcome.errors) |
|---|
| 610 | n/a | if outcome.success: |
|---|
| 611 | n/a | if expecting_failure: |
|---|
| 612 | n/a | if outcome.expectedFailure: |
|---|
| 613 | n/a | self._addExpectedFailure(result, outcome.expectedFailure) |
|---|
| 614 | n/a | else: |
|---|
| 615 | n/a | self._addUnexpectedSuccess(result) |
|---|
| 616 | n/a | else: |
|---|
| 617 | n/a | result.addSuccess(self) |
|---|
| 618 | n/a | return result |
|---|
| 619 | n/a | finally: |
|---|
| 620 | n/a | result.stopTest(self) |
|---|
| 621 | n/a | if orig_result is None: |
|---|
| 622 | n/a | stopTestRun = getattr(result, 'stopTestRun', None) |
|---|
| 623 | n/a | if stopTestRun is not None: |
|---|
| 624 | n/a | stopTestRun() |
|---|
| 625 | n/a | |
|---|
| 626 | n/a | # explicitly break reference cycles: |
|---|
| 627 | n/a | # outcome.errors -> frame -> outcome -> outcome.errors |
|---|
| 628 | n/a | # outcome.expectedFailure -> frame -> outcome -> outcome.expectedFailure |
|---|
| 629 | n/a | outcome.errors.clear() |
|---|
| 630 | n/a | outcome.expectedFailure = None |
|---|
| 631 | n/a | |
|---|
| 632 | n/a | # clear the outcome, no more needed |
|---|
| 633 | n/a | self._outcome = None |
|---|
| 634 | n/a | |
|---|
| 635 | n/a | def doCleanups(self): |
|---|
| 636 | n/a | """Execute all cleanup functions. Normally called for you after |
|---|
| 637 | n/a | tearDown.""" |
|---|
| 638 | n/a | outcome = self._outcome or _Outcome() |
|---|
| 639 | n/a | while self._cleanups: |
|---|
| 640 | n/a | function, args, kwargs = self._cleanups.pop() |
|---|
| 641 | n/a | with outcome.testPartExecutor(self): |
|---|
| 642 | n/a | function(*args, **kwargs) |
|---|
| 643 | n/a | |
|---|
| 644 | n/a | # return this for backwards compatibility |
|---|
| 645 | n/a | # even though we no longer us it internally |
|---|
| 646 | n/a | return outcome.success |
|---|
| 647 | n/a | |
|---|
| 648 | n/a | def __call__(self, *args, **kwds): |
|---|
| 649 | n/a | return self.run(*args, **kwds) |
|---|
| 650 | n/a | |
|---|
| 651 | n/a | def debug(self): |
|---|
| 652 | n/a | """Run the test without collecting errors in a TestResult""" |
|---|
| 653 | n/a | self.setUp() |
|---|
| 654 | n/a | getattr(self, self._testMethodName)() |
|---|
| 655 | n/a | self.tearDown() |
|---|
| 656 | n/a | while self._cleanups: |
|---|
| 657 | n/a | function, args, kwargs = self._cleanups.pop(-1) |
|---|
| 658 | n/a | function(*args, **kwargs) |
|---|
| 659 | n/a | |
|---|
| 660 | n/a | def skipTest(self, reason): |
|---|
| 661 | n/a | """Skip this test.""" |
|---|
| 662 | n/a | raise SkipTest(reason) |
|---|
| 663 | n/a | |
|---|
| 664 | n/a | def fail(self, msg=None): |
|---|
| 665 | n/a | """Fail immediately, with the given message.""" |
|---|
| 666 | n/a | raise self.failureException(msg) |
|---|
| 667 | n/a | |
|---|
| 668 | n/a | def assertFalse(self, expr, msg=None): |
|---|
| 669 | n/a | """Check that the expression is false.""" |
|---|
| 670 | n/a | if expr: |
|---|
| 671 | n/a | msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr)) |
|---|
| 672 | n/a | raise self.failureException(msg) |
|---|
| 673 | n/a | |
|---|
| 674 | n/a | def assertTrue(self, expr, msg=None): |
|---|
| 675 | n/a | """Check that the expression is true.""" |
|---|
| 676 | n/a | if not expr: |
|---|
| 677 | n/a | msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr)) |
|---|
| 678 | n/a | raise self.failureException(msg) |
|---|
| 679 | n/a | |
|---|
| 680 | n/a | def _formatMessage(self, msg, standardMsg): |
|---|
| 681 | n/a | """Honour the longMessage attribute when generating failure messages. |
|---|
| 682 | n/a | If longMessage is False this means: |
|---|
| 683 | n/a | * Use only an explicit message if it is provided |
|---|
| 684 | n/a | * Otherwise use the standard message for the assert |
|---|
| 685 | n/a | |
|---|
| 686 | n/a | If longMessage is True: |
|---|
| 687 | n/a | * Use the standard message |
|---|
| 688 | n/a | * If an explicit message is provided, plus ' : ' and the explicit message |
|---|
| 689 | n/a | """ |
|---|
| 690 | n/a | if not self.longMessage: |
|---|
| 691 | n/a | return msg or standardMsg |
|---|
| 692 | n/a | if msg is None: |
|---|
| 693 | n/a | return standardMsg |
|---|
| 694 | n/a | try: |
|---|
| 695 | n/a | # don't switch to '{}' formatting in Python 2.X |
|---|
| 696 | n/a | # it changes the way unicode input is handled |
|---|
| 697 | n/a | return '%s : %s' % (standardMsg, msg) |
|---|
| 698 | n/a | except UnicodeDecodeError: |
|---|
| 699 | n/a | return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg)) |
|---|
| 700 | n/a | |
|---|
| 701 | n/a | def assertRaises(self, expected_exception, *args, **kwargs): |
|---|
| 702 | n/a | """Fail unless an exception of class expected_exception is raised |
|---|
| 703 | n/a | by the callable when invoked with specified positional and |
|---|
| 704 | n/a | keyword arguments. If a different type of exception is |
|---|
| 705 | n/a | raised, it will not be caught, and the test case will be |
|---|
| 706 | n/a | deemed to have suffered an error, exactly as for an |
|---|
| 707 | n/a | unexpected exception. |
|---|
| 708 | n/a | |
|---|
| 709 | n/a | If called with the callable and arguments omitted, will return a |
|---|
| 710 | n/a | context object used like this:: |
|---|
| 711 | n/a | |
|---|
| 712 | n/a | with self.assertRaises(SomeException): |
|---|
| 713 | n/a | do_something() |
|---|
| 714 | n/a | |
|---|
| 715 | n/a | An optional keyword argument 'msg' can be provided when assertRaises |
|---|
| 716 | n/a | is used as a context object. |
|---|
| 717 | n/a | |
|---|
| 718 | n/a | The context manager keeps a reference to the exception as |
|---|
| 719 | n/a | the 'exception' attribute. This allows you to inspect the |
|---|
| 720 | n/a | exception after the assertion:: |
|---|
| 721 | n/a | |
|---|
| 722 | n/a | with self.assertRaises(SomeException) as cm: |
|---|
| 723 | n/a | do_something() |
|---|
| 724 | n/a | the_exception = cm.exception |
|---|
| 725 | n/a | self.assertEqual(the_exception.error_code, 3) |
|---|
| 726 | n/a | """ |
|---|
| 727 | n/a | context = _AssertRaisesContext(expected_exception, self) |
|---|
| 728 | n/a | return context.handle('assertRaises', args, kwargs) |
|---|
| 729 | n/a | |
|---|
| 730 | n/a | def assertWarns(self, expected_warning, *args, **kwargs): |
|---|
| 731 | n/a | """Fail unless a warning of class warnClass is triggered |
|---|
| 732 | n/a | by the callable when invoked with specified positional and |
|---|
| 733 | n/a | keyword arguments. If a different type of warning is |
|---|
| 734 | n/a | triggered, it will not be handled: depending on the other |
|---|
| 735 | n/a | warning filtering rules in effect, it might be silenced, printed |
|---|
| 736 | n/a | out, or raised as an exception. |
|---|
| 737 | n/a | |
|---|
| 738 | n/a | If called with the callable and arguments omitted, will return a |
|---|
| 739 | n/a | context object used like this:: |
|---|
| 740 | n/a | |
|---|
| 741 | n/a | with self.assertWarns(SomeWarning): |
|---|
| 742 | n/a | do_something() |
|---|
| 743 | n/a | |
|---|
| 744 | n/a | An optional keyword argument 'msg' can be provided when assertWarns |
|---|
| 745 | n/a | is used as a context object. |
|---|
| 746 | n/a | |
|---|
| 747 | n/a | The context manager keeps a reference to the first matching |
|---|
| 748 | n/a | warning as the 'warning' attribute; similarly, the 'filename' |
|---|
| 749 | n/a | and 'lineno' attributes give you information about the line |
|---|
| 750 | n/a | of Python code from which the warning was triggered. |
|---|
| 751 | n/a | This allows you to inspect the warning after the assertion:: |
|---|
| 752 | n/a | |
|---|
| 753 | n/a | with self.assertWarns(SomeWarning) as cm: |
|---|
| 754 | n/a | do_something() |
|---|
| 755 | n/a | the_warning = cm.warning |
|---|
| 756 | n/a | self.assertEqual(the_warning.some_attribute, 147) |
|---|
| 757 | n/a | """ |
|---|
| 758 | n/a | context = _AssertWarnsContext(expected_warning, self) |
|---|
| 759 | n/a | return context.handle('assertWarns', args, kwargs) |
|---|
| 760 | n/a | |
|---|
| 761 | n/a | def assertLogs(self, logger=None, level=None): |
|---|
| 762 | n/a | """Fail unless a log message of level *level* or higher is emitted |
|---|
| 763 | n/a | on *logger_name* or its children. If omitted, *level* defaults to |
|---|
| 764 | n/a | INFO and *logger* defaults to the root logger. |
|---|
| 765 | n/a | |
|---|
| 766 | n/a | This method must be used as a context manager, and will yield |
|---|
| 767 | n/a | a recording object with two attributes: `output` and `records`. |
|---|
| 768 | n/a | At the end of the context manager, the `output` attribute will |
|---|
| 769 | n/a | be a list of the matching formatted log messages and the |
|---|
| 770 | n/a | `records` attribute will be a list of the corresponding LogRecord |
|---|
| 771 | n/a | objects. |
|---|
| 772 | n/a | |
|---|
| 773 | n/a | Example:: |
|---|
| 774 | n/a | |
|---|
| 775 | n/a | with self.assertLogs('foo', level='INFO') as cm: |
|---|
| 776 | n/a | logging.getLogger('foo').info('first message') |
|---|
| 777 | n/a | logging.getLogger('foo.bar').error('second message') |
|---|
| 778 | n/a | self.assertEqual(cm.output, ['INFO:foo:first message', |
|---|
| 779 | n/a | 'ERROR:foo.bar:second message']) |
|---|
| 780 | n/a | """ |
|---|
| 781 | n/a | return _AssertLogsContext(self, logger, level) |
|---|
| 782 | n/a | |
|---|
| 783 | n/a | def _getAssertEqualityFunc(self, first, second): |
|---|
| 784 | n/a | """Get a detailed comparison function for the types of the two args. |
|---|
| 785 | n/a | |
|---|
| 786 | n/a | Returns: A callable accepting (first, second, msg=None) that will |
|---|
| 787 | n/a | raise a failure exception if first != second with a useful human |
|---|
| 788 | n/a | readable error message for those types. |
|---|
| 789 | n/a | """ |
|---|
| 790 | n/a | # |
|---|
| 791 | n/a | # NOTE(gregory.p.smith): I considered isinstance(first, type(second)) |
|---|
| 792 | n/a | # and vice versa. I opted for the conservative approach in case |
|---|
| 793 | n/a | # subclasses are not intended to be compared in detail to their super |
|---|
| 794 | n/a | # class instances using a type equality func. This means testing |
|---|
| 795 | n/a | # subtypes won't automagically use the detailed comparison. Callers |
|---|
| 796 | n/a | # should use their type specific assertSpamEqual method to compare |
|---|
| 797 | n/a | # subclasses if the detailed comparison is desired and appropriate. |
|---|
| 798 | n/a | # See the discussion in http://bugs.python.org/issue2578. |
|---|
| 799 | n/a | # |
|---|
| 800 | n/a | if type(first) is type(second): |
|---|
| 801 | n/a | asserter = self._type_equality_funcs.get(type(first)) |
|---|
| 802 | n/a | if asserter is not None: |
|---|
| 803 | n/a | if isinstance(asserter, str): |
|---|
| 804 | n/a | asserter = getattr(self, asserter) |
|---|
| 805 | n/a | return asserter |
|---|
| 806 | n/a | |
|---|
| 807 | n/a | return self._baseAssertEqual |
|---|
| 808 | n/a | |
|---|
| 809 | n/a | def _baseAssertEqual(self, first, second, msg=None): |
|---|
| 810 | n/a | """The default assertEqual implementation, not type specific.""" |
|---|
| 811 | n/a | if not first == second: |
|---|
| 812 | n/a | standardMsg = '%s != %s' % _common_shorten_repr(first, second) |
|---|
| 813 | n/a | msg = self._formatMessage(msg, standardMsg) |
|---|
| 814 | n/a | raise self.failureException(msg) |
|---|
| 815 | n/a | |
|---|
| 816 | n/a | def assertEqual(self, first, second, msg=None): |
|---|
| 817 | n/a | """Fail if the two objects are unequal as determined by the '==' |
|---|
| 818 | n/a | operator. |
|---|
| 819 | n/a | """ |
|---|
| 820 | n/a | assertion_func = self._getAssertEqualityFunc(first, second) |
|---|
| 821 | n/a | assertion_func(first, second, msg=msg) |
|---|
| 822 | n/a | |
|---|
| 823 | n/a | def assertNotEqual(self, first, second, msg=None): |
|---|
| 824 | n/a | """Fail if the two objects are equal as determined by the '!=' |
|---|
| 825 | n/a | operator. |
|---|
| 826 | n/a | """ |
|---|
| 827 | n/a | if not first != second: |
|---|
| 828 | n/a | msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first), |
|---|
| 829 | n/a | safe_repr(second))) |
|---|
| 830 | n/a | raise self.failureException(msg) |
|---|
| 831 | n/a | |
|---|
| 832 | n/a | def assertAlmostEqual(self, first, second, places=None, msg=None, |
|---|
| 833 | n/a | delta=None): |
|---|
| 834 | n/a | """Fail if the two objects are unequal as determined by their |
|---|
| 835 | n/a | difference rounded to the given number of decimal places |
|---|
| 836 | n/a | (default 7) and comparing to zero, or by comparing that the |
|---|
| 837 | n/a | between the two objects is more than the given delta. |
|---|
| 838 | n/a | |
|---|
| 839 | n/a | Note that decimal places (from zero) are usually not the same |
|---|
| 840 | n/a | as significant digits (measured from the most significant digit). |
|---|
| 841 | n/a | |
|---|
| 842 | n/a | If the two objects compare equal then they will automatically |
|---|
| 843 | n/a | compare almost equal. |
|---|
| 844 | n/a | """ |
|---|
| 845 | n/a | if first == second: |
|---|
| 846 | n/a | # shortcut |
|---|
| 847 | n/a | return |
|---|
| 848 | n/a | if delta is not None and places is not None: |
|---|
| 849 | n/a | raise TypeError("specify delta or places not both") |
|---|
| 850 | n/a | |
|---|
| 851 | n/a | if delta is not None: |
|---|
| 852 | n/a | if abs(first - second) <= delta: |
|---|
| 853 | n/a | return |
|---|
| 854 | n/a | |
|---|
| 855 | n/a | standardMsg = '%s != %s within %s delta' % (safe_repr(first), |
|---|
| 856 | n/a | safe_repr(second), |
|---|
| 857 | n/a | safe_repr(delta)) |
|---|
| 858 | n/a | else: |
|---|
| 859 | n/a | if places is None: |
|---|
| 860 | n/a | places = 7 |
|---|
| 861 | n/a | |
|---|
| 862 | n/a | if round(abs(second-first), places) == 0: |
|---|
| 863 | n/a | return |
|---|
| 864 | n/a | |
|---|
| 865 | n/a | standardMsg = '%s != %s within %r places' % (safe_repr(first), |
|---|
| 866 | n/a | safe_repr(second), |
|---|
| 867 | n/a | places) |
|---|
| 868 | n/a | msg = self._formatMessage(msg, standardMsg) |
|---|
| 869 | n/a | raise self.failureException(msg) |
|---|
| 870 | n/a | |
|---|
| 871 | n/a | def assertNotAlmostEqual(self, first, second, places=None, msg=None, |
|---|
| 872 | n/a | delta=None): |
|---|
| 873 | n/a | """Fail if the two objects are equal as determined by their |
|---|
| 874 | n/a | difference rounded to the given number of decimal places |
|---|
| 875 | n/a | (default 7) and comparing to zero, or by comparing that the |
|---|
| 876 | n/a | between the two objects is less than the given delta. |
|---|
| 877 | n/a | |
|---|
| 878 | n/a | Note that decimal places (from zero) are usually not the same |
|---|
| 879 | n/a | as significant digits (measured from the most significant digit). |
|---|
| 880 | n/a | |
|---|
| 881 | n/a | Objects that are equal automatically fail. |
|---|
| 882 | n/a | """ |
|---|
| 883 | n/a | if delta is not None and places is not None: |
|---|
| 884 | n/a | raise TypeError("specify delta or places not both") |
|---|
| 885 | n/a | if delta is not None: |
|---|
| 886 | n/a | if not (first == second) and abs(first - second) > delta: |
|---|
| 887 | n/a | return |
|---|
| 888 | n/a | standardMsg = '%s == %s within %s delta' % (safe_repr(first), |
|---|
| 889 | n/a | safe_repr(second), |
|---|
| 890 | n/a | safe_repr(delta)) |
|---|
| 891 | n/a | else: |
|---|
| 892 | n/a | if places is None: |
|---|
| 893 | n/a | places = 7 |
|---|
| 894 | n/a | if not (first == second) and round(abs(second-first), places) != 0: |
|---|
| 895 | n/a | return |
|---|
| 896 | n/a | standardMsg = '%s == %s within %r places' % (safe_repr(first), |
|---|
| 897 | n/a | safe_repr(second), |
|---|
| 898 | n/a | places) |
|---|
| 899 | n/a | |
|---|
| 900 | n/a | msg = self._formatMessage(msg, standardMsg) |
|---|
| 901 | n/a | raise self.failureException(msg) |
|---|
| 902 | n/a | |
|---|
| 903 | n/a | |
|---|
| 904 | n/a | def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): |
|---|
| 905 | n/a | """An equality assertion for ordered sequences (like lists and tuples). |
|---|
| 906 | n/a | |
|---|
| 907 | n/a | For the purposes of this function, a valid ordered sequence type is one |
|---|
| 908 | n/a | which can be indexed, has a length, and has an equality operator. |
|---|
| 909 | n/a | |
|---|
| 910 | n/a | Args: |
|---|
| 911 | n/a | seq1: The first sequence to compare. |
|---|
| 912 | n/a | seq2: The second sequence to compare. |
|---|
| 913 | n/a | seq_type: The expected datatype of the sequences, or None if no |
|---|
| 914 | n/a | datatype should be enforced. |
|---|
| 915 | n/a | msg: Optional message to use on failure instead of a list of |
|---|
| 916 | n/a | differences. |
|---|
| 917 | n/a | """ |
|---|
| 918 | n/a | if seq_type is not None: |
|---|
| 919 | n/a | seq_type_name = seq_type.__name__ |
|---|
| 920 | n/a | if not isinstance(seq1, seq_type): |
|---|
| 921 | n/a | raise self.failureException('First sequence is not a %s: %s' |
|---|
| 922 | n/a | % (seq_type_name, safe_repr(seq1))) |
|---|
| 923 | n/a | if not isinstance(seq2, seq_type): |
|---|
| 924 | n/a | raise self.failureException('Second sequence is not a %s: %s' |
|---|
| 925 | n/a | % (seq_type_name, safe_repr(seq2))) |
|---|
| 926 | n/a | else: |
|---|
| 927 | n/a | seq_type_name = "sequence" |
|---|
| 928 | n/a | |
|---|
| 929 | n/a | differing = None |
|---|
| 930 | n/a | try: |
|---|
| 931 | n/a | len1 = len(seq1) |
|---|
| 932 | n/a | except (TypeError, NotImplementedError): |
|---|
| 933 | n/a | differing = 'First %s has no length. Non-sequence?' % ( |
|---|
| 934 | n/a | seq_type_name) |
|---|
| 935 | n/a | |
|---|
| 936 | n/a | if differing is None: |
|---|
| 937 | n/a | try: |
|---|
| 938 | n/a | len2 = len(seq2) |
|---|
| 939 | n/a | except (TypeError, NotImplementedError): |
|---|
| 940 | n/a | differing = 'Second %s has no length. Non-sequence?' % ( |
|---|
| 941 | n/a | seq_type_name) |
|---|
| 942 | n/a | |
|---|
| 943 | n/a | if differing is None: |
|---|
| 944 | n/a | if seq1 == seq2: |
|---|
| 945 | n/a | return |
|---|
| 946 | n/a | |
|---|
| 947 | n/a | differing = '%ss differ: %s != %s\n' % ( |
|---|
| 948 | n/a | (seq_type_name.capitalize(),) + |
|---|
| 949 | n/a | _common_shorten_repr(seq1, seq2)) |
|---|
| 950 | n/a | |
|---|
| 951 | n/a | for i in range(min(len1, len2)): |
|---|
| 952 | n/a | try: |
|---|
| 953 | n/a | item1 = seq1[i] |
|---|
| 954 | n/a | except (TypeError, IndexError, NotImplementedError): |
|---|
| 955 | n/a | differing += ('\nUnable to index element %d of first %s\n' % |
|---|
| 956 | n/a | (i, seq_type_name)) |
|---|
| 957 | n/a | break |
|---|
| 958 | n/a | |
|---|
| 959 | n/a | try: |
|---|
| 960 | n/a | item2 = seq2[i] |
|---|
| 961 | n/a | except (TypeError, IndexError, NotImplementedError): |
|---|
| 962 | n/a | differing += ('\nUnable to index element %d of second %s\n' % |
|---|
| 963 | n/a | (i, seq_type_name)) |
|---|
| 964 | n/a | break |
|---|
| 965 | n/a | |
|---|
| 966 | n/a | if item1 != item2: |
|---|
| 967 | n/a | differing += ('\nFirst differing element %d:\n%s\n%s\n' % |
|---|
| 968 | n/a | ((i,) + _common_shorten_repr(item1, item2))) |
|---|
| 969 | n/a | break |
|---|
| 970 | n/a | else: |
|---|
| 971 | n/a | if (len1 == len2 and seq_type is None and |
|---|
| 972 | n/a | type(seq1) != type(seq2)): |
|---|
| 973 | n/a | # The sequences are the same, but have differing types. |
|---|
| 974 | n/a | return |
|---|
| 975 | n/a | |
|---|
| 976 | n/a | if len1 > len2: |
|---|
| 977 | n/a | differing += ('\nFirst %s contains %d additional ' |
|---|
| 978 | n/a | 'elements.\n' % (seq_type_name, len1 - len2)) |
|---|
| 979 | n/a | try: |
|---|
| 980 | n/a | differing += ('First extra element %d:\n%s\n' % |
|---|
| 981 | n/a | (len2, safe_repr(seq1[len2]))) |
|---|
| 982 | n/a | except (TypeError, IndexError, NotImplementedError): |
|---|
| 983 | n/a | differing += ('Unable to index element %d ' |
|---|
| 984 | n/a | 'of first %s\n' % (len2, seq_type_name)) |
|---|
| 985 | n/a | elif len1 < len2: |
|---|
| 986 | n/a | differing += ('\nSecond %s contains %d additional ' |
|---|
| 987 | n/a | 'elements.\n' % (seq_type_name, len2 - len1)) |
|---|
| 988 | n/a | try: |
|---|
| 989 | n/a | differing += ('First extra element %d:\n%s\n' % |
|---|
| 990 | n/a | (len1, safe_repr(seq2[len1]))) |
|---|
| 991 | n/a | except (TypeError, IndexError, NotImplementedError): |
|---|
| 992 | n/a | differing += ('Unable to index element %d ' |
|---|
| 993 | n/a | 'of second %s\n' % (len1, seq_type_name)) |
|---|
| 994 | n/a | standardMsg = differing |
|---|
| 995 | n/a | diffMsg = '\n' + '\n'.join( |
|---|
| 996 | n/a | difflib.ndiff(pprint.pformat(seq1).splitlines(), |
|---|
| 997 | n/a | pprint.pformat(seq2).splitlines())) |
|---|
| 998 | n/a | |
|---|
| 999 | n/a | standardMsg = self._truncateMessage(standardMsg, diffMsg) |
|---|
| 1000 | n/a | msg = self._formatMessage(msg, standardMsg) |
|---|
| 1001 | n/a | self.fail(msg) |
|---|
| 1002 | n/a | |
|---|
| 1003 | n/a | def _truncateMessage(self, message, diff): |
|---|
| 1004 | n/a | max_diff = self.maxDiff |
|---|
| 1005 | n/a | if max_diff is None or len(diff) <= max_diff: |
|---|
| 1006 | n/a | return message + diff |
|---|
| 1007 | n/a | return message + (DIFF_OMITTED % len(diff)) |
|---|
| 1008 | n/a | |
|---|
| 1009 | n/a | def assertListEqual(self, list1, list2, msg=None): |
|---|
| 1010 | n/a | """A list-specific equality assertion. |
|---|
| 1011 | n/a | |
|---|
| 1012 | n/a | Args: |
|---|
| 1013 | n/a | list1: The first list to compare. |
|---|
| 1014 | n/a | list2: The second list to compare. |
|---|
| 1015 | n/a | msg: Optional message to use on failure instead of a list of |
|---|
| 1016 | n/a | differences. |
|---|
| 1017 | n/a | |
|---|
| 1018 | n/a | """ |
|---|
| 1019 | n/a | self.assertSequenceEqual(list1, list2, msg, seq_type=list) |
|---|
| 1020 | n/a | |
|---|
| 1021 | n/a | def assertTupleEqual(self, tuple1, tuple2, msg=None): |
|---|
| 1022 | n/a | """A tuple-specific equality assertion. |
|---|
| 1023 | n/a | |
|---|
| 1024 | n/a | Args: |
|---|
| 1025 | n/a | tuple1: The first tuple to compare. |
|---|
| 1026 | n/a | tuple2: The second tuple to compare. |
|---|
| 1027 | n/a | msg: Optional message to use on failure instead of a list of |
|---|
| 1028 | n/a | differences. |
|---|
| 1029 | n/a | """ |
|---|
| 1030 | n/a | self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple) |
|---|
| 1031 | n/a | |
|---|
| 1032 | n/a | def assertSetEqual(self, set1, set2, msg=None): |
|---|
| 1033 | n/a | """A set-specific equality assertion. |
|---|
| 1034 | n/a | |
|---|
| 1035 | n/a | Args: |
|---|
| 1036 | n/a | set1: The first set to compare. |
|---|
| 1037 | n/a | set2: The second set to compare. |
|---|
| 1038 | n/a | msg: Optional message to use on failure instead of a list of |
|---|
| 1039 | n/a | differences. |
|---|
| 1040 | n/a | |
|---|
| 1041 | n/a | assertSetEqual uses ducktyping to support different types of sets, and |
|---|
| 1042 | n/a | is optimized for sets specifically (parameters must support a |
|---|
| 1043 | n/a | difference method). |
|---|
| 1044 | n/a | """ |
|---|
| 1045 | n/a | try: |
|---|
| 1046 | n/a | difference1 = set1.difference(set2) |
|---|
| 1047 | n/a | except TypeError as e: |
|---|
| 1048 | n/a | self.fail('invalid type when attempting set difference: %s' % e) |
|---|
| 1049 | n/a | except AttributeError as e: |
|---|
| 1050 | n/a | self.fail('first argument does not support set difference: %s' % e) |
|---|
| 1051 | n/a | |
|---|
| 1052 | n/a | try: |
|---|
| 1053 | n/a | difference2 = set2.difference(set1) |
|---|
| 1054 | n/a | except TypeError as e: |
|---|
| 1055 | n/a | self.fail('invalid type when attempting set difference: %s' % e) |
|---|
| 1056 | n/a | except AttributeError as e: |
|---|
| 1057 | n/a | self.fail('second argument does not support set difference: %s' % e) |
|---|
| 1058 | n/a | |
|---|
| 1059 | n/a | if not (difference1 or difference2): |
|---|
| 1060 | n/a | return |
|---|
| 1061 | n/a | |
|---|
| 1062 | n/a | lines = [] |
|---|
| 1063 | n/a | if difference1: |
|---|
| 1064 | n/a | lines.append('Items in the first set but not the second:') |
|---|
| 1065 | n/a | for item in difference1: |
|---|
| 1066 | n/a | lines.append(repr(item)) |
|---|
| 1067 | n/a | if difference2: |
|---|
| 1068 | n/a | lines.append('Items in the second set but not the first:') |
|---|
| 1069 | n/a | for item in difference2: |
|---|
| 1070 | n/a | lines.append(repr(item)) |
|---|
| 1071 | n/a | |
|---|
| 1072 | n/a | standardMsg = '\n'.join(lines) |
|---|
| 1073 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1074 | n/a | |
|---|
| 1075 | n/a | def assertIn(self, member, container, msg=None): |
|---|
| 1076 | n/a | """Just like self.assertTrue(a in b), but with a nicer default message.""" |
|---|
| 1077 | n/a | if member not in container: |
|---|
| 1078 | n/a | standardMsg = '%s not found in %s' % (safe_repr(member), |
|---|
| 1079 | n/a | safe_repr(container)) |
|---|
| 1080 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1081 | n/a | |
|---|
| 1082 | n/a | def assertNotIn(self, member, container, msg=None): |
|---|
| 1083 | n/a | """Just like self.assertTrue(a not in b), but with a nicer default message.""" |
|---|
| 1084 | n/a | if member in container: |
|---|
| 1085 | n/a | standardMsg = '%s unexpectedly found in %s' % (safe_repr(member), |
|---|
| 1086 | n/a | safe_repr(container)) |
|---|
| 1087 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1088 | n/a | |
|---|
| 1089 | n/a | def assertIs(self, expr1, expr2, msg=None): |
|---|
| 1090 | n/a | """Just like self.assertTrue(a is b), but with a nicer default message.""" |
|---|
| 1091 | n/a | if expr1 is not expr2: |
|---|
| 1092 | n/a | standardMsg = '%s is not %s' % (safe_repr(expr1), |
|---|
| 1093 | n/a | safe_repr(expr2)) |
|---|
| 1094 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1095 | n/a | |
|---|
| 1096 | n/a | def assertIsNot(self, expr1, expr2, msg=None): |
|---|
| 1097 | n/a | """Just like self.assertTrue(a is not b), but with a nicer default message.""" |
|---|
| 1098 | n/a | if expr1 is expr2: |
|---|
| 1099 | n/a | standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),) |
|---|
| 1100 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1101 | n/a | |
|---|
| 1102 | n/a | def assertDictEqual(self, d1, d2, msg=None): |
|---|
| 1103 | n/a | self.assertIsInstance(d1, dict, 'First argument is not a dictionary') |
|---|
| 1104 | n/a | self.assertIsInstance(d2, dict, 'Second argument is not a dictionary') |
|---|
| 1105 | n/a | |
|---|
| 1106 | n/a | if d1 != d2: |
|---|
| 1107 | n/a | standardMsg = '%s != %s' % _common_shorten_repr(d1, d2) |
|---|
| 1108 | n/a | diff = ('\n' + '\n'.join(difflib.ndiff( |
|---|
| 1109 | n/a | pprint.pformat(d1).splitlines(), |
|---|
| 1110 | n/a | pprint.pformat(d2).splitlines()))) |
|---|
| 1111 | n/a | standardMsg = self._truncateMessage(standardMsg, diff) |
|---|
| 1112 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1113 | n/a | |
|---|
| 1114 | n/a | def assertDictContainsSubset(self, subset, dictionary, msg=None): |
|---|
| 1115 | n/a | """Checks whether dictionary is a superset of subset.""" |
|---|
| 1116 | n/a | warnings.warn('assertDictContainsSubset is deprecated', |
|---|
| 1117 | n/a | DeprecationWarning) |
|---|
| 1118 | n/a | missing = [] |
|---|
| 1119 | n/a | mismatched = [] |
|---|
| 1120 | n/a | for key, value in subset.items(): |
|---|
| 1121 | n/a | if key not in dictionary: |
|---|
| 1122 | n/a | missing.append(key) |
|---|
| 1123 | n/a | elif value != dictionary[key]: |
|---|
| 1124 | n/a | mismatched.append('%s, expected: %s, actual: %s' % |
|---|
| 1125 | n/a | (safe_repr(key), safe_repr(value), |
|---|
| 1126 | n/a | safe_repr(dictionary[key]))) |
|---|
| 1127 | n/a | |
|---|
| 1128 | n/a | if not (missing or mismatched): |
|---|
| 1129 | n/a | return |
|---|
| 1130 | n/a | |
|---|
| 1131 | n/a | standardMsg = '' |
|---|
| 1132 | n/a | if missing: |
|---|
| 1133 | n/a | standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in |
|---|
| 1134 | n/a | missing) |
|---|
| 1135 | n/a | if mismatched: |
|---|
| 1136 | n/a | if standardMsg: |
|---|
| 1137 | n/a | standardMsg += '; ' |
|---|
| 1138 | n/a | standardMsg += 'Mismatched values: %s' % ','.join(mismatched) |
|---|
| 1139 | n/a | |
|---|
| 1140 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1141 | n/a | |
|---|
| 1142 | n/a | |
|---|
| 1143 | n/a | def assertCountEqual(self, first, second, msg=None): |
|---|
| 1144 | n/a | """An unordered sequence comparison asserting that the same elements, |
|---|
| 1145 | n/a | regardless of order. If the same element occurs more than once, |
|---|
| 1146 | n/a | it verifies that the elements occur the same number of times. |
|---|
| 1147 | n/a | |
|---|
| 1148 | n/a | self.assertEqual(Counter(list(first)), |
|---|
| 1149 | n/a | Counter(list(second))) |
|---|
| 1150 | n/a | |
|---|
| 1151 | n/a | Example: |
|---|
| 1152 | n/a | - [0, 1, 1] and [1, 0, 1] compare equal. |
|---|
| 1153 | n/a | - [0, 0, 1] and [0, 1] compare unequal. |
|---|
| 1154 | n/a | |
|---|
| 1155 | n/a | """ |
|---|
| 1156 | n/a | first_seq, second_seq = list(first), list(second) |
|---|
| 1157 | n/a | try: |
|---|
| 1158 | n/a | first = collections.Counter(first_seq) |
|---|
| 1159 | n/a | second = collections.Counter(second_seq) |
|---|
| 1160 | n/a | except TypeError: |
|---|
| 1161 | n/a | # Handle case with unhashable elements |
|---|
| 1162 | n/a | differences = _count_diff_all_purpose(first_seq, second_seq) |
|---|
| 1163 | n/a | else: |
|---|
| 1164 | n/a | if first == second: |
|---|
| 1165 | n/a | return |
|---|
| 1166 | n/a | differences = _count_diff_hashable(first_seq, second_seq) |
|---|
| 1167 | n/a | |
|---|
| 1168 | n/a | if differences: |
|---|
| 1169 | n/a | standardMsg = 'Element counts were not equal:\n' |
|---|
| 1170 | n/a | lines = ['First has %d, Second has %d: %r' % diff for diff in differences] |
|---|
| 1171 | n/a | diffMsg = '\n'.join(lines) |
|---|
| 1172 | n/a | standardMsg = self._truncateMessage(standardMsg, diffMsg) |
|---|
| 1173 | n/a | msg = self._formatMessage(msg, standardMsg) |
|---|
| 1174 | n/a | self.fail(msg) |
|---|
| 1175 | n/a | |
|---|
| 1176 | n/a | def assertMultiLineEqual(self, first, second, msg=None): |
|---|
| 1177 | n/a | """Assert that two multi-line strings are equal.""" |
|---|
| 1178 | n/a | self.assertIsInstance(first, str, 'First argument is not a string') |
|---|
| 1179 | n/a | self.assertIsInstance(second, str, 'Second argument is not a string') |
|---|
| 1180 | n/a | |
|---|
| 1181 | n/a | if first != second: |
|---|
| 1182 | n/a | # don't use difflib if the strings are too long |
|---|
| 1183 | n/a | if (len(first) > self._diffThreshold or |
|---|
| 1184 | n/a | len(second) > self._diffThreshold): |
|---|
| 1185 | n/a | self._baseAssertEqual(first, second, msg) |
|---|
| 1186 | n/a | firstlines = first.splitlines(keepends=True) |
|---|
| 1187 | n/a | secondlines = second.splitlines(keepends=True) |
|---|
| 1188 | n/a | if len(firstlines) == 1 and first.strip('\r\n') == first: |
|---|
| 1189 | n/a | firstlines = [first + '\n'] |
|---|
| 1190 | n/a | secondlines = [second + '\n'] |
|---|
| 1191 | n/a | standardMsg = '%s != %s' % _common_shorten_repr(first, second) |
|---|
| 1192 | n/a | diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines)) |
|---|
| 1193 | n/a | standardMsg = self._truncateMessage(standardMsg, diff) |
|---|
| 1194 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1195 | n/a | |
|---|
| 1196 | n/a | def assertLess(self, a, b, msg=None): |
|---|
| 1197 | n/a | """Just like self.assertTrue(a < b), but with a nicer default message.""" |
|---|
| 1198 | n/a | if not a < b: |
|---|
| 1199 | n/a | standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b)) |
|---|
| 1200 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1201 | n/a | |
|---|
| 1202 | n/a | def assertLessEqual(self, a, b, msg=None): |
|---|
| 1203 | n/a | """Just like self.assertTrue(a <= b), but with a nicer default message.""" |
|---|
| 1204 | n/a | if not a <= b: |
|---|
| 1205 | n/a | standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b)) |
|---|
| 1206 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1207 | n/a | |
|---|
| 1208 | n/a | def assertGreater(self, a, b, msg=None): |
|---|
| 1209 | n/a | """Just like self.assertTrue(a > b), but with a nicer default message.""" |
|---|
| 1210 | n/a | if not a > b: |
|---|
| 1211 | n/a | standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b)) |
|---|
| 1212 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1213 | n/a | |
|---|
| 1214 | n/a | def assertGreaterEqual(self, a, b, msg=None): |
|---|
| 1215 | n/a | """Just like self.assertTrue(a >= b), but with a nicer default message.""" |
|---|
| 1216 | n/a | if not a >= b: |
|---|
| 1217 | n/a | standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b)) |
|---|
| 1218 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1219 | n/a | |
|---|
| 1220 | n/a | def assertIsNone(self, obj, msg=None): |
|---|
| 1221 | n/a | """Same as self.assertTrue(obj is None), with a nicer default message.""" |
|---|
| 1222 | n/a | if obj is not None: |
|---|
| 1223 | n/a | standardMsg = '%s is not None' % (safe_repr(obj),) |
|---|
| 1224 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1225 | n/a | |
|---|
| 1226 | n/a | def assertIsNotNone(self, obj, msg=None): |
|---|
| 1227 | n/a | """Included for symmetry with assertIsNone.""" |
|---|
| 1228 | n/a | if obj is None: |
|---|
| 1229 | n/a | standardMsg = 'unexpectedly None' |
|---|
| 1230 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1231 | n/a | |
|---|
| 1232 | n/a | def assertIsInstance(self, obj, cls, msg=None): |
|---|
| 1233 | n/a | """Same as self.assertTrue(isinstance(obj, cls)), with a nicer |
|---|
| 1234 | n/a | default message.""" |
|---|
| 1235 | n/a | if not isinstance(obj, cls): |
|---|
| 1236 | n/a | standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls) |
|---|
| 1237 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1238 | n/a | |
|---|
| 1239 | n/a | def assertNotIsInstance(self, obj, cls, msg=None): |
|---|
| 1240 | n/a | """Included for symmetry with assertIsInstance.""" |
|---|
| 1241 | n/a | if isinstance(obj, cls): |
|---|
| 1242 | n/a | standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls) |
|---|
| 1243 | n/a | self.fail(self._formatMessage(msg, standardMsg)) |
|---|
| 1244 | n/a | |
|---|
| 1245 | n/a | def assertRaisesRegex(self, expected_exception, expected_regex, |
|---|
| 1246 | n/a | *args, **kwargs): |
|---|
| 1247 | n/a | """Asserts that the message in a raised exception matches a regex. |
|---|
| 1248 | n/a | |
|---|
| 1249 | n/a | Args: |
|---|
| 1250 | n/a | expected_exception: Exception class expected to be raised. |
|---|
| 1251 | n/a | expected_regex: Regex (re pattern object or string) expected |
|---|
| 1252 | n/a | to be found in error message. |
|---|
| 1253 | n/a | args: Function to be called and extra positional args. |
|---|
| 1254 | n/a | kwargs: Extra kwargs. |
|---|
| 1255 | n/a | msg: Optional message used in case of failure. Can only be used |
|---|
| 1256 | n/a | when assertRaisesRegex is used as a context manager. |
|---|
| 1257 | n/a | """ |
|---|
| 1258 | n/a | context = _AssertRaisesContext(expected_exception, self, expected_regex) |
|---|
| 1259 | n/a | return context.handle('assertRaisesRegex', args, kwargs) |
|---|
| 1260 | n/a | |
|---|
| 1261 | n/a | def assertWarnsRegex(self, expected_warning, expected_regex, |
|---|
| 1262 | n/a | *args, **kwargs): |
|---|
| 1263 | n/a | """Asserts that the message in a triggered warning matches a regexp. |
|---|
| 1264 | n/a | Basic functioning is similar to assertWarns() with the addition |
|---|
| 1265 | n/a | that only warnings whose messages also match the regular expression |
|---|
| 1266 | n/a | are considered successful matches. |
|---|
| 1267 | n/a | |
|---|
| 1268 | n/a | Args: |
|---|
| 1269 | n/a | expected_warning: Warning class expected to be triggered. |
|---|
| 1270 | n/a | expected_regex: Regex (re pattern object or string) expected |
|---|
| 1271 | n/a | to be found in error message. |
|---|
| 1272 | n/a | args: Function to be called and extra positional args. |
|---|
| 1273 | n/a | kwargs: Extra kwargs. |
|---|
| 1274 | n/a | msg: Optional message used in case of failure. Can only be used |
|---|
| 1275 | n/a | when assertWarnsRegex is used as a context manager. |
|---|
| 1276 | n/a | """ |
|---|
| 1277 | n/a | context = _AssertWarnsContext(expected_warning, self, expected_regex) |
|---|
| 1278 | n/a | return context.handle('assertWarnsRegex', args, kwargs) |
|---|
| 1279 | n/a | |
|---|
| 1280 | n/a | def assertRegex(self, text, expected_regex, msg=None): |
|---|
| 1281 | n/a | """Fail the test unless the text matches the regular expression.""" |
|---|
| 1282 | n/a | if isinstance(expected_regex, (str, bytes)): |
|---|
| 1283 | n/a | assert expected_regex, "expected_regex must not be empty." |
|---|
| 1284 | n/a | expected_regex = re.compile(expected_regex) |
|---|
| 1285 | n/a | if not expected_regex.search(text): |
|---|
| 1286 | n/a | standardMsg = "Regex didn't match: %r not found in %r" % ( |
|---|
| 1287 | n/a | expected_regex.pattern, text) |
|---|
| 1288 | n/a | # _formatMessage ensures the longMessage option is respected |
|---|
| 1289 | n/a | msg = self._formatMessage(msg, standardMsg) |
|---|
| 1290 | n/a | raise self.failureException(msg) |
|---|
| 1291 | n/a | |
|---|
| 1292 | n/a | def assertNotRegex(self, text, unexpected_regex, msg=None): |
|---|
| 1293 | n/a | """Fail the test if the text matches the regular expression.""" |
|---|
| 1294 | n/a | if isinstance(unexpected_regex, (str, bytes)): |
|---|
| 1295 | n/a | unexpected_regex = re.compile(unexpected_regex) |
|---|
| 1296 | n/a | match = unexpected_regex.search(text) |
|---|
| 1297 | n/a | if match: |
|---|
| 1298 | n/a | standardMsg = 'Regex matched: %r matches %r in %r' % ( |
|---|
| 1299 | n/a | text[match.start() : match.end()], |
|---|
| 1300 | n/a | unexpected_regex.pattern, |
|---|
| 1301 | n/a | text) |
|---|
| 1302 | n/a | # _formatMessage ensures the longMessage option is respected |
|---|
| 1303 | n/a | msg = self._formatMessage(msg, standardMsg) |
|---|
| 1304 | n/a | raise self.failureException(msg) |
|---|
| 1305 | n/a | |
|---|
| 1306 | n/a | |
|---|
| 1307 | n/a | def _deprecate(original_func): |
|---|
| 1308 | n/a | def deprecated_func(*args, **kwargs): |
|---|
| 1309 | n/a | warnings.warn( |
|---|
| 1310 | n/a | 'Please use {0} instead.'.format(original_func.__name__), |
|---|
| 1311 | n/a | DeprecationWarning, 2) |
|---|
| 1312 | n/a | return original_func(*args, **kwargs) |
|---|
| 1313 | n/a | return deprecated_func |
|---|
| 1314 | n/a | |
|---|
| 1315 | n/a | # see #9424 |
|---|
| 1316 | n/a | failUnlessEqual = assertEquals = _deprecate(assertEqual) |
|---|
| 1317 | n/a | failIfEqual = assertNotEquals = _deprecate(assertNotEqual) |
|---|
| 1318 | n/a | failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual) |
|---|
| 1319 | n/a | failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual) |
|---|
| 1320 | n/a | failUnless = assert_ = _deprecate(assertTrue) |
|---|
| 1321 | n/a | failUnlessRaises = _deprecate(assertRaises) |
|---|
| 1322 | n/a | failIf = _deprecate(assertFalse) |
|---|
| 1323 | n/a | assertRaisesRegexp = _deprecate(assertRaisesRegex) |
|---|
| 1324 | n/a | assertRegexpMatches = _deprecate(assertRegex) |
|---|
| 1325 | n/a | assertNotRegexpMatches = _deprecate(assertNotRegex) |
|---|
| 1326 | n/a | |
|---|
| 1327 | n/a | |
|---|
| 1328 | n/a | |
|---|
| 1329 | n/a | class FunctionTestCase(TestCase): |
|---|
| 1330 | n/a | """A test case that wraps a test function. |
|---|
| 1331 | n/a | |
|---|
| 1332 | n/a | This is useful for slipping pre-existing test functions into the |
|---|
| 1333 | n/a | unittest framework. Optionally, set-up and tidy-up functions can be |
|---|
| 1334 | n/a | supplied. As with TestCase, the tidy-up ('tearDown') function will |
|---|
| 1335 | n/a | always be called if the set-up ('setUp') function ran successfully. |
|---|
| 1336 | n/a | """ |
|---|
| 1337 | n/a | |
|---|
| 1338 | n/a | def __init__(self, testFunc, setUp=None, tearDown=None, description=None): |
|---|
| 1339 | n/a | super(FunctionTestCase, self).__init__() |
|---|
| 1340 | n/a | self._setUpFunc = setUp |
|---|
| 1341 | n/a | self._tearDownFunc = tearDown |
|---|
| 1342 | n/a | self._testFunc = testFunc |
|---|
| 1343 | n/a | self._description = description |
|---|
| 1344 | n/a | |
|---|
| 1345 | n/a | def setUp(self): |
|---|
| 1346 | n/a | if self._setUpFunc is not None: |
|---|
| 1347 | n/a | self._setUpFunc() |
|---|
| 1348 | n/a | |
|---|
| 1349 | n/a | def tearDown(self): |
|---|
| 1350 | n/a | if self._tearDownFunc is not None: |
|---|
| 1351 | n/a | self._tearDownFunc() |
|---|
| 1352 | n/a | |
|---|
| 1353 | n/a | def runTest(self): |
|---|
| 1354 | n/a | self._testFunc() |
|---|
| 1355 | n/a | |
|---|
| 1356 | n/a | def id(self): |
|---|
| 1357 | n/a | return self._testFunc.__name__ |
|---|
| 1358 | n/a | |
|---|
| 1359 | n/a | def __eq__(self, other): |
|---|
| 1360 | n/a | if not isinstance(other, self.__class__): |
|---|
| 1361 | n/a | return NotImplemented |
|---|
| 1362 | n/a | |
|---|
| 1363 | n/a | return self._setUpFunc == other._setUpFunc and \ |
|---|
| 1364 | n/a | self._tearDownFunc == other._tearDownFunc and \ |
|---|
| 1365 | n/a | self._testFunc == other._testFunc and \ |
|---|
| 1366 | n/a | self._description == other._description |
|---|
| 1367 | n/a | |
|---|
| 1368 | n/a | def __hash__(self): |
|---|
| 1369 | n/a | return hash((type(self), self._setUpFunc, self._tearDownFunc, |
|---|
| 1370 | n/a | self._testFunc, self._description)) |
|---|
| 1371 | n/a | |
|---|
| 1372 | n/a | def __str__(self): |
|---|
| 1373 | n/a | return "%s (%s)" % (strclass(self.__class__), |
|---|
| 1374 | n/a | self._testFunc.__name__) |
|---|
| 1375 | n/a | |
|---|
| 1376 | n/a | def __repr__(self): |
|---|
| 1377 | n/a | return "<%s tec=%s>" % (strclass(self.__class__), |
|---|
| 1378 | n/a | self._testFunc) |
|---|
| 1379 | n/a | |
|---|
| 1380 | n/a | def shortDescription(self): |
|---|
| 1381 | n/a | if self._description is not None: |
|---|
| 1382 | n/a | return self._description |
|---|
| 1383 | n/a | doc = self._testFunc.__doc__ |
|---|
| 1384 | n/a | return doc and doc.split("\n")[0].strip() or None |
|---|
| 1385 | n/a | |
|---|
| 1386 | n/a | |
|---|
| 1387 | n/a | class _SubTest(TestCase): |
|---|
| 1388 | n/a | |
|---|
| 1389 | n/a | def __init__(self, test_case, message, params): |
|---|
| 1390 | n/a | super().__init__() |
|---|
| 1391 | n/a | self._message = message |
|---|
| 1392 | n/a | self.test_case = test_case |
|---|
| 1393 | n/a | self.params = params |
|---|
| 1394 | n/a | self.failureException = test_case.failureException |
|---|
| 1395 | n/a | |
|---|
| 1396 | n/a | def runTest(self): |
|---|
| 1397 | n/a | raise NotImplementedError("subtests cannot be run directly") |
|---|
| 1398 | n/a | |
|---|
| 1399 | n/a | def _subDescription(self): |
|---|
| 1400 | n/a | parts = [] |
|---|
| 1401 | n/a | if self._message is not _subtest_msg_sentinel: |
|---|
| 1402 | n/a | parts.append("[{}]".format(self._message)) |
|---|
| 1403 | n/a | if self.params: |
|---|
| 1404 | n/a | params_desc = ', '.join( |
|---|
| 1405 | n/a | "{}={!r}".format(k, v) |
|---|
| 1406 | n/a | for (k, v) in sorted(self.params.items())) |
|---|
| 1407 | n/a | parts.append("({})".format(params_desc)) |
|---|
| 1408 | n/a | return " ".join(parts) or '(<subtest>)' |
|---|
| 1409 | n/a | |
|---|
| 1410 | n/a | def id(self): |
|---|
| 1411 | n/a | return "{} {}".format(self.test_case.id(), self._subDescription()) |
|---|
| 1412 | n/a | |
|---|
| 1413 | n/a | def shortDescription(self): |
|---|
| 1414 | n/a | """Returns a one-line description of the subtest, or None if no |
|---|
| 1415 | n/a | description has been provided. |
|---|
| 1416 | n/a | """ |
|---|
| 1417 | n/a | return self.test_case.shortDescription() |
|---|
| 1418 | n/a | |
|---|
| 1419 | n/a | def __str__(self): |
|---|
| 1420 | n/a | return "{} {}".format(self.test_case, self._subDescription()) |
|---|