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