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