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