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