Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 2 | ''' |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 3 | Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's |
| 4 | Smalltalk testing framework. |
| 5 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 6 | This module contains the core framework classes that form the basis of |
| 7 | specific test cases and suites (TestCase, TestSuite etc.), and also a |
| 8 | text-based utility class for running the tests and reporting the results |
Jeremy Hylton | efef5da | 2001-10-22 18:14:15 +0000 | [diff] [blame] | 9 | (TextTestRunner). |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 10 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 11 | Simple usage: |
| 12 | |
| 13 | import unittest |
| 14 | |
| 15 | class IntegerArithmenticTestCase(unittest.TestCase): |
| 16 | def testAdd(self): ## test method names begin 'test*' |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 17 | self.assertEqual((1 + 2), 3) |
| 18 | self.assertEqual(0 + 1, 1) |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 19 | def testMultiply(self): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 20 | self.assertEqual((0 * 10), 0) |
| 21 | self.assertEqual((5 * 8), 40) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 22 | |
| 23 | if __name__ == '__main__': |
| 24 | unittest.main() |
| 25 | |
| 26 | Further information is available in the bundled documentation, and from |
| 27 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 28 | http://docs.python.org/library/unittest.html |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 29 | |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 30 | Copyright (c) 1999-2003 Steve Purcell |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 31 | Copyright (c) 2003-2009 Python Software Foundation |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 32 | This module is free software, and you may redistribute it and/or modify |
| 33 | it under the same terms as Python itself, so long as this copyright message |
| 34 | and disclaimer are retained in their original form. |
| 35 | |
| 36 | IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, |
| 37 | SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF |
| 38 | THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH |
| 39 | DAMAGE. |
| 40 | |
| 41 | THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT |
| 42 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
| 43 | PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, |
| 44 | AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, |
| 45 | SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 46 | ''' |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 47 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 48 | import difflib |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 49 | import functools |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 50 | import os |
| 51 | import pprint |
| 52 | import re |
| 53 | import sys |
| 54 | import time |
| 55 | import traceback |
| 56 | import types |
| 57 | import warnings |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 58 | |
| 59 | ############################################################################## |
Steve Purcell | d75e7e4 | 2003-09-15 11:01:21 +0000 | [diff] [blame] | 60 | # Exported classes and functions |
| 61 | ############################################################################## |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame^] | 62 | __all__ = ['TestResult', 'TestCase', 'TestSuite', |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 63 | 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main', |
Benjamin Peterson | 4c93dcb | 2009-03-24 01:33:55 +0000 | [diff] [blame] | 64 | 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless', |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 65 | 'expectedFailure'] |
Steve Purcell | d75e7e4 | 2003-09-15 11:01:21 +0000 | [diff] [blame] | 66 | |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 67 | # Expose obsolete functions for backwards compatibility |
Steve Purcell | d75e7e4 | 2003-09-15 11:01:21 +0000 | [diff] [blame] | 68 | __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases']) |
| 69 | |
| 70 | |
| 71 | ############################################################################## |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 72 | # Test framework core |
| 73 | ############################################################################## |
| 74 | |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 75 | def _strclass(cls): |
| 76 | return "%s.%s" % (cls.__module__, cls.__name__) |
| 77 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 78 | |
| 79 | class SkipTest(Exception): |
| 80 | """ |
| 81 | Raise this exception in a test to skip it. |
| 82 | |
| 83 | Usually you can use TestResult.skip() or one of the skipping decorators |
| 84 | instead of raising this directly. |
| 85 | """ |
| 86 | pass |
| 87 | |
| 88 | class _ExpectedFailure(Exception): |
| 89 | """ |
| 90 | Raise this when a test is expected to fail. |
| 91 | |
| 92 | This is an implementation detail. |
| 93 | """ |
| 94 | |
| 95 | def __init__(self, exc_info): |
| 96 | super(_ExpectedFailure, self).__init__() |
| 97 | self.exc_info = exc_info |
| 98 | |
| 99 | class _UnexpectedSuccess(Exception): |
| 100 | """ |
| 101 | The test was supposed to fail, but it didn't! |
| 102 | """ |
| 103 | pass |
| 104 | |
| 105 | def _id(obj): |
| 106 | return obj |
| 107 | |
| 108 | def skip(reason): |
| 109 | """ |
| 110 | Unconditionally skip a test. |
| 111 | """ |
| 112 | def decorator(test_item): |
| 113 | if isinstance(test_item, type) and issubclass(test_item, TestCase): |
| 114 | test_item.__unittest_skip__ = True |
| 115 | test_item.__unittest_skip_why__ = reason |
| 116 | return test_item |
| 117 | @functools.wraps(test_item) |
| 118 | def skip_wrapper(*args, **kwargs): |
| 119 | raise SkipTest(reason) |
| 120 | return skip_wrapper |
| 121 | return decorator |
| 122 | |
| 123 | def skipIf(condition, reason): |
| 124 | """ |
| 125 | Skip a test if the condition is true. |
| 126 | """ |
| 127 | if condition: |
| 128 | return skip(reason) |
| 129 | return _id |
| 130 | |
| 131 | def skipUnless(condition, reason): |
| 132 | """ |
| 133 | Skip a test unless the condition is true. |
| 134 | """ |
| 135 | if not condition: |
| 136 | return skip(reason) |
| 137 | return _id |
| 138 | |
| 139 | |
| 140 | def expectedFailure(func): |
| 141 | @functools.wraps(func) |
| 142 | def wrapper(*args, **kwargs): |
| 143 | try: |
| 144 | func(*args, **kwargs) |
| 145 | except Exception: |
| 146 | raise _ExpectedFailure(sys.exc_info()) |
| 147 | raise _UnexpectedSuccess |
| 148 | return wrapper |
| 149 | |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 150 | __unittest = 1 |
| 151 | |
Benjamin Peterson | 1467ac8 | 2009-01-09 03:42:38 +0000 | [diff] [blame] | 152 | class TestResult(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 153 | """Holder for test result information. |
| 154 | |
| 155 | Test results are automatically managed by the TestCase and TestSuite |
| 156 | classes, and do not need to be explicitly manipulated by writers of tests. |
| 157 | |
| 158 | Each instance holds the total number of tests run, and collections of |
| 159 | failures and errors that occurred among those test runs. The collections |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 160 | contain tuples of (testcase, exceptioninfo), where exceptioninfo is the |
Fred Drake | 656f9ec | 2001-09-06 19:13:14 +0000 | [diff] [blame] | 161 | formatted traceback of the error that occurred. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 162 | """ |
| 163 | def __init__(self): |
| 164 | self.failures = [] |
| 165 | self.errors = [] |
| 166 | self.testsRun = 0 |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 167 | self.skipped = [] |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 168 | self.expectedFailures = [] |
| 169 | self.unexpectedSuccesses = [] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 170 | self.shouldStop = False |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 171 | |
| 172 | def startTest(self, test): |
| 173 | "Called when the given test is about to be run" |
| 174 | self.testsRun = self.testsRun + 1 |
| 175 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 176 | def startTestRun(self): |
| 177 | """Called once before any tests are executed. |
| 178 | |
| 179 | See startTest for a method called before each test. |
| 180 | """ |
| 181 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 182 | def stopTest(self, test): |
| 183 | "Called when the given test has been run" |
| 184 | pass |
| 185 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 186 | def stopTestRun(self): |
| 187 | """Called once after all tests are executed. |
| 188 | |
| 189 | See stopTest for a method called after each test. |
| 190 | """ |
| 191 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 192 | def addError(self, test, err): |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 193 | """Called when an error has occurred. 'err' is a tuple of values as |
| 194 | returned by sys.exc_info(). |
| 195 | """ |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 196 | self.errors.append((test, self._exc_info_to_string(err, test))) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 197 | |
| 198 | def addFailure(self, test, err): |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 199 | """Called when an error has occurred. 'err' is a tuple of values as |
| 200 | returned by sys.exc_info().""" |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 201 | self.failures.append((test, self._exc_info_to_string(err, test))) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 202 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 203 | def addSuccess(self, test): |
| 204 | "Called when a test has completed successfully" |
| 205 | pass |
| 206 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 207 | def addSkip(self, test, reason): |
| 208 | """Called when a test is skipped.""" |
| 209 | self.skipped.append((test, reason)) |
| 210 | |
| 211 | def addExpectedFailure(self, test, err): |
| 212 | """Called when an expected failure/error occured.""" |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 213 | self.expectedFailures.append( |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 214 | (test, self._exc_info_to_string(err, test))) |
| 215 | |
| 216 | def addUnexpectedSuccess(self, test): |
| 217 | """Called when a test was expected to fail, but succeed.""" |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 218 | self.unexpectedSuccesses.append(test) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 219 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 220 | def wasSuccessful(self): |
| 221 | "Tells whether or not this result was a success" |
| 222 | return len(self.failures) == len(self.errors) == 0 |
| 223 | |
| 224 | def stop(self): |
| 225 | "Indicates that the tests should be aborted" |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 226 | self.shouldStop = True |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 227 | |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 228 | def _exc_info_to_string(self, err, test): |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 229 | """Converts a sys.exc_info()-style tuple of values into a string.""" |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 230 | exctype, value, tb = err |
| 231 | # Skip test runner traceback levels |
| 232 | while tb and self._is_relevant_tb_level(tb): |
| 233 | tb = tb.tb_next |
| 234 | if exctype is test.failureException: |
| 235 | # Skip assert*() traceback levels |
| 236 | length = self._count_relevant_tb_levels(tb) |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 237 | return ''.join(traceback.format_exception(exctype, value, |
| 238 | tb, length)) |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 239 | return ''.join(traceback.format_exception(exctype, value, tb)) |
| 240 | |
| 241 | def _is_relevant_tb_level(self, tb): |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 242 | return '__unittest' in tb.tb_frame.f_globals |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 243 | |
| 244 | def _count_relevant_tb_levels(self, tb): |
| 245 | length = 0 |
| 246 | while tb and not self._is_relevant_tb_level(tb): |
| 247 | length += 1 |
| 248 | tb = tb.tb_next |
| 249 | return length |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 250 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 251 | def __repr__(self): |
| 252 | return "<%s run=%i errors=%i failures=%i>" % \ |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 253 | (_strclass(self.__class__), self.testsRun, len(self.errors), |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 254 | len(self.failures)) |
| 255 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 256 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 257 | class _AssertRaisesContext(object): |
| 258 | """A context manager used to implement TestCase.assertRaises* methods.""" |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 259 | |
| 260 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 261 | def __init__(self, expected, test_case, callable_obj=None, |
| 262 | expected_regexp=None): |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 263 | self.expected = expected |
| 264 | self.failureException = test_case.failureException |
| 265 | if callable_obj is not None: |
| 266 | try: |
| 267 | self.obj_name = callable_obj.__name__ |
| 268 | except AttributeError: |
| 269 | self.obj_name = str(callable_obj) |
| 270 | else: |
| 271 | self.obj_name = None |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 272 | self.expected_regex = expected_regexp |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 273 | |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 274 | def __enter__(self): |
| 275 | pass |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 276 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 277 | def __exit__(self, exc_type, exc_value, tb): |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 278 | if exc_type is None: |
| 279 | try: |
| 280 | exc_name = self.expected.__name__ |
| 281 | except AttributeError: |
| 282 | exc_name = str(self.expected) |
| 283 | if self.obj_name: |
| 284 | raise self.failureException("{0} not raised by {1}" |
| 285 | .format(exc_name, self.obj_name)) |
| 286 | else: |
| 287 | raise self.failureException("{0} not raised" |
| 288 | .format(exc_name)) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 289 | if not issubclass(exc_type, self.expected): |
| 290 | # let unexpected exceptions pass through |
| 291 | return False |
| 292 | if self.expected_regex is None: |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 293 | return True |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 294 | |
| 295 | expected_regexp = self.expected_regex |
| 296 | if isinstance(expected_regexp, (bytes, str)): |
| 297 | expected_regexp = re.compile(expected_regexp) |
| 298 | if not expected_regexp.search(str(exc_value)): |
| 299 | raise self.failureException('"%s" does not match "%s"' % |
| 300 | (expected_regexp.pattern, str(exc_value))) |
| 301 | return True |
| 302 | |
| 303 | |
| 304 | class _AssertWrapper(object): |
| 305 | """Wrap entries in the _type_equality_funcs registry to make them deep |
| 306 | copyable.""" |
| 307 | |
| 308 | def __init__(self, function): |
| 309 | self.function = function |
| 310 | |
| 311 | def __deepcopy__(self, memo): |
| 312 | memo[id(self)] = self |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 313 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 314 | |
Benjamin Peterson | 1467ac8 | 2009-01-09 03:42:38 +0000 | [diff] [blame] | 315 | class TestCase(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 316 | """A class whose instances are single test cases. |
| 317 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 318 | By default, the test code itself should be placed in a method named |
| 319 | 'runTest'. |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 320 | |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 321 | If the fixture may be used for many test cases, create as |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 322 | many test methods as are needed. When instantiating such a TestCase |
| 323 | subclass, specify in the constructor arguments the name of the test method |
| 324 | that the instance is to execute. |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 325 | |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 326 | Test authors should subclass TestCase for their own tests. Construction |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 327 | and deconstruction of the test's environment ('fixture') can be |
| 328 | implemented by overriding the 'setUp' and 'tearDown' methods respectively. |
| 329 | |
| 330 | If it is necessary to override the __init__ method, the base class |
| 331 | __init__ method must always be called. It is important that subclasses |
| 332 | should not change the signature of their __init__ method, since instances |
| 333 | of the classes are instantiated automatically by parts of the framework |
| 334 | in order to be run. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 335 | """ |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 336 | |
| 337 | # This attribute determines which exception will be raised when |
| 338 | # the instance's assertion methods fail; test methods raising this |
| 339 | # exception will be deemed to have 'failed' rather than 'errored' |
| 340 | |
| 341 | failureException = AssertionError |
| 342 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 343 | # This attribute determines whether long messages (including repr of |
| 344 | # objects used in assert methods) will be printed on failure in *addition* |
| 345 | # to any explicit message passed. |
| 346 | |
| 347 | longMessage = False |
| 348 | |
| 349 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 350 | def __init__(self, methodName='runTest'): |
| 351 | """Create an instance of the class that will use the named test |
| 352 | method when executed. Raises a ValueError if the instance does |
| 353 | not have a method with the specified name. |
| 354 | """ |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 355 | self._testMethodName = methodName |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 356 | self._result = None |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 357 | try: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 358 | testMethod = getattr(self, methodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 359 | except AttributeError: |
Benjamin Peterson | 1467ac8 | 2009-01-09 03:42:38 +0000 | [diff] [blame] | 360 | raise ValueError("no such test method in %s: %s" % \ |
| 361 | (self.__class__, methodName)) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 362 | self._testMethodDoc = testMethod.__doc__ |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 363 | self._cleanups = [] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 364 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 365 | # Map types to custom assertEqual functions that will compare |
| 366 | # instances of said type in more detail to generate a more useful |
| 367 | # error message. |
| 368 | self._type_equality_funcs = {} |
| 369 | self.addTypeEqualityFunc(dict, self.assertDictEqual) |
| 370 | self.addTypeEqualityFunc(list, self.assertListEqual) |
| 371 | self.addTypeEqualityFunc(tuple, self.assertTupleEqual) |
| 372 | self.addTypeEqualityFunc(set, self.assertSetEqual) |
| 373 | self.addTypeEqualityFunc(frozenset, self.assertSetEqual) |
| 374 | |
| 375 | def addTypeEqualityFunc(self, typeobj, function): |
| 376 | """Add a type specific assertEqual style function to compare a type. |
| 377 | |
| 378 | This method is for use by TestCase subclasses that need to register |
| 379 | their own type equality functions to provide nicer error messages. |
| 380 | |
| 381 | Args: |
| 382 | typeobj: The data type to call this function on when both values |
| 383 | are of the same type in assertEqual(). |
| 384 | function: The callable taking two arguments and an optional |
| 385 | msg= argument that raises self.failureException with a |
| 386 | useful error message when the two arguments are not equal. |
| 387 | """ |
| 388 | self._type_equality_funcs[typeobj] = _AssertWrapper(function) |
| 389 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 390 | def addCleanup(self, function, *args, **kwargs): |
| 391 | """Add a function, with arguments, to be called when the test is |
| 392 | completed. Functions added are called on a LIFO basis and are |
| 393 | called after tearDown on test failure or success. |
| 394 | |
| 395 | Cleanup items are called even if setUp fails (unlike tearDown).""" |
| 396 | self._cleanups.append((function, args, kwargs)) |
| 397 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 398 | def setUp(self): |
| 399 | "Hook method for setting up the test fixture before exercising it." |
| 400 | pass |
| 401 | |
| 402 | def tearDown(self): |
| 403 | "Hook method for deconstructing the test fixture after testing it." |
| 404 | pass |
| 405 | |
| 406 | def countTestCases(self): |
| 407 | return 1 |
| 408 | |
| 409 | def defaultTestResult(self): |
| 410 | return TestResult() |
| 411 | |
| 412 | def shortDescription(self): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 413 | """Returns both the test method name and first line of its docstring. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 414 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 415 | If no docstring is given, only returns the method name. |
| 416 | |
| 417 | This method overrides unittest.TestCase.shortDescription(), which |
| 418 | only returns the first line of the docstring, obscuring the name |
| 419 | of the test upon failure. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 420 | """ |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 421 | desc = str(self) |
| 422 | doc_first_line = None |
| 423 | |
| 424 | if self._testMethodDoc: |
| 425 | doc_first_line = self._testMethodDoc.split("\n")[0].strip() |
| 426 | if doc_first_line: |
| 427 | desc = '\n'.join((desc, doc_first_line)) |
| 428 | return desc |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 429 | |
| 430 | def id(self): |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 431 | return "%s.%s" % (_strclass(self.__class__), self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 432 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 433 | def __eq__(self, other): |
| 434 | if type(self) is not type(other): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 435 | return NotImplemented |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 436 | |
| 437 | return self._testMethodName == other._testMethodName |
| 438 | |
| 439 | def __ne__(self, other): |
| 440 | return not self == other |
| 441 | |
| 442 | def __hash__(self): |
| 443 | return hash((type(self), self._testMethodName)) |
| 444 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 445 | def __str__(self): |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 446 | return "%s (%s)" % (self._testMethodName, _strclass(self.__class__)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 447 | |
| 448 | def __repr__(self): |
| 449 | return "<%s testMethod=%s>" % \ |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 450 | (_strclass(self.__class__), self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 451 | |
| 452 | def run(self, result=None): |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 453 | orig_result = result |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 454 | if result is None: |
| 455 | result = self.defaultTestResult() |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 456 | startTestRun = getattr(result, 'startTestRun', None) |
| 457 | if startTestRun is not None: |
| 458 | startTestRun() |
| 459 | |
| 460 | self._result = result |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 461 | result.startTest(self) |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame^] | 462 | if getattr(self.__class__, "__unittest_skip__", False): |
| 463 | # If the whole class was skipped. |
| 464 | try: |
| 465 | result.addSkip(self, self.__class__.__unittest_skip_why__) |
| 466 | finally: |
| 467 | result.stopTest(self) |
| 468 | return |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 469 | testMethod = getattr(self, self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 470 | try: |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 471 | success = False |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 472 | try: |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 473 | self.setUp() |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 474 | except SkipTest as e: |
| 475 | result.addSkip(self, str(e)) |
Benjamin Peterson | 1467ac8 | 2009-01-09 03:42:38 +0000 | [diff] [blame] | 476 | except Exception: |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 477 | result.addError(self, sys.exc_info()) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 478 | else: |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 479 | try: |
| 480 | testMethod() |
| 481 | except self.failureException: |
| 482 | result.addFailure(self, sys.exc_info()) |
| 483 | except _ExpectedFailure as e: |
| 484 | result.addExpectedFailure(self, e.exc_info) |
| 485 | except _UnexpectedSuccess: |
| 486 | result.addUnexpectedSuccess(self) |
| 487 | except SkipTest as e: |
| 488 | result.addSkip(self, str(e)) |
| 489 | except Exception: |
| 490 | result.addError(self, sys.exc_info()) |
| 491 | else: |
| 492 | success = True |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 493 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 494 | try: |
| 495 | self.tearDown() |
| 496 | except Exception: |
| 497 | result.addError(self, sys.exc_info()) |
| 498 | success = False |
| 499 | |
| 500 | cleanUpSuccess = self.doCleanups() |
| 501 | success = success and cleanUpSuccess |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 502 | if success: |
| 503 | result.addSuccess(self) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 504 | finally: |
| 505 | result.stopTest(self) |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 506 | if orig_result is None: |
| 507 | stopTestRun = getattr(result, 'stopTestRun', None) |
| 508 | if stopTestRun is not None: |
| 509 | stopTestRun() |
| 510 | |
| 511 | def doCleanups(self): |
| 512 | """Execute all cleanup functions. Normally called for you after |
| 513 | tearDown.""" |
| 514 | result = self._result |
| 515 | ok = True |
| 516 | while self._cleanups: |
| 517 | function, args, kwargs = self._cleanups.pop(-1) |
| 518 | try: |
| 519 | function(*args, **kwargs) |
| 520 | except Exception: |
| 521 | ok = False |
| 522 | result.addError(self, sys.exc_info()) |
| 523 | return ok |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 524 | |
Raymond Hettinger | 664347b | 2004-12-04 21:21:53 +0000 | [diff] [blame] | 525 | def __call__(self, *args, **kwds): |
| 526 | return self.run(*args, **kwds) |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 527 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 528 | def debug(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 529 | """Run the test without collecting errors in a TestResult""" |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 530 | self.setUp() |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 531 | getattr(self, self._testMethodName)() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 532 | self.tearDown() |
| 533 | |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 534 | def skipTest(self, reason): |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 535 | """Skip this test.""" |
| 536 | raise SkipTest(reason) |
| 537 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 538 | def fail(self, msg=None): |
| 539 | """Fail immediately, with the given message.""" |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 540 | raise self.failureException(msg) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 541 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 542 | def assertFalse(self, expr, msg=None): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 543 | "Fail the test if the expression is true." |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 544 | if expr: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 545 | msg = self._formatMessage(msg, "%r is not False" % expr) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 546 | raise self.failureException(msg) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 547 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 548 | def assertTrue(self, expr, msg=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 549 | """Fail the test unless the expression is true.""" |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 550 | if not expr: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 551 | msg = self._formatMessage(msg, "%r is not True" % expr) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 552 | raise self.failureException(msg) |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 553 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 554 | def _formatMessage(self, msg, standardMsg): |
| 555 | """Honour the longMessage attribute when generating failure messages. |
| 556 | If longMessage is False this means: |
| 557 | * Use only an explicit message if it is provided |
| 558 | * Otherwise use the standard message for the assert |
| 559 | |
| 560 | If longMessage is True: |
| 561 | * Use the standard message |
| 562 | * If an explicit message is provided, plus ' : ' and the explicit message |
| 563 | """ |
| 564 | if not self.longMessage: |
| 565 | return msg or standardMsg |
| 566 | if msg is None: |
| 567 | return standardMsg |
| 568 | return standardMsg + ' : ' + msg |
| 569 | |
| 570 | |
| 571 | def assertRaises(self, excClass, callableObj=None, *args, **kwargs): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 572 | """Fail unless an exception of class excClass is thrown |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 573 | by callableObj when invoked with arguments args and keyword |
| 574 | arguments kwargs. If a different type of exception is |
| 575 | thrown, it will not be caught, and the test case will be |
| 576 | deemed to have suffered an error, exactly as for an |
| 577 | unexpected exception. |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 578 | |
| 579 | If called with callableObj omitted or None, will return a |
| 580 | context object used like this:: |
| 581 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 582 | with self.assertRaises(some_error_class): |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 583 | do_something() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 584 | """ |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 585 | context = _AssertRaisesContext(excClass, self, callableObj) |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 586 | if callableObj is None: |
| 587 | return context |
| 588 | with context: |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 589 | callableObj(*args, **kwargs) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 590 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 591 | def _getAssertEqualityFunc(self, first, second): |
| 592 | """Get a detailed comparison function for the types of the two args. |
| 593 | |
| 594 | Returns: A callable accepting (first, second, msg=None) that will |
| 595 | raise a failure exception if first != second with a useful human |
| 596 | readable error message for those types. |
| 597 | """ |
| 598 | # |
| 599 | # NOTE(gregory.p.smith): I considered isinstance(first, type(second)) |
| 600 | # and vice versa. I opted for the conservative approach in case |
| 601 | # subclasses are not intended to be compared in detail to their super |
| 602 | # class instances using a type equality func. This means testing |
| 603 | # subtypes won't automagically use the detailed comparison. Callers |
| 604 | # should use their type specific assertSpamEqual method to compare |
| 605 | # subclasses if the detailed comparison is desired and appropriate. |
| 606 | # See the discussion in http://bugs.python.org/issue2578. |
| 607 | # |
| 608 | if type(first) is type(second): |
| 609 | asserter = self._type_equality_funcs.get(type(first)) |
| 610 | if asserter is not None: |
| 611 | return asserter.function |
| 612 | |
| 613 | return self._baseAssertEqual |
| 614 | |
| 615 | def _baseAssertEqual(self, first, second, msg=None): |
| 616 | """The default assertEqual implementation, not type specific.""" |
| 617 | if not first == second: |
| 618 | standardMsg = '%r != %r' % (first, second) |
| 619 | msg = self._formatMessage(msg, standardMsg) |
| 620 | raise self.failureException(msg) |
| 621 | |
| 622 | def assertEqual(self, first, second, msg=None): |
Raymond Hettinger | c377cbf | 2003-04-04 22:56:42 +0000 | [diff] [blame] | 623 | """Fail if the two objects are unequal as determined by the '==' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 624 | operator. |
| 625 | """ |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 626 | assertion_func = self._getAssertEqualityFunc(first, second) |
| 627 | assertion_func(first, second, msg=msg) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 628 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 629 | def assertNotEqual(self, first, second, msg=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 630 | """Fail if the two objects are equal as determined by the '==' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 631 | operator. |
| 632 | """ |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 633 | if not first != second: |
| 634 | msg = self._formatMessage(msg, '%r == %r' % (first, second)) |
| 635 | raise self.failureException(msg) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 636 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 637 | def assertAlmostEqual(self, first, second, *, places=7, msg=None): |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 638 | """Fail if the two objects are unequal as determined by their |
| 639 | difference rounded to the given number of decimal places |
| 640 | (default 7) and comparing to zero. |
| 641 | |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 642 | Note that decimal places (from zero) are usually not the same |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 643 | as significant digits (measured from the most signficant digit). |
| 644 | """ |
Jeffrey Yasskin | 1cc5544 | 2007-09-06 18:55:17 +0000 | [diff] [blame] | 645 | if round(abs(second-first), places) != 0: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 646 | standardMsg = '%r != %r within %r places' % (first, second, places) |
| 647 | msg = self._formatMessage(msg, standardMsg) |
| 648 | raise self.failureException(msg) |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 649 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 650 | def assertNotAlmostEqual(self, first, second, *, places=7, msg=None): |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 651 | """Fail if the two objects are equal as determined by their |
| 652 | difference rounded to the given number of decimal places |
| 653 | (default 7) and comparing to zero. |
| 654 | |
Steve Purcell | cca3491 | 2003-10-26 16:38:16 +0000 | [diff] [blame] | 655 | Note that decimal places (from zero) are usually not the same |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 656 | as significant digits (measured from the most signficant digit). |
| 657 | """ |
Jeffrey Yasskin | 1cc5544 | 2007-09-06 18:55:17 +0000 | [diff] [blame] | 658 | if round(abs(second-first), places) == 0: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 659 | standardMsg = '%r == %r within %r places' % (first, second, places) |
| 660 | msg = self._formatMessage(msg, standardMsg) |
| 661 | raise self.failureException(msg) |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 662 | |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 663 | # Synonyms for assertion methods |
| 664 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 665 | # The plurals are undocumented. Keep them that way to discourage use. |
| 666 | # Do not add more. Do not remove. |
| 667 | # Going through a deprecation cycle on these would annoy many people. |
| 668 | assertEquals = assertEqual |
| 669 | assertNotEquals = assertNotEqual |
| 670 | assertAlmostEquals = assertAlmostEqual |
| 671 | assertNotAlmostEquals = assertNotAlmostEqual |
| 672 | assert_ = assertTrue |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 673 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 674 | # These fail* assertion method names are pending deprecation and will |
| 675 | # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578 |
| 676 | def _deprecate(original_func): |
| 677 | def deprecated_func(*args, **kwargs): |
| 678 | warnings.warn( |
| 679 | 'Please use {0} instead.'.format(original_func.__name__), |
| 680 | PendingDeprecationWarning, 2) |
| 681 | return original_func(*args, **kwargs) |
| 682 | return deprecated_func |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 683 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 684 | failUnlessEqual = _deprecate(assertEqual) |
| 685 | failIfEqual = _deprecate(assertNotEqual) |
| 686 | failUnlessAlmostEqual = _deprecate(assertAlmostEqual) |
| 687 | failIfAlmostEqual = _deprecate(assertNotAlmostEqual) |
| 688 | failUnless = _deprecate(assertTrue) |
| 689 | failUnlessRaises = _deprecate(assertRaises) |
| 690 | failIf = _deprecate(assertFalse) |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 691 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 692 | def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): |
| 693 | """An equality assertion for ordered sequences (like lists and tuples). |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 694 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 695 | For the purposes of this function, a valid orderd sequence type is one |
| 696 | which can be indexed, has a length, and has an equality operator. |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 697 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 698 | Args: |
| 699 | seq1: The first sequence to compare. |
| 700 | seq2: The second sequence to compare. |
| 701 | seq_type: The expected datatype of the sequences, or None if no |
| 702 | datatype should be enforced. |
| 703 | msg: Optional message to use on failure instead of a list of |
| 704 | differences. |
| 705 | """ |
| 706 | if seq_type != None: |
| 707 | seq_type_name = seq_type.__name__ |
| 708 | if not isinstance(seq1, seq_type): |
| 709 | raise self.failureException('First sequence is not a %s: %r' |
| 710 | % (seq_type_name, seq1)) |
| 711 | if not isinstance(seq2, seq_type): |
| 712 | raise self.failureException('Second sequence is not a %s: %r' |
| 713 | % (seq_type_name, seq2)) |
| 714 | else: |
| 715 | seq_type_name = "sequence" |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 716 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 717 | differing = None |
| 718 | try: |
| 719 | len1 = len(seq1) |
| 720 | except (TypeError, NotImplementedError): |
| 721 | differing = 'First %s has no length. Non-sequence?' % ( |
| 722 | seq_type_name) |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 723 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 724 | if differing is None: |
| 725 | try: |
| 726 | len2 = len(seq2) |
| 727 | except (TypeError, NotImplementedError): |
| 728 | differing = 'Second %s has no length. Non-sequence?' % ( |
| 729 | seq_type_name) |
| 730 | |
| 731 | if differing is None: |
| 732 | if seq1 == seq2: |
| 733 | return |
| 734 | |
| 735 | for i in range(min(len1, len2)): |
| 736 | try: |
| 737 | item1 = seq1[i] |
| 738 | except (TypeError, IndexError, NotImplementedError): |
| 739 | differing = ('Unable to index element %d of first %s\n' % |
| 740 | (i, seq_type_name)) |
| 741 | break |
| 742 | |
| 743 | try: |
| 744 | item2 = seq2[i] |
| 745 | except (TypeError, IndexError, NotImplementedError): |
| 746 | differing = ('Unable to index element %d of second %s\n' % |
| 747 | (i, seq_type_name)) |
| 748 | break |
| 749 | |
| 750 | if item1 != item2: |
| 751 | differing = ('First differing element %d:\n%s\n%s\n' % |
| 752 | (i, item1, item2)) |
| 753 | break |
| 754 | else: |
| 755 | if (len1 == len2 and seq_type is None and |
| 756 | type(seq1) != type(seq2)): |
| 757 | # The sequences are the same, but have differing types. |
| 758 | return |
| 759 | # A catch-all message for handling arbitrary user-defined |
| 760 | # sequences. |
| 761 | differing = '%ss differ:\n' % seq_type_name.capitalize() |
| 762 | if len1 > len2: |
| 763 | differing = ('First %s contains %d additional ' |
| 764 | 'elements.\n' % (seq_type_name, len1 - len2)) |
| 765 | try: |
| 766 | differing += ('First extra element %d:\n%s\n' % |
| 767 | (len2, seq1[len2])) |
| 768 | except (TypeError, IndexError, NotImplementedError): |
| 769 | differing += ('Unable to index element %d ' |
| 770 | 'of first %s\n' % (len2, seq_type_name)) |
| 771 | elif len1 < len2: |
| 772 | differing = ('Second %s contains %d additional ' |
| 773 | 'elements.\n' % (seq_type_name, len2 - len1)) |
| 774 | try: |
| 775 | differing += ('First extra element %d:\n%s\n' % |
| 776 | (len1, seq2[len1])) |
| 777 | except (TypeError, IndexError, NotImplementedError): |
| 778 | differing += ('Unable to index element %d ' |
| 779 | 'of second %s\n' % (len1, seq_type_name)) |
| 780 | standardMsg = differing + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(), |
| 781 | pprint.pformat(seq2).splitlines())) |
| 782 | msg = self._formatMessage(msg, standardMsg) |
| 783 | self.fail(msg) |
| 784 | |
| 785 | def assertListEqual(self, list1, list2, msg=None): |
| 786 | """A list-specific equality assertion. |
| 787 | |
| 788 | Args: |
| 789 | list1: The first list to compare. |
| 790 | list2: The second list to compare. |
| 791 | msg: Optional message to use on failure instead of a list of |
| 792 | differences. |
| 793 | |
| 794 | """ |
| 795 | self.assertSequenceEqual(list1, list2, msg, seq_type=list) |
| 796 | |
| 797 | def assertTupleEqual(self, tuple1, tuple2, msg=None): |
| 798 | """A tuple-specific equality assertion. |
| 799 | |
| 800 | Args: |
| 801 | tuple1: The first tuple to compare. |
| 802 | tuple2: The second tuple to compare. |
| 803 | msg: Optional message to use on failure instead of a list of |
| 804 | differences. |
| 805 | """ |
| 806 | self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple) |
| 807 | |
| 808 | def assertSetEqual(self, set1, set2, msg=None): |
| 809 | """A set-specific equality assertion. |
| 810 | |
| 811 | Args: |
| 812 | set1: The first set to compare. |
| 813 | set2: The second set to compare. |
| 814 | msg: Optional message to use on failure instead of a list of |
| 815 | differences. |
| 816 | |
| 817 | For more general containership equality, assertSameElements will work |
| 818 | with things other than sets. This uses ducktyping to support |
| 819 | different types of sets, and is optimized for sets specifically |
| 820 | (parameters must support a difference method). |
| 821 | """ |
| 822 | try: |
| 823 | difference1 = set1.difference(set2) |
| 824 | except TypeError as e: |
| 825 | self.fail('invalid type when attempting set difference: %s' % e) |
| 826 | except AttributeError as e: |
| 827 | self.fail('first argument does not support set difference: %s' % e) |
| 828 | |
| 829 | try: |
| 830 | difference2 = set2.difference(set1) |
| 831 | except TypeError as e: |
| 832 | self.fail('invalid type when attempting set difference: %s' % e) |
| 833 | except AttributeError as e: |
| 834 | self.fail('second argument does not support set difference: %s' % e) |
| 835 | |
| 836 | if not (difference1 or difference2): |
| 837 | return |
| 838 | |
| 839 | lines = [] |
| 840 | if difference1: |
| 841 | lines.append('Items in the first set but not the second:') |
| 842 | for item in difference1: |
| 843 | lines.append(repr(item)) |
| 844 | if difference2: |
| 845 | lines.append('Items in the second set but not the first:') |
| 846 | for item in difference2: |
| 847 | lines.append(repr(item)) |
| 848 | |
| 849 | standardMsg = '\n'.join(lines) |
| 850 | self.fail(self._formatMessage(msg, standardMsg)) |
| 851 | |
| 852 | def assertIn(self, member, container, msg=None): |
| 853 | """Just like self.assertTrue(a in b), but with a nicer default message.""" |
| 854 | if member not in container: |
| 855 | standardMsg = '%r not found in %r' % (member, container) |
| 856 | self.fail(self._formatMessage(msg, standardMsg)) |
| 857 | |
| 858 | def assertNotIn(self, member, container, msg=None): |
| 859 | """Just like self.assertTrue(a not in b), but with a nicer default message.""" |
| 860 | if member in container: |
| 861 | standardMsg = '%r unexpectedly found in %r' % (member, container) |
| 862 | self.fail(self._formatMessage(msg, standardMsg)) |
| 863 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 864 | def assertIs(self, expr1, expr2, msg=None): |
| 865 | """Just like self.assertTrue(a is b), but with a nicer default message.""" |
| 866 | if expr1 is not expr2: |
| 867 | standardMsg = '%r is not %r' % (expr1, expr2) |
| 868 | self.fail(self._formatMessage(msg, standardMsg)) |
| 869 | |
| 870 | def assertIsNot(self, expr1, expr2, msg=None): |
| 871 | """Just like self.assertTrue(a is not b), but with a nicer default message.""" |
| 872 | if expr1 is expr2: |
| 873 | standardMsg = 'unexpectedly identical: %r' % (expr1,) |
| 874 | self.fail(self._formatMessage(msg, standardMsg)) |
| 875 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 876 | def assertDictEqual(self, d1, d2, msg=None): |
| 877 | self.assert_(isinstance(d1, dict), 'First argument is not a dictionary') |
| 878 | self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary') |
| 879 | |
| 880 | if d1 != d2: |
| 881 | standardMsg = ('\n' + '\n'.join(difflib.ndiff( |
| 882 | pprint.pformat(d1).splitlines(), |
| 883 | pprint.pformat(d2).splitlines()))) |
| 884 | self.fail(self._formatMessage(msg, standardMsg)) |
| 885 | |
| 886 | def assertDictContainsSubset(self, expected, actual, msg=None): |
| 887 | """Checks whether actual is a superset of expected.""" |
| 888 | missing = [] |
| 889 | mismatched = [] |
| 890 | for key, value in expected.items(): |
| 891 | if key not in actual: |
| 892 | missing.append(key) |
| 893 | elif value != actual[key]: |
| 894 | mismatched.append('%s, expected: %s, actual: %s' % (key, value, actual[key])) |
| 895 | |
| 896 | if not (missing or mismatched): |
| 897 | return |
| 898 | |
| 899 | standardMsg = '' |
| 900 | if missing: |
| 901 | standardMsg = 'Missing: %r' % ','.join(missing) |
| 902 | if mismatched: |
| 903 | if standardMsg: |
| 904 | standardMsg += '; ' |
| 905 | standardMsg += 'Mismatched values: %s' % ','.join(mismatched) |
| 906 | |
| 907 | self.fail(self._formatMessage(msg, standardMsg)) |
| 908 | |
| 909 | def assertSameElements(self, expected_seq, actual_seq, msg=None): |
| 910 | """An unordered sequence specific comparison. |
| 911 | |
| 912 | Raises with an error message listing which elements of expected_seq |
| 913 | are missing from actual_seq and vice versa if any. |
| 914 | """ |
| 915 | try: |
| 916 | expected = set(expected_seq) |
| 917 | actual = set(actual_seq) |
| 918 | missing = list(expected.difference(actual)) |
| 919 | unexpected = list(actual.difference(expected)) |
| 920 | missing.sort() |
| 921 | unexpected.sort() |
| 922 | except TypeError: |
| 923 | # Fall back to slower list-compare if any of the objects are |
| 924 | # not hashable. |
| 925 | expected = list(expected_seq) |
| 926 | actual = list(actual_seq) |
Michael Foord | a5809c8 | 2009-04-04 18:55:09 +0000 | [diff] [blame] | 927 | try: |
| 928 | expected.sort() |
| 929 | actual.sort() |
| 930 | except TypeError: |
| 931 | missing, unexpected = _UnorderableListDifference(expected, actual) |
| 932 | else: |
| 933 | missing, unexpected = _SortedListDifference(expected, actual) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 934 | errors = [] |
| 935 | if missing: |
| 936 | errors.append('Expected, but missing:\n %r' % missing) |
| 937 | if unexpected: |
| 938 | errors.append('Unexpected, but present:\n %r' % unexpected) |
| 939 | if errors: |
| 940 | standardMsg = '\n'.join(errors) |
| 941 | self.fail(self._formatMessage(msg, standardMsg)) |
| 942 | |
| 943 | def assertMultiLineEqual(self, first, second, msg=None): |
| 944 | """Assert that two multi-line strings are equal.""" |
| 945 | self.assert_(isinstance(first, str), ( |
| 946 | 'First argument is not a string')) |
| 947 | self.assert_(isinstance(second, str), ( |
| 948 | 'Second argument is not a string')) |
| 949 | |
| 950 | if first != second: |
| 951 | standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True))) |
| 952 | self.fail(self._formatMessage(msg, standardMsg)) |
| 953 | |
| 954 | def assertLess(self, a, b, msg=None): |
| 955 | """Just like self.assertTrue(a < b), but with a nicer default message.""" |
| 956 | if not a < b: |
| 957 | standardMsg = '%r not less than %r' % (a, b) |
| 958 | self.fail(self._formatMessage(msg, standardMsg)) |
| 959 | |
| 960 | def assertLessEqual(self, a, b, msg=None): |
| 961 | """Just like self.assertTrue(a <= b), but with a nicer default message.""" |
| 962 | if not a <= b: |
| 963 | standardMsg = '%r not less than or equal to %r' % (a, b) |
| 964 | self.fail(self._formatMessage(msg, standardMsg)) |
| 965 | |
| 966 | def assertGreater(self, a, b, msg=None): |
| 967 | """Just like self.assertTrue(a > b), but with a nicer default message.""" |
| 968 | if not a > b: |
| 969 | standardMsg = '%r not greater than %r' % (a, b) |
| 970 | self.fail(self._formatMessage(msg, standardMsg)) |
| 971 | |
| 972 | def assertGreaterEqual(self, a, b, msg=None): |
| 973 | """Just like self.assertTrue(a >= b), but with a nicer default message.""" |
| 974 | if not a >= b: |
| 975 | standardMsg = '%r not greater than or equal to %r' % (a, b) |
| 976 | self.fail(self._formatMessage(msg, standardMsg)) |
| 977 | |
| 978 | def assertIsNone(self, obj, msg=None): |
| 979 | """Same as self.assertTrue(obj is None), with a nicer default message.""" |
| 980 | if obj is not None: |
| 981 | standardMsg = '%r is not None' % obj |
| 982 | self.fail(self._formatMessage(msg, standardMsg)) |
| 983 | |
| 984 | def assertIsNotNone(self, obj, msg=None): |
| 985 | """Included for symmetry with assertIsNone.""" |
| 986 | if obj is None: |
| 987 | standardMsg = 'unexpectedly None' |
| 988 | self.fail(self._formatMessage(msg, standardMsg)) |
| 989 | |
| 990 | def assertRaisesRegexp(self, expected_exception, expected_regexp, |
| 991 | callable_obj=None, *args, **kwargs): |
| 992 | """Asserts that the message in a raised exception matches a regexp. |
| 993 | |
| 994 | Args: |
| 995 | expected_exception: Exception class expected to be raised. |
| 996 | expected_regexp: Regexp (re pattern object or string) expected |
| 997 | to be found in error message. |
| 998 | callable_obj: Function to be called. |
| 999 | args: Extra args. |
| 1000 | kwargs: Extra kwargs. |
| 1001 | """ |
| 1002 | context = _AssertRaisesContext(expected_exception, self, callable_obj, |
| 1003 | expected_regexp) |
| 1004 | if callable_obj is None: |
| 1005 | return context |
| 1006 | with context: |
| 1007 | callable_obj(*args, **kwargs) |
| 1008 | |
| 1009 | def assertRegexpMatches(self, text, expected_regex, msg=None): |
| 1010 | if isinstance(expected_regex, (str, bytes)): |
| 1011 | expected_regex = re.compile(expected_regex) |
| 1012 | if not expected_regex.search(text): |
| 1013 | msg = msg or "Regexp didn't match" |
| 1014 | msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text) |
| 1015 | raise self.failureException(msg) |
| 1016 | |
| 1017 | |
| 1018 | def _SortedListDifference(expected, actual): |
| 1019 | """Finds elements in only one or the other of two, sorted input lists. |
| 1020 | |
| 1021 | Returns a two-element tuple of lists. The first list contains those |
| 1022 | elements in the "expected" list but not in the "actual" list, and the |
| 1023 | second contains those elements in the "actual" list but not in the |
| 1024 | "expected" list. Duplicate elements in either input list are ignored. |
| 1025 | """ |
| 1026 | i = j = 0 |
| 1027 | missing = [] |
| 1028 | unexpected = [] |
| 1029 | while True: |
| 1030 | try: |
| 1031 | e = expected[i] |
| 1032 | a = actual[j] |
| 1033 | if e < a: |
| 1034 | missing.append(e) |
| 1035 | i += 1 |
| 1036 | while expected[i] == e: |
| 1037 | i += 1 |
| 1038 | elif e > a: |
| 1039 | unexpected.append(a) |
| 1040 | j += 1 |
| 1041 | while actual[j] == a: |
| 1042 | j += 1 |
| 1043 | else: |
| 1044 | i += 1 |
| 1045 | try: |
| 1046 | while expected[i] == e: |
| 1047 | i += 1 |
| 1048 | finally: |
| 1049 | j += 1 |
| 1050 | while actual[j] == a: |
| 1051 | j += 1 |
| 1052 | except IndexError: |
| 1053 | missing.extend(expected[i:]) |
| 1054 | unexpected.extend(actual[j:]) |
| 1055 | break |
| 1056 | return missing, unexpected |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1057 | |
Michael Foord | a5809c8 | 2009-04-04 18:55:09 +0000 | [diff] [blame] | 1058 | def _UnorderableListDifference(expected, actual): |
| 1059 | """Same behavior as _SortedListDifference but |
| 1060 | for lists of unorderable items (like dicts). |
| 1061 | |
| 1062 | As it does a linear search per item (remove) it |
| 1063 | has O(n*n) performance.""" |
| 1064 | missing = [] |
| 1065 | while expected: |
| 1066 | item = expected.pop() |
| 1067 | try: |
| 1068 | actual.remove(item) |
| 1069 | except ValueError: |
| 1070 | missing.append(item) |
| 1071 | |
| 1072 | # anything left in actual is unexpected |
| 1073 | return missing, actual |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1074 | |
Benjamin Peterson | 1467ac8 | 2009-01-09 03:42:38 +0000 | [diff] [blame] | 1075 | class TestSuite(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1076 | """A test suite is a composite test consisting of a number of TestCases. |
| 1077 | |
| 1078 | For use, create an instance of TestSuite, then add test case instances. |
| 1079 | When all tests have been added, the suite can be passed to a test |
| 1080 | runner, such as TextTestRunner. It will run the individual test cases |
| 1081 | in the order in which they were added, aggregating the results. When |
| 1082 | subclassing, do not forget to call the base class constructor. |
| 1083 | """ |
| 1084 | def __init__(self, tests=()): |
| 1085 | self._tests = [] |
| 1086 | self.addTests(tests) |
| 1087 | |
| 1088 | def __repr__(self): |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 1089 | return "<%s tests=%s>" % (_strclass(self.__class__), list(self)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1090 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1091 | def __eq__(self, other): |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1092 | if not isinstance(other, self.__class__): |
| 1093 | return NotImplemented |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1094 | return list(self) == list(other) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1095 | |
| 1096 | def __ne__(self, other): |
| 1097 | return not self == other |
| 1098 | |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 1099 | def __iter__(self): |
| 1100 | return iter(self._tests) |
| 1101 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1102 | def countTestCases(self): |
| 1103 | cases = 0 |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 1104 | for test in self: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1105 | cases += test.countTestCases() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1106 | return cases |
| 1107 | |
| 1108 | def addTest(self, test): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1109 | # sanity checks |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 1110 | if not hasattr(test, '__call__'): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1111 | raise TypeError("the test to add must be callable") |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 1112 | if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1113 | raise TypeError("TestCases and TestSuites must be instantiated " |
| 1114 | "before passing them to addTest()") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1115 | self._tests.append(test) |
| 1116 | |
| 1117 | def addTests(self, tests): |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 1118 | if isinstance(tests, str): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1119 | raise TypeError("tests must be an iterable of tests, not a string") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1120 | for test in tests: |
| 1121 | self.addTest(test) |
| 1122 | |
| 1123 | def run(self, result): |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 1124 | for test in self: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1125 | if result.shouldStop: |
| 1126 | break |
| 1127 | test(result) |
| 1128 | return result |
| 1129 | |
Raymond Hettinger | 664347b | 2004-12-04 21:21:53 +0000 | [diff] [blame] | 1130 | def __call__(self, *args, **kwds): |
| 1131 | return self.run(*args, **kwds) |
| 1132 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1133 | def debug(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1134 | """Run the tests without collecting errors in a TestResult""" |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 1135 | for test in self: |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1136 | test.debug() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1137 | |
| 1138 | |
| 1139 | class FunctionTestCase(TestCase): |
| 1140 | """A test case that wraps a test function. |
| 1141 | |
| 1142 | This is useful for slipping pre-existing test functions into the |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1143 | unittest framework. Optionally, set-up and tidy-up functions can be |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1144 | supplied. As with TestCase, the tidy-up ('tearDown') function will |
| 1145 | always be called if the set-up ('setUp') function ran successfully. |
| 1146 | """ |
| 1147 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1148 | def __init__(self, testFunc, setUp=None, tearDown=None, description=None): |
| 1149 | super(FunctionTestCase, self).__init__() |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1150 | self._setUpFunc = setUp |
| 1151 | self._tearDownFunc = tearDown |
| 1152 | self._testFunc = testFunc |
| 1153 | self._description = description |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1154 | |
| 1155 | def setUp(self): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1156 | if self._setUpFunc is not None: |
| 1157 | self._setUpFunc() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1158 | |
| 1159 | def tearDown(self): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1160 | if self._tearDownFunc is not None: |
| 1161 | self._tearDownFunc() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1162 | |
| 1163 | def runTest(self): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1164 | self._testFunc() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1165 | |
| 1166 | def id(self): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1167 | return self._testFunc.__name__ |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1168 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1169 | def __eq__(self, other): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1170 | if not isinstance(other, self.__class__): |
| 1171 | return NotImplemented |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1172 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1173 | return self._setUpFunc == other._setUpFunc and \ |
| 1174 | self._tearDownFunc == other._tearDownFunc and \ |
| 1175 | self._testFunc == other._testFunc and \ |
| 1176 | self._description == other._description |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1177 | |
| 1178 | def __ne__(self, other): |
| 1179 | return not self == other |
| 1180 | |
| 1181 | def __hash__(self): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1182 | return hash((type(self), self._setUpFunc, self._tearDownFunc, |
| 1183 | self._testFunc, self._description)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1184 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1185 | def __str__(self): |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1186 | return "%s (%s)" % (_strclass(self.__class__), self._testFunc.__name__) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1187 | |
| 1188 | def __repr__(self): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1189 | return "<%s testFunc=%s>" % (_strclass(self.__class__), self._testFunc) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1190 | |
| 1191 | def shortDescription(self): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1192 | if self._description is not None: |
| 1193 | return self._description |
| 1194 | doc = self._testFunc.__doc__ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1195 | return doc and doc.split("\n")[0].strip() or None |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1196 | |
| 1197 | |
| 1198 | |
| 1199 | ############################################################################## |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1200 | # Locating and loading tests |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1201 | ############################################################################## |
| 1202 | |
Raymond Hettinger | d4cb56d | 2008-01-30 02:55:10 +0000 | [diff] [blame] | 1203 | def CmpToKey(mycmp): |
| 1204 | 'Convert a cmp= function into a key= function' |
| 1205 | class K(object): |
| 1206 | def __init__(self, obj, *args): |
| 1207 | self.obj = obj |
| 1208 | def __lt__(self, other): |
| 1209 | return mycmp(self.obj, other.obj) == -1 |
| 1210 | return K |
| 1211 | |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1212 | def three_way_cmp(x, y): |
| 1213 | """Return -1 if x < y, 0 if x == y and 1 if x > y""" |
| 1214 | return (x > y) - (x < y) |
| 1215 | |
Benjamin Peterson | 1467ac8 | 2009-01-09 03:42:38 +0000 | [diff] [blame] | 1216 | class TestLoader(object): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1217 | """ |
| 1218 | This class is responsible for loading tests according to various criteria |
| 1219 | and returning them wrapped in a TestSuite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1220 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1221 | testMethodPrefix = 'test' |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1222 | sortTestMethodsUsing = staticmethod(three_way_cmp) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1223 | suiteClass = TestSuite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1224 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1225 | def loadTestsFromTestCase(self, testCaseClass): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1226 | """Return a suite of all tests cases contained in testCaseClass""" |
Johannes Gijsbers | d7b6ad4 | 2004-11-07 15:46:25 +0000 | [diff] [blame] | 1227 | if issubclass(testCaseClass, TestSuite): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1228 | raise TypeError("Test cases should not be derived from TestSuite." \ |
| 1229 | " Maybe you meant to derive from TestCase?") |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1230 | testCaseNames = self.getTestCaseNames(testCaseClass) |
| 1231 | if not testCaseNames and hasattr(testCaseClass, 'runTest'): |
| 1232 | testCaseNames = ['runTest'] |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame^] | 1233 | suite = self.suiteClass(map(testCaseClass, testCaseNames)) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1234 | return suite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1235 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1236 | def loadTestsFromModule(self, module): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1237 | """Return a suite of all tests cases contained in the given module""" |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1238 | tests = [] |
| 1239 | for name in dir(module): |
| 1240 | obj = getattr(module, name) |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 1241 | if isinstance(obj, type) and issubclass(obj, TestCase): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1242 | tests.append(self.loadTestsFromTestCase(obj)) |
| 1243 | return self.suiteClass(tests) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1244 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1245 | def loadTestsFromName(self, name, module=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1246 | """Return a suite of all tests cases given a string specifier. |
| 1247 | |
| 1248 | The name may resolve either to a module, a test case class, a |
| 1249 | test method within a test case class, or a callable object which |
| 1250 | returns a TestCase or TestSuite instance. |
Tim Peters | 613b222 | 2001-04-13 05:37:27 +0000 | [diff] [blame] | 1251 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1252 | The method optionally resolves the names relative to a given module. |
| 1253 | """ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1254 | parts = name.split('.') |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1255 | if module is None: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1256 | parts_copy = parts[:] |
| 1257 | while parts_copy: |
| 1258 | try: |
| 1259 | module = __import__('.'.join(parts_copy)) |
| 1260 | break |
| 1261 | except ImportError: |
| 1262 | del parts_copy[-1] |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1263 | if not parts_copy: |
| 1264 | raise |
Armin Rigo | 1b3c04b | 2003-10-24 17:15:29 +0000 | [diff] [blame] | 1265 | parts = parts[1:] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1266 | obj = module |
| 1267 | for part in parts: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1268 | parent, obj = obj, getattr(obj, part) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1269 | |
Benjamin Peterson | 1467ac8 | 2009-01-09 03:42:38 +0000 | [diff] [blame] | 1270 | if isinstance(obj, types.ModuleType): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1271 | return self.loadTestsFromModule(obj) |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 1272 | elif isinstance(obj, type) and issubclass(obj, TestCase): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1273 | return self.loadTestsFromTestCase(obj) |
Christian Heimes | 4a22b5d | 2007-11-25 09:39:14 +0000 | [diff] [blame] | 1274 | elif (isinstance(obj, types.FunctionType) and |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 1275 | isinstance(parent, type) and |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1276 | issubclass(parent, TestCase)): |
Christian Heimes | 4a22b5d | 2007-11-25 09:39:14 +0000 | [diff] [blame] | 1277 | name = obj.__name__ |
| 1278 | inst = parent(name) |
| 1279 | # static methods follow a different path |
Christian Heimes | 4975a1f | 2007-11-26 10:14:51 +0000 | [diff] [blame] | 1280 | if not isinstance(getattr(inst, name), types.FunctionType): |
Christian Heimes | 4a22b5d | 2007-11-25 09:39:14 +0000 | [diff] [blame] | 1281 | return TestSuite([inst]) |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 1282 | elif isinstance(obj, TestSuite): |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1283 | return obj |
Christian Heimes | 4a22b5d | 2007-11-25 09:39:14 +0000 | [diff] [blame] | 1284 | |
| 1285 | if hasattr(obj, '__call__'): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1286 | test = obj() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1287 | if isinstance(test, TestSuite): |
| 1288 | return test |
| 1289 | elif isinstance(test, TestCase): |
| 1290 | return TestSuite([test]) |
| 1291 | else: |
| 1292 | raise TypeError("calling %s returned %s, not a test" % |
| 1293 | (obj, test)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1294 | else: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1295 | raise TypeError("don't know how to make test from: %s" % obj) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1296 | |
| 1297 | def loadTestsFromNames(self, names, module=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1298 | """Return a suite of all tests cases found using the given sequence |
| 1299 | of string specifiers. See 'loadTestsFromName()'. |
| 1300 | """ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1301 | suites = [self.loadTestsFromName(name, module) for name in names] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1302 | return self.suiteClass(suites) |
| 1303 | |
| 1304 | def getTestCaseNames(self, testCaseClass): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1305 | """Return a sorted sequence of method names found within testCaseClass |
| 1306 | """ |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 1307 | def isTestMethod(attrname, testCaseClass=testCaseClass, |
| 1308 | prefix=self.testMethodPrefix): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1309 | return attrname.startswith(prefix) and \ |
| 1310 | hasattr(getattr(testCaseClass, attrname), '__call__') |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 1311 | testFnNames = list(filter(isTestMethod, dir(testCaseClass))) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1312 | if self.sortTestMethodsUsing: |
Raymond Hettinger | d4cb56d | 2008-01-30 02:55:10 +0000 | [diff] [blame] | 1313 | testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing)) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1314 | return testFnNames |
| 1315 | |
| 1316 | |
| 1317 | |
| 1318 | defaultTestLoader = TestLoader() |
| 1319 | |
| 1320 | |
| 1321 | ############################################################################## |
| 1322 | # Patches for old functions: these functions should be considered obsolete |
| 1323 | ############################################################################## |
| 1324 | |
| 1325 | def _makeLoader(prefix, sortUsing, suiteClass=None): |
| 1326 | loader = TestLoader() |
| 1327 | loader.sortTestMethodsUsing = sortUsing |
| 1328 | loader.testMethodPrefix = prefix |
| 1329 | if suiteClass: loader.suiteClass = suiteClass |
| 1330 | return loader |
| 1331 | |
Mark Dickinson | c429a83 | 2009-01-27 20:27:05 +0000 | [diff] [blame] | 1332 | def getTestCaseNames(testCaseClass, prefix, sortUsing=three_way_cmp): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1333 | return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass) |
| 1334 | |
Mark Dickinson | c429a83 | 2009-01-27 20:27:05 +0000 | [diff] [blame] | 1335 | def makeSuite(testCaseClass, prefix='test', sortUsing=three_way_cmp, |
| 1336 | suiteClass=TestSuite): |
| 1337 | return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase( |
| 1338 | testCaseClass) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1339 | |
Mark Dickinson | c429a83 | 2009-01-27 20:27:05 +0000 | [diff] [blame] | 1340 | def findTestCases(module, prefix='test', sortUsing=three_way_cmp, |
| 1341 | suiteClass=TestSuite): |
| 1342 | return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule( |
| 1343 | module) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1344 | |
| 1345 | |
| 1346 | ############################################################################## |
| 1347 | # Text UI |
| 1348 | ############################################################################## |
| 1349 | |
Benjamin Peterson | 1467ac8 | 2009-01-09 03:42:38 +0000 | [diff] [blame] | 1350 | class _WritelnDecorator(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1351 | """Used to decorate file-like objects with a handy 'writeln' method""" |
| 1352 | def __init__(self,stream): |
| 1353 | self.stream = stream |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1354 | |
| 1355 | def __getattr__(self, attr): |
| 1356 | return getattr(self.stream,attr) |
| 1357 | |
Raymond Hettinger | 91dd19d | 2003-09-13 02:58:00 +0000 | [diff] [blame] | 1358 | def writeln(self, arg=None): |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 1359 | if arg: |
| 1360 | self.write(arg) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1361 | self.write('\n') # text-mode streams translate to \r\n if needed |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 1362 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1363 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1364 | class _TextTestResult(TestResult): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1365 | """A test result class that can print formatted text results to a stream. |
| 1366 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1367 | Used by TextTestRunner. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1368 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1369 | separator1 = '=' * 70 |
| 1370 | separator2 = '-' * 70 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1371 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1372 | def __init__(self, stream, descriptions, verbosity): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1373 | super(_TextTestResult, self).__init__() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1374 | self.stream = stream |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1375 | self.showAll = verbosity > 1 |
| 1376 | self.dots = verbosity == 1 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1377 | self.descriptions = descriptions |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1378 | |
| 1379 | def getDescription(self, test): |
| 1380 | if self.descriptions: |
| 1381 | return test.shortDescription() or str(test) |
| 1382 | else: |
| 1383 | return str(test) |
| 1384 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1385 | def startTest(self, test): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1386 | super(_TextTestResult, self).startTest(test) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1387 | if self.showAll: |
| 1388 | self.stream.write(self.getDescription(test)) |
| 1389 | self.stream.write(" ... ") |
Alexandre Vassalotti | 8ae3e05 | 2008-05-16 00:41:41 +0000 | [diff] [blame] | 1390 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1391 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1392 | def addSuccess(self, test): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1393 | super(_TextTestResult, self).addSuccess(test) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1394 | if self.showAll: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1395 | self.stream.writeln("ok") |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1396 | elif self.dots: |
| 1397 | self.stream.write('.') |
Alexandre Vassalotti | 8ae3e05 | 2008-05-16 00:41:41 +0000 | [diff] [blame] | 1398 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1399 | |
| 1400 | def addError(self, test, err): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1401 | super(_TextTestResult, self).addError(test, err) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1402 | if self.showAll: |
| 1403 | self.stream.writeln("ERROR") |
| 1404 | elif self.dots: |
| 1405 | self.stream.write('E') |
Alexandre Vassalotti | 8ae3e05 | 2008-05-16 00:41:41 +0000 | [diff] [blame] | 1406 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1407 | |
| 1408 | def addFailure(self, test, err): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1409 | super(_TextTestResult, self).addFailure(test, err) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1410 | if self.showAll: |
| 1411 | self.stream.writeln("FAIL") |
| 1412 | elif self.dots: |
| 1413 | self.stream.write('F') |
Alexandre Vassalotti | 8ae3e05 | 2008-05-16 00:41:41 +0000 | [diff] [blame] | 1414 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1415 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1416 | def addSkip(self, test, reason): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1417 | super(_TextTestResult, self).addSkip(test, reason) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1418 | if self.showAll: |
| 1419 | self.stream.writeln("skipped {0!r}".format(reason)) |
| 1420 | elif self.dots: |
| 1421 | self.stream.write("s") |
| 1422 | self.stream.flush() |
| 1423 | |
| 1424 | def addExpectedFailure(self, test, err): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1425 | super(_TextTestResult, self).addExpectedFailure(test, err) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1426 | if self.showAll: |
| 1427 | self.stream.writeln("expected failure") |
| 1428 | elif self.dots: |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 1429 | self.stream.write("x") |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1430 | self.stream.flush() |
| 1431 | |
| 1432 | def addUnexpectedSuccess(self, test): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1433 | super(_TextTestResult, self).addUnexpectedSuccess(test) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1434 | if self.showAll: |
| 1435 | self.stream.writeln("unexpected success") |
| 1436 | elif self.dots: |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 1437 | self.stream.write("u") |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1438 | self.stream.flush() |
| 1439 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1440 | def printErrors(self): |
| 1441 | if self.dots or self.showAll: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1442 | self.stream.writeln() |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1443 | self.printErrorList('ERROR', self.errors) |
| 1444 | self.printErrorList('FAIL', self.failures) |
| 1445 | |
| 1446 | def printErrorList(self, flavour, errors): |
| 1447 | for test, err in errors: |
| 1448 | self.stream.writeln(self.separator1) |
| 1449 | self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) |
| 1450 | self.stream.writeln(self.separator2) |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 1451 | self.stream.writeln("%s" % err) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1452 | |
| 1453 | |
Benjamin Peterson | 1467ac8 | 2009-01-09 03:42:38 +0000 | [diff] [blame] | 1454 | class TextTestRunner(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1455 | """A test runner class that displays results in textual form. |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 1456 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1457 | It prints out the names of tests as they are run, errors as they |
| 1458 | occur, and a summary of the results at the end of the test run. |
| 1459 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1460 | def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1461 | self.stream = _WritelnDecorator(stream) |
| 1462 | self.descriptions = descriptions |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1463 | self.verbosity = verbosity |
| 1464 | |
| 1465 | def _makeResult(self): |
| 1466 | return _TextTestResult(self.stream, self.descriptions, self.verbosity) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1467 | |
| 1468 | def run(self, test): |
| 1469 | "Run the given test case or test suite." |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1470 | result = self._makeResult() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1471 | startTime = time.time() |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1472 | startTestRun = getattr(result, 'startTestRun', None) |
| 1473 | if startTestRun is not None: |
| 1474 | startTestRun() |
| 1475 | try: |
| 1476 | test(result) |
| 1477 | finally: |
| 1478 | stopTestRun = getattr(result, 'stopTestRun', None) |
| 1479 | if stopTestRun is not None: |
| 1480 | stopTestRun() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1481 | stopTime = time.time() |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 1482 | timeTaken = stopTime - startTime |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1483 | result.printErrors() |
| 1484 | self.stream.writeln(result.separator2) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1485 | run = result.testsRun |
| 1486 | self.stream.writeln("Ran %d test%s in %.3fs" % |
Neal Norwitz | 7616504 | 2002-05-31 14:15:11 +0000 | [diff] [blame] | 1487 | (run, run != 1 and "s" or "", timeTaken)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1488 | self.stream.writeln() |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1489 | results = map(len, (result.expectedFailures, |
| 1490 | result.unexpectedSuccesses, |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1491 | result.skipped)) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1492 | expectedFails, unexpectedSuccesses, skipped = results |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1493 | infos = [] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1494 | if not result.wasSuccessful(): |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1495 | self.stream.write("FAILED") |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 1496 | failed, errored = len(result.failures), len(result.errors) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1497 | if failed: |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1498 | infos.append("failures=%d" % failed) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1499 | if errored: |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1500 | infos.append("errors=%d" % errored) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1501 | else: |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 1502 | self.stream.write("OK") |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1503 | if skipped: |
| 1504 | infos.append("skipped=%d" % skipped) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1505 | if expectedFails: |
| 1506 | infos.append("expected failures=%d" % expectedFails) |
| 1507 | if unexpectedSuccesses: |
| 1508 | infos.append("unexpected successes=%d" % unexpectedSuccesses) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1509 | if infos: |
| 1510 | self.stream.writeln(" (%s)" % (", ".join(infos),)) |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 1511 | else: |
| 1512 | self.stream.write("\n") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1513 | return result |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 1514 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1515 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1516 | |
| 1517 | ############################################################################## |
| 1518 | # Facilities for running tests from the command line |
| 1519 | ############################################################################## |
| 1520 | |
Benjamin Peterson | 1467ac8 | 2009-01-09 03:42:38 +0000 | [diff] [blame] | 1521 | class TestProgram(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1522 | """A command-line program that runs a set of tests; this is primarily |
| 1523 | for making test modules conveniently executable. |
| 1524 | """ |
| 1525 | USAGE = """\ |
Steve Purcell | 17a781b | 2001-04-09 15:37:31 +0000 | [diff] [blame] | 1526 | Usage: %(progName)s [options] [test] [...] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1527 | |
| 1528 | Options: |
| 1529 | -h, --help Show this message |
| 1530 | -v, --verbose Verbose output |
| 1531 | -q, --quiet Minimal output |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1532 | |
| 1533 | Examples: |
| 1534 | %(progName)s - run default set of tests |
| 1535 | %(progName)s MyTestSuite - run suite 'MyTestSuite' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1536 | %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething |
| 1537 | %(progName)s MyTestCase - run all 'test*' test methods |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1538 | in MyTestCase |
| 1539 | """ |
| 1540 | def __init__(self, module='__main__', defaultTest=None, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1541 | argv=None, testRunner=TextTestRunner, |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1542 | testLoader=defaultTestLoader, exit=True): |
Antoine Pitrou | e7bd868 | 2009-01-09 19:29:16 +0000 | [diff] [blame] | 1543 | if isinstance(module, str): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1544 | self.module = __import__(module) |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1545 | for part in module.split('.')[1:]: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1546 | self.module = getattr(self.module, part) |
| 1547 | else: |
| 1548 | self.module = module |
| 1549 | if argv is None: |
| 1550 | argv = sys.argv |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1551 | |
| 1552 | self.exit = exit |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1553 | self.verbosity = 1 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1554 | self.defaultTest = defaultTest |
| 1555 | self.testRunner = testRunner |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1556 | self.testLoader = testLoader |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1557 | self.progName = os.path.basename(argv[0]) |
| 1558 | self.parseArgs(argv) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1559 | self.runTests() |
| 1560 | |
| 1561 | def usageExit(self, msg=None): |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1562 | if msg: |
| 1563 | print(msg) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1564 | print(self.USAGE % self.__dict__) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1565 | sys.exit(2) |
| 1566 | |
| 1567 | def parseArgs(self, argv): |
| 1568 | import getopt |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1569 | long_opts = ['help','verbose','quiet'] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1570 | try: |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1571 | options, args = getopt.getopt(argv[1:], 'hHvq', long_opts) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1572 | for opt, value in options: |
| 1573 | if opt in ('-h','-H','--help'): |
| 1574 | self.usageExit() |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1575 | if opt in ('-q','--quiet'): |
| 1576 | self.verbosity = 0 |
| 1577 | if opt in ('-v','--verbose'): |
| 1578 | self.verbosity = 2 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1579 | if len(args) == 0 and self.defaultTest is None: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1580 | self.test = self.testLoader.loadTestsFromModule(self.module) |
| 1581 | return |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1582 | if len(args) > 0: |
| 1583 | self.testNames = args |
| 1584 | else: |
| 1585 | self.testNames = (self.defaultTest,) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1586 | self.createTests() |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 1587 | except getopt.error as msg: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1588 | self.usageExit(msg) |
| 1589 | |
| 1590 | def createTests(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1591 | self.test = self.testLoader.loadTestsFromNames(self.testNames, |
| 1592 | self.module) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1593 | |
| 1594 | def runTests(self): |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 1595 | if isinstance(self.testRunner, type): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1596 | try: |
| 1597 | testRunner = self.testRunner(verbosity=self.verbosity) |
| 1598 | except TypeError: |
| 1599 | # didn't accept the verbosity argument |
| 1600 | testRunner = self.testRunner() |
| 1601 | else: |
| 1602 | # it is assumed to be a TestRunner instance |
| 1603 | testRunner = self.testRunner |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1604 | self.result = testRunner.run(self.test) |
| 1605 | if self.exit: |
| 1606 | sys.exit(not self.result.wasSuccessful()) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1607 | |
| 1608 | main = TestProgram |
| 1609 | |
| 1610 | |
| 1611 | ############################################################################## |
| 1612 | # Executing this module from the command line |
| 1613 | ############################################################################## |
| 1614 | |
| 1615 | if __name__ == "__main__": |
| 1616 | main(module=None) |