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 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 254 | class AssertRaisesContext(object): |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 255 | def __init__(self, expected, test_case): |
| 256 | self.expected = expected |
| 257 | self.failureException = test_case.failureException |
| 258 | def __enter__(self): |
| 259 | pass |
| 260 | def __exit__(self, exc_type, exc_value, traceback): |
| 261 | if exc_type is None: |
| 262 | try: |
| 263 | exc_name = self.expected.__name__ |
| 264 | except AttributeError: |
| 265 | exc_name = str(self.expected) |
| 266 | raise self.failureException( |
| 267 | "{0} not raised".format(exc_name)) |
| 268 | if issubclass(exc_type, self.expected): |
| 269 | return True |
| 270 | # Let unexpected exceptions skip through |
| 271 | return False |
| 272 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 273 | class TestCase(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 274 | """A class whose instances are single test cases. |
| 275 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 276 | By default, the test code itself should be placed in a method named |
| 277 | 'runTest'. |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 278 | |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 279 | If the fixture may be used for many test cases, create as |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 280 | many test methods as are needed. When instantiating such a TestCase |
| 281 | subclass, specify in the constructor arguments the name of the test method |
| 282 | that the instance is to execute. |
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 | Test authors should subclass TestCase for their own tests. Construction |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 285 | and deconstruction of the test's environment ('fixture') can be |
| 286 | implemented by overriding the 'setUp' and 'tearDown' methods respectively. |
| 287 | |
| 288 | If it is necessary to override the __init__ method, the base class |
| 289 | __init__ method must always be called. It is important that subclasses |
| 290 | should not change the signature of their __init__ method, since instances |
| 291 | of the classes are instantiated automatically by parts of the framework |
| 292 | in order to be run. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 293 | """ |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 294 | |
| 295 | # This attribute determines which exception will be raised when |
| 296 | # the instance's assertion methods fail; test methods raising this |
| 297 | # exception will be deemed to have 'failed' rather than 'errored' |
| 298 | |
| 299 | failureException = AssertionError |
| 300 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 301 | def __init__(self, methodName='runTest'): |
| 302 | """Create an instance of the class that will use the named test |
| 303 | method when executed. Raises a ValueError if the instance does |
| 304 | not have a method with the specified name. |
| 305 | """ |
| 306 | try: |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 307 | self._testMethodName = methodName |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 308 | testMethod = getattr(self, methodName) |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 309 | self._testMethodDoc = testMethod.__doc__ |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 310 | except AttributeError: |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 311 | raise ValueError("no such test method in %s: %s" % \ |
| 312 | (self.__class__, methodName)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 313 | |
| 314 | def setUp(self): |
| 315 | "Hook method for setting up the test fixture before exercising it." |
| 316 | pass |
| 317 | |
| 318 | def tearDown(self): |
| 319 | "Hook method for deconstructing the test fixture after testing it." |
| 320 | pass |
| 321 | |
| 322 | def countTestCases(self): |
| 323 | return 1 |
| 324 | |
| 325 | def defaultTestResult(self): |
| 326 | return TestResult() |
| 327 | |
| 328 | def shortDescription(self): |
| 329 | """Returns a one-line description of the test, or None if no |
| 330 | description has been provided. |
| 331 | |
| 332 | The default implementation of this method returns the first line of |
| 333 | the specified test method's docstring. |
| 334 | """ |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 335 | doc = self._testMethodDoc |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 336 | return doc and doc.split("\n")[0].strip() or None |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 337 | |
| 338 | def id(self): |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 339 | return "%s.%s" % (_strclass(self.__class__), self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 340 | |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 341 | def __eq__(self, other): |
| 342 | if type(self) is not type(other): |
| 343 | return False |
| 344 | |
| 345 | return self._testMethodName == other._testMethodName |
| 346 | |
| 347 | def __ne__(self, other): |
| 348 | return not self == other |
| 349 | |
| 350 | def __hash__(self): |
Collin Winter | 9453e5d | 2007-03-09 23:30:39 +0000 | [diff] [blame] | 351 | return hash((type(self), self._testMethodName)) |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 352 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 353 | def __str__(self): |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 354 | return "%s (%s)" % (self._testMethodName, _strclass(self.__class__)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 355 | |
| 356 | def __repr__(self): |
| 357 | return "<%s testMethod=%s>" % \ |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 358 | (_strclass(self.__class__), self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 359 | |
| 360 | def run(self, result=None): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 361 | if result is None: result = self.defaultTestResult() |
| 362 | result.startTest(self) |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 363 | testMethod = getattr(self, self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 364 | try: |
| 365 | try: |
| 366 | self.setUp() |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 367 | except SkipTest as e: |
| 368 | result.addSkip(self, str(e)) |
| 369 | return |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 370 | except Exception: |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 371 | result.addError(self, self._exc_info()) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 372 | return |
| 373 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 374 | success = False |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 375 | try: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 376 | testMethod() |
Skip Montanaro | ae5c37b | 2003-07-13 15:18:12 +0000 | [diff] [blame] | 377 | except self.failureException: |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 378 | result.addFailure(self, self._exc_info()) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 379 | except _ExpectedFailure as e: |
| 380 | result.addExpectedFailure(self, e.exc_info) |
| 381 | except _UnexpectedSuccess: |
| 382 | result.addUnexpectedSuccess(self) |
| 383 | except SkipTest as e: |
| 384 | result.addSkip(self, str(e)) |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 385 | except Exception: |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 386 | result.addError(self, self._exc_info()) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 387 | else: |
| 388 | success = True |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 389 | |
| 390 | try: |
| 391 | self.tearDown() |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 392 | except Exception: |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 393 | result.addError(self, self._exc_info()) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 394 | success = False |
| 395 | if success: |
| 396 | result.addSuccess(self) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 397 | finally: |
| 398 | result.stopTest(self) |
| 399 | |
Raymond Hettinger | 664347b | 2004-12-04 21:21:53 +0000 | [diff] [blame] | 400 | def __call__(self, *args, **kwds): |
| 401 | return self.run(*args, **kwds) |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 402 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 403 | def debug(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 404 | """Run the test without collecting errors in a TestResult""" |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 405 | self.setUp() |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 406 | getattr(self, self._testMethodName)() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 407 | self.tearDown() |
| 408 | |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 409 | def _exc_info(self): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 410 | """Return a version of sys.exc_info() with the traceback frame |
| 411 | minimised; usually the top level of the traceback frame is not |
| 412 | needed. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 413 | """ |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 414 | return sys.exc_info() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 415 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 416 | def skip(self, reason): |
| 417 | """Skip this test.""" |
| 418 | raise SkipTest(reason) |
| 419 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 420 | def fail(self, msg=None): |
| 421 | """Fail immediately, with the given message.""" |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 422 | raise self.failureException(msg) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 423 | |
| 424 | def failIf(self, expr, msg=None): |
| 425 | "Fail the test if the expression is true." |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 426 | if expr: raise self.failureException(msg) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 427 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 428 | def failUnless(self, expr, msg=None): |
| 429 | """Fail the test unless the expression is true.""" |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 430 | if not expr: 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 | |
| 524 | __str__ = __repr__ |
| 525 | |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 526 | def __eq__(self, other): |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 527 | if not isinstance(other, self.__class__): |
| 528 | return NotImplemented |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 529 | return self._tests == other._tests |
| 530 | |
| 531 | def __ne__(self, other): |
| 532 | return not self == other |
| 533 | |
Nick Coghlan | 48361f5 | 2008-08-11 15:45:58 +0000 | [diff] [blame] | 534 | # Can't guarantee hash invariant, so flag as unhashable |
| 535 | __hash__ = None |
| 536 | |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 537 | def __iter__(self): |
| 538 | return iter(self._tests) |
| 539 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 540 | def countTestCases(self): |
| 541 | cases = 0 |
| 542 | for test in self._tests: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 543 | cases += test.countTestCases() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 544 | return cases |
| 545 | |
| 546 | def addTest(self, test): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 547 | # sanity checks |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 548 | if not hasattr(test, '__call__'): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 549 | raise TypeError("the test to add must be callable") |
| 550 | if (isinstance(test, (type, types.ClassType)) and |
| 551 | issubclass(test, (TestCase, TestSuite))): |
| 552 | raise TypeError("TestCases and TestSuites must be instantiated " |
| 553 | "before passing them to addTest()") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 554 | self._tests.append(test) |
| 555 | |
| 556 | def addTests(self, tests): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 557 | if isinstance(tests, basestring): |
| 558 | raise TypeError("tests must be an iterable of tests, not a string") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 559 | for test in tests: |
| 560 | self.addTest(test) |
| 561 | |
| 562 | def run(self, result): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 563 | for test in self._tests: |
| 564 | if result.shouldStop: |
| 565 | break |
| 566 | test(result) |
| 567 | return result |
| 568 | |
Raymond Hettinger | 664347b | 2004-12-04 21:21:53 +0000 | [diff] [blame] | 569 | def __call__(self, *args, **kwds): |
| 570 | return self.run(*args, **kwds) |
| 571 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 572 | def debug(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 573 | """Run the tests without collecting errors in a TestResult""" |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 574 | for test in self._tests: test.debug() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 575 | |
| 576 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 577 | class ClassTestSuite(TestSuite): |
| 578 | """ |
| 579 | Suite of tests derived from a single TestCase class. |
| 580 | """ |
| 581 | |
| 582 | def __init__(self, tests, class_collected_from): |
| 583 | super(ClassTestSuite, self).__init__(tests) |
| 584 | self.collected_from = class_collected_from |
| 585 | |
| 586 | def id(self): |
| 587 | module = getattr(self.collected_from, "__module__", None) |
| 588 | if module is not None: |
| 589 | return "{0}.{1}".format(module, self.collected_from.__name__) |
| 590 | return self.collected_from.__name__ |
| 591 | |
| 592 | def run(self, result): |
| 593 | if getattr(self.collected_from, "__unittest_skip__", False): |
| 594 | # ClassTestSuite result pretends to be a TestCase enough to be |
| 595 | # reported. |
| 596 | result.startTest(self) |
| 597 | try: |
| 598 | result.addSkip(self, self.collected_from.__unittest_skip_why__) |
| 599 | finally: |
| 600 | result.stopTest(self) |
| 601 | else: |
| 602 | result = super(ClassTestSuite, self).run(result) |
| 603 | return result |
| 604 | |
| 605 | shortDescription = id |
| 606 | |
| 607 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 608 | class FunctionTestCase(TestCase): |
| 609 | """A test case that wraps a test function. |
| 610 | |
| 611 | This is useful for slipping pre-existing test functions into the |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 612 | unittest framework. Optionally, set-up and tidy-up functions can be |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 613 | supplied. As with TestCase, the tidy-up ('tearDown') function will |
| 614 | always be called if the set-up ('setUp') function ran successfully. |
| 615 | """ |
| 616 | |
| 617 | def __init__(self, testFunc, setUp=None, tearDown=None, |
| 618 | description=None): |
| 619 | TestCase.__init__(self) |
| 620 | self.__setUpFunc = setUp |
| 621 | self.__tearDownFunc = tearDown |
| 622 | self.__testFunc = testFunc |
| 623 | self.__description = description |
| 624 | |
| 625 | def setUp(self): |
| 626 | if self.__setUpFunc is not None: |
| 627 | self.__setUpFunc() |
| 628 | |
| 629 | def tearDown(self): |
| 630 | if self.__tearDownFunc is not None: |
| 631 | self.__tearDownFunc() |
| 632 | |
| 633 | def runTest(self): |
| 634 | self.__testFunc() |
| 635 | |
| 636 | def id(self): |
| 637 | return self.__testFunc.__name__ |
| 638 | |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 639 | def __eq__(self, other): |
| 640 | if type(self) is not type(other): |
| 641 | return False |
| 642 | |
| 643 | return self.__setUpFunc == other.__setUpFunc and \ |
| 644 | self.__tearDownFunc == other.__tearDownFunc and \ |
| 645 | self.__testFunc == other.__testFunc and \ |
| 646 | self.__description == other.__description |
| 647 | |
| 648 | def __ne__(self, other): |
| 649 | return not self == other |
| 650 | |
| 651 | def __hash__(self): |
Collin Winter | 9453e5d | 2007-03-09 23:30:39 +0000 | [diff] [blame] | 652 | return hash((type(self), self.__setUpFunc, self.__tearDownFunc, |
| 653 | self.__testFunc, self.__description)) |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 654 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 655 | def __str__(self): |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 656 | return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 657 | |
| 658 | def __repr__(self): |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 659 | return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 660 | |
| 661 | def shortDescription(self): |
| 662 | if self.__description is not None: return self.__description |
| 663 | doc = self.__testFunc.__doc__ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 664 | return doc and doc.split("\n")[0].strip() or None |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 665 | |
| 666 | |
| 667 | |
| 668 | ############################################################################## |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 669 | # Locating and loading tests |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 670 | ############################################################################## |
| 671 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 672 | class TestLoader(object): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 673 | """This class is responsible for loading tests according to various |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 674 | criteria and returning them wrapped in a TestSuite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 675 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 676 | testMethodPrefix = 'test' |
| 677 | sortTestMethodsUsing = cmp |
| 678 | suiteClass = TestSuite |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 679 | classSuiteClass = ClassTestSuite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 680 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 681 | def loadTestsFromTestCase(self, testCaseClass): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 682 | """Return a suite of all tests cases contained in testCaseClass""" |
Johannes Gijsbers | d7b6ad4 | 2004-11-07 15:46:25 +0000 | [diff] [blame] | 683 | if issubclass(testCaseClass, TestSuite): |
| 684 | raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?") |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 685 | testCaseNames = self.getTestCaseNames(testCaseClass) |
| 686 | if not testCaseNames and hasattr(testCaseClass, 'runTest'): |
| 687 | testCaseNames = ['runTest'] |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 688 | suite = self.classSuiteClass(map(testCaseClass, testCaseNames), |
| 689 | testCaseClass) |
| 690 | return suite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 691 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 692 | def loadTestsFromModule(self, module): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 693 | """Return a suite of all tests cases contained in the given module""" |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 694 | tests = [] |
| 695 | for name in dir(module): |
| 696 | obj = getattr(module, name) |
Guido van Rossum | 6791137 | 2002-09-30 19:25:56 +0000 | [diff] [blame] | 697 | if (isinstance(obj, (type, types.ClassType)) and |
| 698 | issubclass(obj, TestCase)): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 699 | tests.append(self.loadTestsFromTestCase(obj)) |
| 700 | return self.suiteClass(tests) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 701 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 702 | def loadTestsFromName(self, name, module=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 703 | """Return a suite of all tests cases given a string specifier. |
| 704 | |
| 705 | The name may resolve either to a module, a test case class, a |
| 706 | test method within a test case class, or a callable object which |
| 707 | returns a TestCase or TestSuite instance. |
Tim Peters | 613b222 | 2001-04-13 05:37:27 +0000 | [diff] [blame] | 708 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 709 | The method optionally resolves the names relative to a given module. |
| 710 | """ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 711 | parts = name.split('.') |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 712 | if module is None: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 713 | parts_copy = parts[:] |
| 714 | while parts_copy: |
| 715 | try: |
| 716 | module = __import__('.'.join(parts_copy)) |
| 717 | break |
| 718 | except ImportError: |
| 719 | del parts_copy[-1] |
| 720 | if not parts_copy: raise |
Armin Rigo | 1b3c04b | 2003-10-24 17:15:29 +0000 | [diff] [blame] | 721 | parts = parts[1:] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 722 | obj = module |
| 723 | for part in parts: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 724 | parent, obj = obj, getattr(obj, part) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 725 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 726 | if isinstance(obj, types.ModuleType): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 727 | return self.loadTestsFromModule(obj) |
Guido van Rossum | 6791137 | 2002-09-30 19:25:56 +0000 | [diff] [blame] | 728 | elif (isinstance(obj, (type, types.ClassType)) and |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 729 | issubclass(obj, TestCase)): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 730 | return self.loadTestsFromTestCase(obj) |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 731 | elif (isinstance(obj, types.UnboundMethodType) and |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 732 | isinstance(parent, (type, types.ClassType)) and |
| 733 | issubclass(parent, TestCase)): |
| 734 | return TestSuite([parent(obj.__name__)]) |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 735 | elif isinstance(obj, TestSuite): |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 736 | return obj |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 737 | elif hasattr(obj, '__call__'): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 738 | test = obj() |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 739 | if isinstance(test, TestSuite): |
| 740 | return test |
| 741 | elif isinstance(test, TestCase): |
| 742 | return TestSuite([test]) |
| 743 | else: |
| 744 | raise TypeError("calling %s returned %s, not a test" % |
| 745 | (obj, test)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 746 | else: |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 747 | raise TypeError("don't know how to make test from: %s" % obj) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 748 | |
| 749 | def loadTestsFromNames(self, names, module=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 750 | """Return a suite of all tests cases found using the given sequence |
| 751 | of string specifiers. See 'loadTestsFromName()'. |
| 752 | """ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 753 | suites = [self.loadTestsFromName(name, module) for name in names] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 754 | return self.suiteClass(suites) |
| 755 | |
| 756 | def getTestCaseNames(self, testCaseClass): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 757 | """Return a sorted sequence of method names found within testCaseClass |
| 758 | """ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 759 | def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix): |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 760 | return attrname.startswith(prefix) and 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): |
| 805 | if arg: self.write(arg) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 806 | self.write('\n') # text-mode streams translate to \r\n if needed |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 807 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 808 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 809 | class _TextTestResult(TestResult): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 810 | """A test result class that can print formatted text results to a stream. |
| 811 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 812 | Used by TextTestRunner. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 813 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 814 | separator1 = '=' * 70 |
| 815 | separator2 = '-' * 70 |
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 | def __init__(self, stream, descriptions, verbosity): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 818 | TestResult.__init__(self) |
| 819 | self.stream = stream |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 820 | self.showAll = verbosity > 1 |
| 821 | self.dots = verbosity == 1 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 822 | self.descriptions = descriptions |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 823 | |
| 824 | def getDescription(self, test): |
| 825 | if self.descriptions: |
| 826 | return test.shortDescription() or str(test) |
| 827 | else: |
| 828 | return str(test) |
| 829 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 830 | def startTest(self, test): |
| 831 | TestResult.startTest(self, test) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 832 | if self.showAll: |
| 833 | self.stream.write(self.getDescription(test)) |
| 834 | self.stream.write(" ... ") |
Georg Brandl | d063240 | 2008-05-11 15:17:41 +0000 | [diff] [blame] | 835 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 836 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 837 | def addSuccess(self, test): |
| 838 | TestResult.addSuccess(self, test) |
| 839 | if self.showAll: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 840 | self.stream.writeln("ok") |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 841 | elif self.dots: |
| 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 | |
| 845 | def addError(self, test, err): |
| 846 | TestResult.addError(self, test, err) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 847 | if self.showAll: |
| 848 | self.stream.writeln("ERROR") |
| 849 | elif self.dots: |
| 850 | self.stream.write('E') |
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 addFailure(self, test, err): |
| 854 | TestResult.addFailure(self, test, err) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 855 | if self.showAll: |
| 856 | self.stream.writeln("FAIL") |
| 857 | elif self.dots: |
| 858 | self.stream.write('F') |
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 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 861 | def addSkip(self, test, reason): |
| 862 | TestResult.addSkip(self, test, reason) |
| 863 | if self.showAll: |
| 864 | self.stream.writeln("skipped {0!r}".format(reason)) |
| 865 | elif self.dots: |
| 866 | self.stream.write("s") |
| 867 | self.stream.flush() |
| 868 | |
| 869 | def addExpectedFailure(self, test, err): |
| 870 | TestResult.addExpectedFailure(self, test, err) |
| 871 | if self.showAll: |
| 872 | self.stream.writeln("expected failure") |
| 873 | elif self.dots: |
| 874 | self.stream.write(".") |
| 875 | self.stream.flush() |
| 876 | |
| 877 | def addUnexpectedSuccess(self, test): |
| 878 | TestResult.addUnexpectedSuccess(self, test) |
| 879 | if self.showAll: |
| 880 | self.stream.writeln("unexpected success") |
| 881 | elif self.dots: |
| 882 | self.stream.write(".") |
| 883 | self.stream.flush() |
| 884 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 885 | def printErrors(self): |
| 886 | if self.dots or self.showAll: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 887 | self.stream.writeln() |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 888 | self.printErrorList('ERROR', self.errors) |
| 889 | self.printErrorList('FAIL', self.failures) |
| 890 | |
| 891 | def printErrorList(self, flavour, errors): |
| 892 | for test, err in errors: |
| 893 | self.stream.writeln(self.separator1) |
| 894 | self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) |
| 895 | self.stream.writeln(self.separator2) |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 896 | self.stream.writeln("%s" % err) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 897 | |
| 898 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 899 | class TextTestRunner(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 900 | """A test runner class that displays results in textual form. |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 901 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 902 | It prints out the names of tests as they are run, errors as they |
| 903 | occur, and a summary of the results at the end of the test run. |
| 904 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 905 | def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 906 | self.stream = _WritelnDecorator(stream) |
| 907 | self.descriptions = descriptions |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 908 | self.verbosity = verbosity |
| 909 | |
| 910 | def _makeResult(self): |
| 911 | return _TextTestResult(self.stream, self.descriptions, self.verbosity) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 912 | |
| 913 | def run(self, test): |
| 914 | "Run the given test case or test suite." |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 915 | result = self._makeResult() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 916 | startTime = time.time() |
| 917 | test(result) |
| 918 | stopTime = time.time() |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 919 | timeTaken = stopTime - startTime |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 920 | result.printErrors() |
| 921 | self.stream.writeln(result.separator2) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 922 | run = result.testsRun |
| 923 | self.stream.writeln("Ran %d test%s in %.3fs" % |
Neal Norwitz | 7616504 | 2002-05-31 14:15:11 +0000 | [diff] [blame] | 924 | (run, run != 1 and "s" or "", timeTaken)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 925 | self.stream.writeln() |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 926 | results = map(len, (result.expectedFailures, |
| 927 | result.unexpectedSuccesses, |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 928 | result.skipped)) |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 929 | expectedFails, unexpectedSuccesses, skipped = results |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 930 | infos = [] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 931 | if not result.wasSuccessful(): |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 932 | self.stream.write("FAILED") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 933 | failed, errored = map(len, (result.failures, result.errors)) |
| 934 | if failed: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 935 | infos.append("failures=%d" % failed) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 936 | if errored: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 937 | infos.append("errors=%d" % errored) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 938 | else: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 939 | self.stream.write("OK") |
| 940 | if skipped: |
| 941 | infos.append("skipped=%d" % skipped) |
| 942 | if expected_fails: |
| 943 | infos.append("expected failures=%d" % expected_fails) |
| 944 | if unexpected_successes: |
| 945 | infos.append("unexpected successes=%d" % unexpected_successes) |
| 946 | if infos: |
| 947 | self.stream.writeln(" (%s)" % (", ".join(infos),)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 948 | return result |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 949 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 950 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 951 | |
| 952 | ############################################################################## |
| 953 | # Facilities for running tests from the command line |
| 954 | ############################################################################## |
| 955 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 956 | class TestProgram(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 957 | """A command-line program that runs a set of tests; this is primarily |
| 958 | for making test modules conveniently executable. |
| 959 | """ |
| 960 | USAGE = """\ |
Steve Purcell | 17a781b | 2001-04-09 15:37:31 +0000 | [diff] [blame] | 961 | Usage: %(progName)s [options] [test] [...] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 962 | |
| 963 | Options: |
| 964 | -h, --help Show this message |
| 965 | -v, --verbose Verbose output |
| 966 | -q, --quiet Minimal output |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 967 | |
| 968 | Examples: |
| 969 | %(progName)s - run default set of tests |
| 970 | %(progName)s MyTestSuite - run suite 'MyTestSuite' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 971 | %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething |
| 972 | %(progName)s MyTestCase - run all 'test*' test methods |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 973 | in MyTestCase |
| 974 | """ |
| 975 | def __init__(self, module='__main__', defaultTest=None, |
Georg Brandl | d0a9625 | 2007-03-07 09:21:06 +0000 | [diff] [blame] | 976 | argv=None, testRunner=TextTestRunner, |
| 977 | testLoader=defaultTestLoader): |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 978 | if isinstance(module, basestring): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 979 | self.module = __import__(module) |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 980 | for part in module.split('.')[1:]: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 981 | self.module = getattr(self.module, part) |
| 982 | else: |
| 983 | self.module = module |
| 984 | if argv is None: |
| 985 | argv = sys.argv |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 986 | self.verbosity = 1 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 987 | self.defaultTest = defaultTest |
| 988 | self.testRunner = testRunner |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 989 | self.testLoader = testLoader |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 990 | self.progName = os.path.basename(argv[0]) |
| 991 | self.parseArgs(argv) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 992 | self.runTests() |
| 993 | |
| 994 | def usageExit(self, msg=None): |
| 995 | if msg: print msg |
| 996 | print self.USAGE % self.__dict__ |
| 997 | sys.exit(2) |
| 998 | |
| 999 | def parseArgs(self, argv): |
| 1000 | import getopt |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1001 | long_opts = ['help','verbose','quiet'] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1002 | try: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1003 | options, args = getopt.getopt(argv[1:], 'hHvq', long_opts) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1004 | for opt, value in options: |
| 1005 | if opt in ('-h','-H','--help'): |
| 1006 | self.usageExit() |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1007 | if opt in ('-q','--quiet'): |
| 1008 | self.verbosity = 0 |
| 1009 | if opt in ('-v','--verbose'): |
| 1010 | self.verbosity = 2 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1011 | if len(args) == 0 and self.defaultTest is None: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1012 | self.test = self.testLoader.loadTestsFromModule(self.module) |
| 1013 | return |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1014 | if len(args) > 0: |
| 1015 | self.testNames = args |
| 1016 | else: |
| 1017 | self.testNames = (self.defaultTest,) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1018 | self.createTests() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1019 | except getopt.error, msg: |
| 1020 | self.usageExit(msg) |
| 1021 | |
| 1022 | def createTests(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1023 | self.test = self.testLoader.loadTestsFromNames(self.testNames, |
| 1024 | self.module) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1025 | |
| 1026 | def runTests(self): |
Georg Brandl | d0a9625 | 2007-03-07 09:21:06 +0000 | [diff] [blame] | 1027 | if isinstance(self.testRunner, (type, types.ClassType)): |
| 1028 | try: |
| 1029 | testRunner = self.testRunner(verbosity=self.verbosity) |
| 1030 | except TypeError: |
| 1031 | # didn't accept the verbosity argument |
| 1032 | testRunner = self.testRunner() |
| 1033 | else: |
| 1034 | # it is assumed to be a TestRunner instance |
| 1035 | testRunner = self.testRunner |
| 1036 | result = testRunner.run(self.test) |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 1037 | sys.exit(not result.wasSuccessful()) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1038 | |
| 1039 | main = TestProgram |
| 1040 | |
| 1041 | |
| 1042 | ############################################################################## |
| 1043 | # Executing this module from the command line |
| 1044 | ############################################################################## |
| 1045 | |
| 1046 | if __name__ == "__main__": |
| 1047 | main(module=None) |