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