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*' |
| 17 | self.assertEquals((1 + 2), 3) |
| 18 | self.assertEquals(0 + 1, 1) |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 19 | def testMultiply(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 20 | self.assertEquals((0 * 10), 0) |
| 21 | self.assertEquals((5 * 8), 40) |
| 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 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 48 | import time |
| 49 | import sys |
| 50 | import traceback |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 51 | import os |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 52 | import types |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 53 | import functools |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 54 | |
| 55 | ############################################################################## |
Steve Purcell | d75e7e4 | 2003-09-15 11:01:21 +0000 | [diff] [blame] | 56 | # Exported classes and functions |
| 57 | ############################################################################## |
Benjamin Peterson | c750d4d | 2009-03-24 00:39:24 +0000 | [diff] [blame] | 58 | __all__ = ['TestResult', 'TestCase', 'TestSuite', 'ClassTestSuite', |
| 59 | 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main', |
Benjamin Peterson | 0371548 | 2009-03-24 01:11:37 +0000 | [diff] [blame] | 60 | 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless', |
Benjamin Peterson | c750d4d | 2009-03-24 00:39:24 +0000 | [diff] [blame] | 61 | 'expectedFailure'] |
Steve Purcell | d75e7e4 | 2003-09-15 11:01:21 +0000 | [diff] [blame] | 62 | |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 63 | # Expose obsolete functions for backwards compatibility |
Steve Purcell | d75e7e4 | 2003-09-15 11:01:21 +0000 | [diff] [blame] | 64 | __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases']) |
| 65 | |
| 66 | |
| 67 | ############################################################################## |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 68 | # Backward compatibility |
| 69 | ############################################################################## |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 70 | |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 71 | def _CmpToKey(mycmp): |
| 72 | 'Convert a cmp= function into a key= function' |
| 73 | class K(object): |
| 74 | def __init__(self, obj): |
| 75 | self.obj = obj |
| 76 | def __lt__(self, other): |
| 77 | return mycmp(self.obj, other.obj) == -1 |
| 78 | return K |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 79 | |
| 80 | ############################################################################## |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 81 | # Test framework core |
| 82 | ############################################################################## |
| 83 | |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 84 | def _strclass(cls): |
| 85 | return "%s.%s" % (cls.__module__, cls.__name__) |
| 86 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 87 | |
| 88 | class SkipTest(Exception): |
| 89 | """ |
| 90 | Raise this exception in a test to skip it. |
| 91 | |
| 92 | Usually you can use TestResult.skip() or one of the skipping decorators |
| 93 | instead of raising this directly. |
| 94 | """ |
| 95 | pass |
| 96 | |
| 97 | class _ExpectedFailure(Exception): |
| 98 | """ |
| 99 | Raise this when a test is expected to fail. |
| 100 | |
| 101 | This is an implementation detail. |
| 102 | """ |
| 103 | |
| 104 | def __init__(self, exc_info): |
| 105 | super(_ExpectedFailure, self).__init__() |
| 106 | self.exc_info = exc_info |
| 107 | |
| 108 | class _UnexpectedSuccess(Exception): |
| 109 | """ |
| 110 | The test was supposed to fail, but it didn't! |
| 111 | """ |
| 112 | pass |
| 113 | |
| 114 | def _id(obj): |
| 115 | return obj |
| 116 | |
| 117 | def skip(reason): |
| 118 | """ |
| 119 | Unconditionally skip a test. |
| 120 | """ |
| 121 | def decorator(test_item): |
| 122 | if isinstance(test_item, type) and issubclass(test_item, TestCase): |
| 123 | test_item.__unittest_skip__ = True |
| 124 | test_item.__unittest_skip_why__ = reason |
| 125 | return test_item |
| 126 | @functools.wraps(test_item) |
| 127 | def skip_wrapper(*args, **kwargs): |
| 128 | raise SkipTest(reason) |
| 129 | return skip_wrapper |
| 130 | return decorator |
| 131 | |
| 132 | def skipIf(condition, reason): |
| 133 | """ |
| 134 | Skip a test if the condition is true. |
| 135 | """ |
| 136 | if condition: |
| 137 | return skip(reason) |
| 138 | return _id |
| 139 | |
| 140 | def skipUnless(condition, reason): |
| 141 | """ |
| 142 | Skip a test unless the condition is true. |
| 143 | """ |
| 144 | if not condition: |
| 145 | return skip(reason) |
| 146 | return _id |
| 147 | |
| 148 | |
| 149 | def expectedFailure(func): |
| 150 | @functools.wraps(func) |
| 151 | def wrapper(*args, **kwargs): |
| 152 | try: |
| 153 | func(*args, **kwargs) |
| 154 | except Exception: |
| 155 | raise _ExpectedFailure(sys.exc_info()) |
| 156 | raise _UnexpectedSuccess |
| 157 | return wrapper |
| 158 | |
| 159 | |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 160 | __unittest = 1 |
| 161 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 162 | class TestResult(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 163 | """Holder for test result information. |
| 164 | |
| 165 | Test results are automatically managed by the TestCase and TestSuite |
| 166 | classes, and do not need to be explicitly manipulated by writers of tests. |
| 167 | |
| 168 | Each instance holds the total number of tests run, and collections of |
| 169 | failures and errors that occurred among those test runs. The collections |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 170 | contain tuples of (testcase, exceptioninfo), where exceptioninfo is the |
Fred Drake | 656f9ec | 2001-09-06 19:13:14 +0000 | [diff] [blame] | 171 | formatted traceback of the error that occurred. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 172 | """ |
| 173 | def __init__(self): |
| 174 | self.failures = [] |
| 175 | self.errors = [] |
| 176 | self.testsRun = 0 |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 177 | self.skipped = [] |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 178 | self.expectedFailures = [] |
| 179 | self.unexpectedSuccesses = [] |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 180 | self.shouldStop = False |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 181 | |
| 182 | def startTest(self, test): |
| 183 | "Called when the given test is about to be run" |
| 184 | self.testsRun = self.testsRun + 1 |
| 185 | |
| 186 | def stopTest(self, test): |
| 187 | "Called when the given test has been run" |
| 188 | pass |
| 189 | |
| 190 | def addError(self, test, err): |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 191 | """Called when an error has occurred. 'err' is a tuple of values as |
| 192 | returned by sys.exc_info(). |
| 193 | """ |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 194 | self.errors.append((test, self._exc_info_to_string(err, test))) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 195 | |
| 196 | def addFailure(self, test, err): |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 197 | """Called when an error has occurred. 'err' is a tuple of values as |
| 198 | returned by sys.exc_info().""" |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 199 | self.failures.append((test, self._exc_info_to_string(err, test))) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 200 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 201 | def addSuccess(self, test): |
| 202 | "Called when a test has completed successfully" |
| 203 | pass |
| 204 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 205 | def addSkip(self, test, reason): |
| 206 | """Called when a test is skipped.""" |
| 207 | self.skipped.append((test, reason)) |
| 208 | |
| 209 | def addExpectedFailure(self, test, err): |
| 210 | """Called when an expected failure/error occured.""" |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 211 | self.expectedFailures.append( |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 212 | (test, self._exc_info_to_string(err, test))) |
| 213 | |
| 214 | def addUnexpectedSuccess(self, test): |
| 215 | """Called when a test was expected to fail, but succeed.""" |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 216 | self.unexpectedSuccesses.append(test) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 217 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 218 | def wasSuccessful(self): |
| 219 | "Tells whether or not this result was a success" |
| 220 | return len(self.failures) == len(self.errors) == 0 |
| 221 | |
| 222 | def stop(self): |
| 223 | "Indicates that the tests should be aborted" |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 224 | self.shouldStop = True |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 225 | |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 226 | def _exc_info_to_string(self, err, test): |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 227 | """Converts a sys.exc_info()-style tuple of values into a string.""" |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 228 | exctype, value, tb = err |
| 229 | # Skip test runner traceback levels |
| 230 | while tb and self._is_relevant_tb_level(tb): |
| 231 | tb = tb.tb_next |
| 232 | if exctype is test.failureException: |
| 233 | # Skip assert*() traceback levels |
| 234 | length = self._count_relevant_tb_levels(tb) |
| 235 | return ''.join(traceback.format_exception(exctype, value, tb, length)) |
| 236 | return ''.join(traceback.format_exception(exctype, value, tb)) |
| 237 | |
| 238 | def _is_relevant_tb_level(self, tb): |
Georg Brandl | 56af5fc | 2008-07-18 19:30:10 +0000 | [diff] [blame] | 239 | return '__unittest' in tb.tb_frame.f_globals |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 240 | |
| 241 | def _count_relevant_tb_levels(self, tb): |
| 242 | length = 0 |
| 243 | while tb and not self._is_relevant_tb_level(tb): |
| 244 | length += 1 |
| 245 | tb = tb.tb_next |
| 246 | return length |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 247 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 248 | def __repr__(self): |
| 249 | return "<%s run=%i errors=%i failures=%i>" % \ |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 250 | (_strclass(self.__class__), self.testsRun, len(self.errors), |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 251 | len(self.failures)) |
| 252 | |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 253 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 254 | class AssertRaisesContext(object): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 255 | |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 256 | def __init__(self, expected, test_case): |
| 257 | self.expected = expected |
| 258 | self.failureException = test_case.failureException |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 259 | |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 260 | def __enter__(self): |
| 261 | pass |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 262 | |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 263 | def __exit__(self, exc_type, exc_value, traceback): |
| 264 | if exc_type is None: |
| 265 | try: |
| 266 | exc_name = self.expected.__name__ |
| 267 | except AttributeError: |
| 268 | exc_name = str(self.expected) |
| 269 | raise self.failureException( |
| 270 | "{0} not raised".format(exc_name)) |
| 271 | if issubclass(exc_type, self.expected): |
| 272 | return True |
| 273 | # Let unexpected exceptions skip through |
| 274 | return False |
| 275 | |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 276 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 277 | class TestCase(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 278 | """A class whose instances are single test cases. |
| 279 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 280 | By default, the test code itself should be placed in a method named |
| 281 | 'runTest'. |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 282 | |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 283 | If the fixture may be used for many test cases, create as |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 284 | many test methods as are needed. When instantiating such a TestCase |
| 285 | subclass, specify in the constructor arguments the name of the test method |
| 286 | that the instance is to execute. |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 287 | |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 288 | Test authors should subclass TestCase for their own tests. Construction |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 289 | and deconstruction of the test's environment ('fixture') can be |
| 290 | implemented by overriding the 'setUp' and 'tearDown' methods respectively. |
| 291 | |
| 292 | If it is necessary to override the __init__ method, the base class |
| 293 | __init__ method must always be called. It is important that subclasses |
| 294 | should not change the signature of their __init__ method, since instances |
| 295 | of the classes are instantiated automatically by parts of the framework |
| 296 | in order to be run. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 297 | """ |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 298 | |
| 299 | # This attribute determines which exception will be raised when |
| 300 | # the instance's assertion methods fail; test methods raising this |
| 301 | # exception will be deemed to have 'failed' rather than 'errored' |
| 302 | |
| 303 | failureException = AssertionError |
| 304 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 305 | def __init__(self, methodName='runTest'): |
| 306 | """Create an instance of the class that will use the named test |
| 307 | method when executed. Raises a ValueError if the instance does |
| 308 | not have a method with the specified name. |
| 309 | """ |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 310 | self._testMethodName = methodName |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 311 | try: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 312 | testMethod = getattr(self, methodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 313 | except AttributeError: |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 314 | raise ValueError("no such test method in %s: %s" % \ |
| 315 | (self.__class__, methodName)) |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 316 | self._testMethodDoc = testMethod.__doc__ |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 317 | |
| 318 | def setUp(self): |
| 319 | "Hook method for setting up the test fixture before exercising it." |
| 320 | pass |
| 321 | |
| 322 | def tearDown(self): |
| 323 | "Hook method for deconstructing the test fixture after testing it." |
| 324 | pass |
| 325 | |
| 326 | def countTestCases(self): |
| 327 | return 1 |
| 328 | |
| 329 | def defaultTestResult(self): |
| 330 | return TestResult() |
| 331 | |
| 332 | def shortDescription(self): |
| 333 | """Returns a one-line description of the test, or None if no |
| 334 | description has been provided. |
| 335 | |
| 336 | The default implementation of this method returns the first line of |
| 337 | the specified test method's docstring. |
| 338 | """ |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 339 | doc = self._testMethodDoc |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 340 | return doc and doc.split("\n")[0].strip() or None |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 341 | |
| 342 | def id(self): |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 343 | return "%s.%s" % (_strclass(self.__class__), self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 344 | |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 345 | def __eq__(self, other): |
| 346 | if type(self) is not type(other): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 347 | return NotImplemented |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 348 | |
| 349 | return self._testMethodName == other._testMethodName |
| 350 | |
| 351 | def __ne__(self, other): |
| 352 | return not self == other |
| 353 | |
| 354 | def __hash__(self): |
Collin Winter | 9453e5d | 2007-03-09 23:30:39 +0000 | [diff] [blame] | 355 | return hash((type(self), self._testMethodName)) |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 356 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 357 | def __str__(self): |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 358 | return "%s (%s)" % (self._testMethodName, _strclass(self.__class__)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 359 | |
| 360 | def __repr__(self): |
| 361 | return "<%s testMethod=%s>" % \ |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 362 | (_strclass(self.__class__), self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 363 | |
| 364 | def run(self, result=None): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 365 | if result is None: |
| 366 | result = self.defaultTestResult() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 367 | result.startTest(self) |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 368 | testMethod = getattr(self, self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 369 | try: |
| 370 | try: |
| 371 | self.setUp() |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 372 | except SkipTest as e: |
| 373 | result.addSkip(self, str(e)) |
| 374 | return |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 375 | except Exception: |
Benjamin Peterson | c930135 | 2009-03-26 16:32:23 +0000 | [diff] [blame^] | 376 | result.addError(self, sys.exc_info()) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 377 | return |
| 378 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 379 | success = False |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 380 | try: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 381 | testMethod() |
Skip Montanaro | ae5c37b | 2003-07-13 15:18:12 +0000 | [diff] [blame] | 382 | except self.failureException: |
Benjamin Peterson | c930135 | 2009-03-26 16:32:23 +0000 | [diff] [blame^] | 383 | result.addFailure(self, sys.exc_info()) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 384 | except _ExpectedFailure as e: |
| 385 | result.addExpectedFailure(self, e.exc_info) |
| 386 | except _UnexpectedSuccess: |
| 387 | result.addUnexpectedSuccess(self) |
| 388 | except SkipTest as e: |
| 389 | result.addSkip(self, str(e)) |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 390 | except Exception: |
Benjamin Peterson | c930135 | 2009-03-26 16:32:23 +0000 | [diff] [blame^] | 391 | result.addError(self, sys.exc_info()) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 392 | else: |
| 393 | success = True |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 394 | |
| 395 | try: |
| 396 | self.tearDown() |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 397 | except Exception: |
Benjamin Peterson | c930135 | 2009-03-26 16:32:23 +0000 | [diff] [blame^] | 398 | result.addError(self, sys.exc_info()) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 399 | success = False |
| 400 | if success: |
| 401 | result.addSuccess(self) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 402 | finally: |
| 403 | result.stopTest(self) |
| 404 | |
Raymond Hettinger | 664347b | 2004-12-04 21:21:53 +0000 | [diff] [blame] | 405 | def __call__(self, *args, **kwds): |
| 406 | return self.run(*args, **kwds) |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 407 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 408 | def debug(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 409 | """Run the test without collecting errors in a TestResult""" |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 410 | self.setUp() |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 411 | getattr(self, self._testMethodName)() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 412 | self.tearDown() |
| 413 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 414 | def skip(self, reason): |
| 415 | """Skip this test.""" |
| 416 | raise SkipTest(reason) |
| 417 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 418 | def fail(self, msg=None): |
| 419 | """Fail immediately, with the given message.""" |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 420 | raise self.failureException(msg) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 421 | |
| 422 | def failIf(self, expr, msg=None): |
| 423 | "Fail the test if the expression is true." |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 424 | if expr: |
| 425 | raise self.failureException(msg) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 426 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 427 | def failUnless(self, expr, msg=None): |
| 428 | """Fail the test unless the expression is true.""" |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 429 | if not expr: |
| 430 | raise self.failureException(msg) |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 431 | |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 432 | def failUnlessRaises(self, excClass, callableObj=None, *args, **kwargs): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 433 | """Fail unless an exception of class excClass is thrown |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 434 | by callableObj when invoked with arguments args and keyword |
| 435 | arguments kwargs. If a different type of exception is |
| 436 | thrown, it will not be caught, and the test case will be |
| 437 | deemed to have suffered an error, exactly as for an |
| 438 | unexpected exception. |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 439 | |
| 440 | If called with callableObj omitted or None, will return a |
| 441 | context object used like this:: |
| 442 | |
| 443 | with self.failUnlessRaises(some_error_class): |
| 444 | do_something() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 445 | """ |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 446 | context = AssertRaisesContext(excClass, self) |
| 447 | if callableObj is None: |
| 448 | return context |
| 449 | with context: |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 450 | callableObj(*args, **kwargs) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 451 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 452 | def failUnlessEqual(self, first, second, msg=None): |
Raymond Hettinger | c377cbf | 2003-04-04 22:56:42 +0000 | [diff] [blame] | 453 | """Fail if the two objects are unequal as determined by the '==' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 454 | operator. |
| 455 | """ |
Raymond Hettinger | c377cbf | 2003-04-04 22:56:42 +0000 | [diff] [blame] | 456 | if not first == second: |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 457 | raise self.failureException(msg or '%r != %r' % (first, second)) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 458 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 459 | def failIfEqual(self, first, second, msg=None): |
| 460 | """Fail if the two objects are equal as determined by the '==' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 461 | operator. |
| 462 | """ |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 463 | if first == second: |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 464 | raise self.failureException(msg or '%r == %r' % (first, second)) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 465 | |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 466 | def failUnlessAlmostEqual(self, first, second, places=7, msg=None): |
| 467 | """Fail if the two objects are unequal as determined by their |
| 468 | difference rounded to the given number of decimal places |
| 469 | (default 7) and comparing to zero. |
| 470 | |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 471 | Note that decimal places (from zero) are usually not the same |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 472 | as significant digits (measured from the most signficant digit). |
| 473 | """ |
Jeffrey Yasskin | 2f3c16b | 2008-01-03 02:21:52 +0000 | [diff] [blame] | 474 | if round(abs(second-first), places) != 0: |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 475 | raise self.failureException( |
| 476 | msg or '%r != %r within %r places' % (first, second, places)) |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 477 | |
| 478 | def failIfAlmostEqual(self, first, second, places=7, msg=None): |
| 479 | """Fail if the two objects are equal as determined by their |
| 480 | difference rounded to the given number of decimal places |
| 481 | (default 7) and comparing to zero. |
| 482 | |
Steve Purcell | cca3491 | 2003-10-26 16:38:16 +0000 | [diff] [blame] | 483 | Note that decimal places (from zero) are usually not the same |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 484 | as significant digits (measured from the most signficant digit). |
| 485 | """ |
Jeffrey Yasskin | 2f3c16b | 2008-01-03 02:21:52 +0000 | [diff] [blame] | 486 | if round(abs(second-first), places) == 0: |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 487 | raise self.failureException( |
| 488 | msg or '%r == %r within %r places' % (first, second, places)) |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 489 | |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 490 | # Synonyms for assertion methods |
| 491 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 492 | assertEqual = assertEquals = failUnlessEqual |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 493 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 494 | assertNotEqual = assertNotEquals = failIfEqual |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 495 | |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 496 | assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual |
| 497 | |
| 498 | assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual |
| 499 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 500 | assertRaises = failUnlessRaises |
| 501 | |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 502 | assert_ = assertTrue = failUnless |
| 503 | |
| 504 | assertFalse = failIf |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 505 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 506 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 507 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 508 | class TestSuite(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 509 | """A test suite is a composite test consisting of a number of TestCases. |
| 510 | |
| 511 | For use, create an instance of TestSuite, then add test case instances. |
| 512 | When all tests have been added, the suite can be passed to a test |
| 513 | runner, such as TextTestRunner. It will run the individual test cases |
| 514 | in the order in which they were added, aggregating the results. When |
| 515 | subclassing, do not forget to call the base class constructor. |
| 516 | """ |
| 517 | def __init__(self, tests=()): |
| 518 | self._tests = [] |
| 519 | self.addTests(tests) |
| 520 | |
| 521 | def __repr__(self): |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 522 | return "<%s tests=%s>" % (_strclass(self.__class__), self._tests) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 523 | |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 524 | def __eq__(self, other): |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 525 | if not isinstance(other, self.__class__): |
| 526 | return NotImplemented |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 527 | return self._tests == other._tests |
| 528 | |
| 529 | def __ne__(self, other): |
| 530 | return not self == other |
| 531 | |
Nick Coghlan | 48361f5 | 2008-08-11 15:45:58 +0000 | [diff] [blame] | 532 | # Can't guarantee hash invariant, so flag as unhashable |
| 533 | __hash__ = None |
| 534 | |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 535 | def __iter__(self): |
| 536 | return iter(self._tests) |
| 537 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 538 | def countTestCases(self): |
| 539 | cases = 0 |
| 540 | for test in self._tests: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 541 | cases += test.countTestCases() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 542 | return cases |
| 543 | |
| 544 | def addTest(self, test): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 545 | # sanity checks |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 546 | if not hasattr(test, '__call__'): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 547 | raise TypeError("the test to add must be callable") |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 548 | if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 549 | raise TypeError("TestCases and TestSuites must be instantiated " |
| 550 | "before passing them to addTest()") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 551 | self._tests.append(test) |
| 552 | |
| 553 | def addTests(self, tests): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 554 | if isinstance(tests, basestring): |
| 555 | raise TypeError("tests must be an iterable of tests, not a string") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 556 | for test in tests: |
| 557 | self.addTest(test) |
| 558 | |
| 559 | def run(self, result): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 560 | for test in self._tests: |
| 561 | if result.shouldStop: |
| 562 | break |
| 563 | test(result) |
| 564 | return result |
| 565 | |
Raymond Hettinger | 664347b | 2004-12-04 21:21:53 +0000 | [diff] [blame] | 566 | def __call__(self, *args, **kwds): |
| 567 | return self.run(*args, **kwds) |
| 568 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 569 | def debug(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 570 | """Run the tests without collecting errors in a TestResult""" |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 571 | for test in self._tests: |
| 572 | test.debug() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 573 | |
| 574 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 575 | class ClassTestSuite(TestSuite): |
| 576 | """ |
| 577 | Suite of tests derived from a single TestCase class. |
| 578 | """ |
| 579 | |
| 580 | def __init__(self, tests, class_collected_from): |
| 581 | super(ClassTestSuite, self).__init__(tests) |
| 582 | self.collected_from = class_collected_from |
| 583 | |
| 584 | def id(self): |
| 585 | module = getattr(self.collected_from, "__module__", None) |
| 586 | if module is not None: |
| 587 | return "{0}.{1}".format(module, self.collected_from.__name__) |
| 588 | return self.collected_from.__name__ |
| 589 | |
| 590 | def run(self, result): |
| 591 | if getattr(self.collected_from, "__unittest_skip__", False): |
| 592 | # ClassTestSuite result pretends to be a TestCase enough to be |
| 593 | # reported. |
| 594 | result.startTest(self) |
| 595 | try: |
| 596 | result.addSkip(self, self.collected_from.__unittest_skip_why__) |
| 597 | finally: |
| 598 | result.stopTest(self) |
| 599 | else: |
| 600 | result = super(ClassTestSuite, self).run(result) |
| 601 | return result |
| 602 | |
| 603 | shortDescription = id |
| 604 | |
| 605 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 606 | class FunctionTestCase(TestCase): |
| 607 | """A test case that wraps a test function. |
| 608 | |
| 609 | This is useful for slipping pre-existing test functions into the |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 610 | unittest framework. Optionally, set-up and tidy-up functions can be |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 611 | supplied. As with TestCase, the tidy-up ('tearDown') function will |
| 612 | always be called if the set-up ('setUp') function ran successfully. |
| 613 | """ |
| 614 | |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 615 | def __init__(self, testFunc, setUp=None, tearDown=None, description=None): |
| 616 | super(FunctionTestCase, self).__init__() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 617 | self.__setUpFunc = setUp |
| 618 | self.__tearDownFunc = tearDown |
| 619 | self.__testFunc = testFunc |
| 620 | self.__description = description |
| 621 | |
| 622 | def setUp(self): |
| 623 | if self.__setUpFunc is not None: |
| 624 | self.__setUpFunc() |
| 625 | |
| 626 | def tearDown(self): |
| 627 | if self.__tearDownFunc is not None: |
| 628 | self.__tearDownFunc() |
| 629 | |
| 630 | def runTest(self): |
| 631 | self.__testFunc() |
| 632 | |
| 633 | def id(self): |
| 634 | return self.__testFunc.__name__ |
| 635 | |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 636 | def __eq__(self, other): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 637 | if not isinstance(other, self.__class__): |
| 638 | return NotImplemented |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 639 | |
| 640 | return self.__setUpFunc == other.__setUpFunc and \ |
| 641 | self.__tearDownFunc == other.__tearDownFunc and \ |
| 642 | self.__testFunc == other.__testFunc and \ |
| 643 | self.__description == other.__description |
| 644 | |
| 645 | def __ne__(self, other): |
| 646 | return not self == other |
| 647 | |
| 648 | def __hash__(self): |
Collin Winter | 9453e5d | 2007-03-09 23:30:39 +0000 | [diff] [blame] | 649 | return hash((type(self), self.__setUpFunc, self.__tearDownFunc, |
| 650 | self.__testFunc, self.__description)) |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 651 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 652 | def __str__(self): |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 653 | return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 654 | |
| 655 | def __repr__(self): |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 656 | return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 657 | |
| 658 | def shortDescription(self): |
| 659 | if self.__description is not None: return self.__description |
| 660 | doc = self.__testFunc.__doc__ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 661 | return doc and doc.split("\n")[0].strip() or None |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 662 | |
| 663 | |
| 664 | |
| 665 | ############################################################################## |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 666 | # Locating and loading tests |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 667 | ############################################################################## |
| 668 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 669 | class TestLoader(object): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 670 | """ |
| 671 | This class is responsible for loading tests according to various criteria |
| 672 | and returning them wrapped in a TestSuite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 673 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 674 | testMethodPrefix = 'test' |
| 675 | sortTestMethodsUsing = cmp |
| 676 | suiteClass = TestSuite |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 677 | classSuiteClass = ClassTestSuite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 678 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 679 | def loadTestsFromTestCase(self, testCaseClass): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 680 | """Return a suite of all tests cases contained in testCaseClass""" |
Johannes Gijsbers | d7b6ad4 | 2004-11-07 15:46:25 +0000 | [diff] [blame] | 681 | if issubclass(testCaseClass, TestSuite): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 682 | raise TypeError("Test cases should not be derived from TestSuite." \ |
| 683 | " Maybe you meant to derive from TestCase?") |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 684 | testCaseNames = self.getTestCaseNames(testCaseClass) |
| 685 | if not testCaseNames and hasattr(testCaseClass, 'runTest'): |
| 686 | testCaseNames = ['runTest'] |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 687 | suite = self.classSuiteClass(map(testCaseClass, testCaseNames), |
| 688 | testCaseClass) |
| 689 | return suite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 690 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 691 | def loadTestsFromModule(self, module): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 692 | """Return a suite of all tests cases contained in the given module""" |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 693 | tests = [] |
| 694 | for name in dir(module): |
| 695 | obj = getattr(module, name) |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 696 | if isinstance(obj, type) and issubclass(obj, TestCase): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 697 | tests.append(self.loadTestsFromTestCase(obj)) |
| 698 | return self.suiteClass(tests) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 699 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 700 | def loadTestsFromName(self, name, module=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 701 | """Return a suite of all tests cases given a string specifier. |
| 702 | |
| 703 | The name may resolve either to a module, a test case class, a |
| 704 | test method within a test case class, or a callable object which |
| 705 | returns a TestCase or TestSuite instance. |
Tim Peters | 613b222 | 2001-04-13 05:37:27 +0000 | [diff] [blame] | 706 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 707 | The method optionally resolves the names relative to a given module. |
| 708 | """ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 709 | parts = name.split('.') |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 710 | if module is None: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 711 | parts_copy = parts[:] |
| 712 | while parts_copy: |
| 713 | try: |
| 714 | module = __import__('.'.join(parts_copy)) |
| 715 | break |
| 716 | except ImportError: |
| 717 | del parts_copy[-1] |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 718 | if not parts_copy: |
| 719 | raise |
Armin Rigo | 1b3c04b | 2003-10-24 17:15:29 +0000 | [diff] [blame] | 720 | parts = parts[1:] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 721 | obj = module |
| 722 | for part in parts: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 723 | parent, obj = obj, getattr(obj, part) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 724 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 725 | if isinstance(obj, types.ModuleType): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 726 | return self.loadTestsFromModule(obj) |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 727 | elif isinstance(obj, type) and issubclass(obj, TestCase): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 728 | return self.loadTestsFromTestCase(obj) |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 729 | elif (isinstance(obj, types.UnboundMethodType) and |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 730 | isinstance(parent, type) and |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 731 | issubclass(parent, TestCase)): |
| 732 | return TestSuite([parent(obj.__name__)]) |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 733 | elif isinstance(obj, TestSuite): |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 734 | return obj |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 735 | elif hasattr(obj, '__call__'): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 736 | test = obj() |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 737 | if isinstance(test, TestSuite): |
| 738 | return test |
| 739 | elif isinstance(test, TestCase): |
| 740 | return TestSuite([test]) |
| 741 | else: |
| 742 | raise TypeError("calling %s returned %s, not a test" % |
| 743 | (obj, test)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 744 | else: |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 745 | raise TypeError("don't know how to make test from: %s" % obj) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 746 | |
| 747 | def loadTestsFromNames(self, names, module=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 748 | """Return a suite of all tests cases found using the given sequence |
| 749 | of string specifiers. See 'loadTestsFromName()'. |
| 750 | """ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 751 | suites = [self.loadTestsFromName(name, module) for name in names] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 752 | return self.suiteClass(suites) |
| 753 | |
| 754 | def getTestCaseNames(self, testCaseClass): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 755 | """Return a sorted sequence of method names found within testCaseClass |
| 756 | """ |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 757 | def isTestMethod(attrname, testCaseClass=testCaseClass, |
| 758 | prefix=self.testMethodPrefix): |
| 759 | return attrname.startswith(prefix) and \ |
| 760 | hasattr(getattr(testCaseClass, attrname), '__call__') |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 761 | testFnNames = filter(isTestMethod, dir(testCaseClass)) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 762 | if self.sortTestMethodsUsing: |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 763 | testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing)) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 764 | return testFnNames |
| 765 | |
| 766 | |
| 767 | |
| 768 | defaultTestLoader = TestLoader() |
| 769 | |
| 770 | |
| 771 | ############################################################################## |
| 772 | # Patches for old functions: these functions should be considered obsolete |
| 773 | ############################################################################## |
| 774 | |
| 775 | def _makeLoader(prefix, sortUsing, suiteClass=None): |
| 776 | loader = TestLoader() |
| 777 | loader.sortTestMethodsUsing = sortUsing |
| 778 | loader.testMethodPrefix = prefix |
| 779 | if suiteClass: loader.suiteClass = suiteClass |
| 780 | return loader |
| 781 | |
| 782 | def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): |
| 783 | return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass) |
| 784 | |
| 785 | def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite): |
| 786 | return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass) |
| 787 | |
| 788 | def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite): |
| 789 | return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 790 | |
| 791 | |
| 792 | ############################################################################## |
| 793 | # Text UI |
| 794 | ############################################################################## |
| 795 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 796 | class _WritelnDecorator(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 797 | """Used to decorate file-like objects with a handy 'writeln' method""" |
| 798 | def __init__(self,stream): |
| 799 | self.stream = stream |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 800 | |
| 801 | def __getattr__(self, attr): |
| 802 | return getattr(self.stream,attr) |
| 803 | |
Raymond Hettinger | 91dd19d | 2003-09-13 02:58:00 +0000 | [diff] [blame] | 804 | def writeln(self, arg=None): |
Benjamin Peterson | d0cdb2d | 2009-03-24 23:07:07 +0000 | [diff] [blame] | 805 | if arg: |
| 806 | self.write(arg) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 807 | self.write('\n') # text-mode streams translate to \r\n if needed |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 808 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 809 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 810 | class _TextTestResult(TestResult): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 811 | """A test result class that can print formatted text results to a stream. |
| 812 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 813 | Used by TextTestRunner. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 814 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 815 | separator1 = '=' * 70 |
| 816 | separator2 = '-' * 70 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 817 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 818 | def __init__(self, stream, descriptions, verbosity): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 819 | super(_TextTestResult, self).__init__() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 820 | self.stream = stream |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 821 | self.showAll = verbosity > 1 |
| 822 | self.dots = verbosity == 1 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 823 | self.descriptions = descriptions |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 824 | |
| 825 | def getDescription(self, test): |
| 826 | if self.descriptions: |
| 827 | return test.shortDescription() or str(test) |
| 828 | else: |
| 829 | return str(test) |
| 830 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 831 | def startTest(self, test): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 832 | super(_TextTestResult, self).startTest(test) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 833 | if self.showAll: |
| 834 | self.stream.write(self.getDescription(test)) |
| 835 | self.stream.write(" ... ") |
Georg Brandl | d063240 | 2008-05-11 15:17:41 +0000 | [diff] [blame] | 836 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 837 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 838 | def addSuccess(self, test): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 839 | super(_TextTestResult, self).addSuccess(test) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 840 | if self.showAll: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 841 | self.stream.writeln("ok") |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 842 | elif self.dots: |
| 843 | self.stream.write('.') |
Georg Brandl | d063240 | 2008-05-11 15:17:41 +0000 | [diff] [blame] | 844 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 845 | |
| 846 | def addError(self, test, err): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 847 | super(_TextTestResult, self).addError(test, err) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 848 | if self.showAll: |
| 849 | self.stream.writeln("ERROR") |
| 850 | elif self.dots: |
| 851 | self.stream.write('E') |
Georg Brandl | d063240 | 2008-05-11 15:17:41 +0000 | [diff] [blame] | 852 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 853 | |
| 854 | def addFailure(self, test, err): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 855 | super(_TextTestResult, self).addFailure(test, err) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 856 | if self.showAll: |
| 857 | self.stream.writeln("FAIL") |
| 858 | elif self.dots: |
| 859 | self.stream.write('F') |
Georg Brandl | d063240 | 2008-05-11 15:17:41 +0000 | [diff] [blame] | 860 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 861 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 862 | def addSkip(self, test, reason): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 863 | super(_TextTestResult, self).addSkip(test, reason) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 864 | if self.showAll: |
| 865 | self.stream.writeln("skipped {0!r}".format(reason)) |
| 866 | elif self.dots: |
| 867 | self.stream.write("s") |
| 868 | self.stream.flush() |
| 869 | |
| 870 | def addExpectedFailure(self, test, err): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 871 | super(_TextTestResult, self).addExpectedFailure(test, err) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 872 | if self.showAll: |
| 873 | self.stream.writeln("expected failure") |
| 874 | elif self.dots: |
Benjamin Peterson | a8adceb | 2009-03-25 21:24:04 +0000 | [diff] [blame] | 875 | self.stream.write("x") |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 876 | self.stream.flush() |
| 877 | |
| 878 | def addUnexpectedSuccess(self, test): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 879 | super(_TextTestResult, self).addUnexpectedSuccess(test) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 880 | if self.showAll: |
| 881 | self.stream.writeln("unexpected success") |
| 882 | elif self.dots: |
Benjamin Peterson | a8adceb | 2009-03-25 21:24:04 +0000 | [diff] [blame] | 883 | self.stream.write("u") |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 884 | self.stream.flush() |
| 885 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 886 | def printErrors(self): |
| 887 | if self.dots or self.showAll: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 888 | self.stream.writeln() |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 889 | self.printErrorList('ERROR', self.errors) |
| 890 | self.printErrorList('FAIL', self.failures) |
| 891 | |
| 892 | def printErrorList(self, flavour, errors): |
| 893 | for test, err in errors: |
| 894 | self.stream.writeln(self.separator1) |
| 895 | self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) |
| 896 | self.stream.writeln(self.separator2) |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 897 | self.stream.writeln("%s" % err) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 898 | |
| 899 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 900 | class TextTestRunner(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 901 | """A test runner class that displays results in textual form. |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 902 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 903 | It prints out the names of tests as they are run, errors as they |
| 904 | occur, and a summary of the results at the end of the test run. |
| 905 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 906 | def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 907 | self.stream = _WritelnDecorator(stream) |
| 908 | self.descriptions = descriptions |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 909 | self.verbosity = verbosity |
| 910 | |
| 911 | def _makeResult(self): |
| 912 | return _TextTestResult(self.stream, self.descriptions, self.verbosity) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 913 | |
| 914 | def run(self, test): |
| 915 | "Run the given test case or test suite." |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 916 | result = self._makeResult() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 917 | startTime = time.time() |
| 918 | test(result) |
| 919 | stopTime = time.time() |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 920 | timeTaken = stopTime - startTime |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 921 | result.printErrors() |
| 922 | self.stream.writeln(result.separator2) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 923 | run = result.testsRun |
| 924 | self.stream.writeln("Ran %d test%s in %.3fs" % |
Neal Norwitz | 7616504 | 2002-05-31 14:15:11 +0000 | [diff] [blame] | 925 | (run, run != 1 and "s" or "", timeTaken)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 926 | self.stream.writeln() |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 927 | results = map(len, (result.expectedFailures, |
| 928 | result.unexpectedSuccesses, |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 929 | result.skipped)) |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 930 | expectedFails, unexpectedSuccesses, skipped = results |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 931 | infos = [] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 932 | if not result.wasSuccessful(): |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 933 | self.stream.write("FAILED") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 934 | failed, errored = map(len, (result.failures, result.errors)) |
| 935 | if failed: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 936 | infos.append("failures=%d" % failed) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 937 | if errored: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 938 | infos.append("errors=%d" % errored) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 939 | else: |
Benjamin Peterson | a473f00 | 2009-03-24 22:56:32 +0000 | [diff] [blame] | 940 | self.stream.write("OK") |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 941 | if skipped: |
| 942 | infos.append("skipped=%d" % skipped) |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 943 | if expectedFails: |
| 944 | infos.append("expected failures=%d" % expectedFails) |
| 945 | if unexpectedSuccesses: |
| 946 | infos.append("unexpected successes=%d" % unexpectedSuccesses) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 947 | if infos: |
| 948 | self.stream.writeln(" (%s)" % (", ".join(infos),)) |
Benjamin Peterson | a473f00 | 2009-03-24 22:56:32 +0000 | [diff] [blame] | 949 | else: |
| 950 | self.stream.write("\n") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 951 | return result |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 952 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 953 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 954 | |
| 955 | ############################################################################## |
| 956 | # Facilities for running tests from the command line |
| 957 | ############################################################################## |
| 958 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 959 | class TestProgram(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 960 | """A command-line program that runs a set of tests; this is primarily |
| 961 | for making test modules conveniently executable. |
| 962 | """ |
| 963 | USAGE = """\ |
Steve Purcell | 17a781b | 2001-04-09 15:37:31 +0000 | [diff] [blame] | 964 | Usage: %(progName)s [options] [test] [...] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 965 | |
| 966 | Options: |
| 967 | -h, --help Show this message |
| 968 | -v, --verbose Verbose output |
| 969 | -q, --quiet Minimal output |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 970 | |
| 971 | Examples: |
| 972 | %(progName)s - run default set of tests |
| 973 | %(progName)s MyTestSuite - run suite 'MyTestSuite' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 974 | %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething |
| 975 | %(progName)s MyTestCase - run all 'test*' test methods |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 976 | in MyTestCase |
| 977 | """ |
| 978 | def __init__(self, module='__main__', defaultTest=None, |
Georg Brandl | d0a9625 | 2007-03-07 09:21:06 +0000 | [diff] [blame] | 979 | argv=None, testRunner=TextTestRunner, |
| 980 | testLoader=defaultTestLoader): |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 981 | if isinstance(module, basestring): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 982 | self.module = __import__(module) |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 983 | for part in module.split('.')[1:]: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 984 | self.module = getattr(self.module, part) |
| 985 | else: |
| 986 | self.module = module |
| 987 | if argv is None: |
| 988 | argv = sys.argv |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 989 | self.verbosity = 1 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 990 | self.defaultTest = defaultTest |
| 991 | self.testRunner = testRunner |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 992 | self.testLoader = testLoader |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 993 | self.progName = os.path.basename(argv[0]) |
| 994 | self.parseArgs(argv) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 995 | self.runTests() |
| 996 | |
| 997 | def usageExit(self, msg=None): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 998 | if msg: |
| 999 | print msg |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1000 | print self.USAGE % self.__dict__ |
| 1001 | sys.exit(2) |
| 1002 | |
| 1003 | def parseArgs(self, argv): |
| 1004 | import getopt |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1005 | long_opts = ['help','verbose','quiet'] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1006 | try: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1007 | options, args = getopt.getopt(argv[1:], 'hHvq', long_opts) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1008 | for opt, value in options: |
| 1009 | if opt in ('-h','-H','--help'): |
| 1010 | self.usageExit() |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1011 | if opt in ('-q','--quiet'): |
| 1012 | self.verbosity = 0 |
| 1013 | if opt in ('-v','--verbose'): |
| 1014 | self.verbosity = 2 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1015 | if len(args) == 0 and self.defaultTest is None: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1016 | self.test = self.testLoader.loadTestsFromModule(self.module) |
| 1017 | return |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1018 | if len(args) > 0: |
| 1019 | self.testNames = args |
| 1020 | else: |
| 1021 | self.testNames = (self.defaultTest,) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1022 | self.createTests() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1023 | except getopt.error, msg: |
| 1024 | self.usageExit(msg) |
| 1025 | |
| 1026 | def createTests(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1027 | self.test = self.testLoader.loadTestsFromNames(self.testNames, |
| 1028 | self.module) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1029 | |
| 1030 | def runTests(self): |
Georg Brandl | d0a9625 | 2007-03-07 09:21:06 +0000 | [diff] [blame] | 1031 | if isinstance(self.testRunner, (type, types.ClassType)): |
| 1032 | try: |
| 1033 | testRunner = self.testRunner(verbosity=self.verbosity) |
| 1034 | except TypeError: |
| 1035 | # didn't accept the verbosity argument |
| 1036 | testRunner = self.testRunner() |
| 1037 | else: |
| 1038 | # it is assumed to be a TestRunner instance |
| 1039 | testRunner = self.testRunner |
| 1040 | result = testRunner.run(self.test) |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 1041 | sys.exit(not result.wasSuccessful()) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1042 | |
| 1043 | main = TestProgram |
| 1044 | |
| 1045 | |
| 1046 | ############################################################################## |
| 1047 | # Executing this module from the command line |
| 1048 | ############################################################################## |
| 1049 | |
| 1050 | if __name__ == "__main__": |
| 1051 | main(module=None) |