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