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