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