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