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