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