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