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