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: |
| 192 | result.addError(self,self.__exc_info()) |
| 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: |
| 200 | result.addFailure(self,self.__exc_info()) |
| 201 | except: |
| 202 | result.addError(self,self.__exc_info()) |
| 203 | |
| 204 | try: |
| 205 | self.tearDown() |
| 206 | except: |
| 207 | result.addError(self,self.__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 | def __exc_info(self): |
| 270 | """Return a version of sys.exc_info() with the traceback frame |
| 271 | minimised; usually the top level of the traceback frame is not |
| 272 | needed. |
| 273 | """ |
| 274 | exctype, excvalue, tb = sys.exc_info() |
| 275 | newtb = tb.tb_next |
| 276 | if newtb is None: |
| 277 | return (exctype, excvalue, tb) |
| 278 | return (exctype, excvalue, newtb) |
| 279 | |
| 280 | |
| 281 | class TestSuite: |
| 282 | """A test suite is a composite test consisting of a number of TestCases. |
| 283 | |
| 284 | For use, create an instance of TestSuite, then add test case instances. |
| 285 | When all tests have been added, the suite can be passed to a test |
| 286 | runner, such as TextTestRunner. It will run the individual test cases |
| 287 | in the order in which they were added, aggregating the results. When |
| 288 | subclassing, do not forget to call the base class constructor. |
| 289 | """ |
| 290 | def __init__(self, tests=()): |
| 291 | self._tests = [] |
| 292 | self.addTests(tests) |
| 293 | |
| 294 | def __repr__(self): |
| 295 | return "<%s tests=%s>" % (self.__class__, self._tests) |
| 296 | |
| 297 | __str__ = __repr__ |
| 298 | |
| 299 | def countTestCases(self): |
| 300 | cases = 0 |
| 301 | for test in self._tests: |
| 302 | cases = cases + test.countTestCases() |
| 303 | return cases |
| 304 | |
| 305 | def addTest(self, test): |
| 306 | self._tests.append(test) |
| 307 | |
| 308 | def addTests(self, tests): |
| 309 | for test in tests: |
| 310 | self.addTest(test) |
| 311 | |
| 312 | def run(self, result): |
| 313 | return self(result) |
| 314 | |
| 315 | def __call__(self, result): |
| 316 | for test in self._tests: |
| 317 | if result.shouldStop: |
| 318 | break |
| 319 | test(result) |
| 320 | return result |
| 321 | |
| 322 | def debug(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 323 | """Run the tests without collecting errors in a TestResult""" |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 324 | for test in self._tests: test.debug() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 325 | |
| 326 | |
| 327 | class FunctionTestCase(TestCase): |
| 328 | """A test case that wraps a test function. |
| 329 | |
| 330 | This is useful for slipping pre-existing test functions into the |
| 331 | PyUnit framework. Optionally, set-up and tidy-up functions can be |
| 332 | supplied. As with TestCase, the tidy-up ('tearDown') function will |
| 333 | always be called if the set-up ('setUp') function ran successfully. |
| 334 | """ |
| 335 | |
| 336 | def __init__(self, testFunc, setUp=None, tearDown=None, |
| 337 | description=None): |
| 338 | TestCase.__init__(self) |
| 339 | self.__setUpFunc = setUp |
| 340 | self.__tearDownFunc = tearDown |
| 341 | self.__testFunc = testFunc |
| 342 | self.__description = description |
| 343 | |
| 344 | def setUp(self): |
| 345 | if self.__setUpFunc is not None: |
| 346 | self.__setUpFunc() |
| 347 | |
| 348 | def tearDown(self): |
| 349 | if self.__tearDownFunc is not None: |
| 350 | self.__tearDownFunc() |
| 351 | |
| 352 | def runTest(self): |
| 353 | self.__testFunc() |
| 354 | |
| 355 | def id(self): |
| 356 | return self.__testFunc.__name__ |
| 357 | |
| 358 | def __str__(self): |
| 359 | return "%s (%s)" % (self.__class__, self.__testFunc.__name__) |
| 360 | |
| 361 | def __repr__(self): |
| 362 | return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) |
| 363 | |
| 364 | def shortDescription(self): |
| 365 | if self.__description is not None: return self.__description |
| 366 | doc = self.__testFunc.__doc__ |
| 367 | return doc and string.strip(string.split(doc, "\n")[0]) or None |
| 368 | |
| 369 | |
| 370 | |
| 371 | ############################################################################## |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 372 | # Locating and loading tests |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 373 | ############################################################################## |
| 374 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 375 | class TestLoader: |
| 376 | """This class is responsible for loading tests according to various |
| 377 | criteria and returning them wrapped in a Test |
| 378 | |
| 379 | It can load all tests within a given, module |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 380 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 381 | testMethodPrefix = 'test' |
| 382 | sortTestMethodsUsing = cmp |
| 383 | suiteClass = TestSuite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 384 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 385 | def loadTestsFromTestCase(self, testCaseClass): |
| 386 | return self.suiteClass(map(testCaseClass, |
| 387 | self.getTestCaseNames(testCaseClass))) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 388 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 389 | def loadTestsFromModule(self, module): |
| 390 | tests = [] |
| 391 | for name in dir(module): |
| 392 | obj = getattr(module, name) |
| 393 | if type(obj) == types.ClassType and issubclass(obj, TestCase): |
| 394 | tests.append(self.loadTestsFromTestCase(obj)) |
| 395 | return self.suiteClass(tests) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 396 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 397 | def loadTestsFromName(self, name, module=None): |
| 398 | parts = string.split(name, '.') |
| 399 | if module is None: |
| 400 | if not parts: |
| 401 | raise ValueError, "incomplete test name: %s" % name |
| 402 | else: |
| 403 | module = __import__(parts) |
| 404 | parts = parts[1:] |
| 405 | obj = module |
| 406 | for part in parts: |
| 407 | obj = getattr(obj, part) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 408 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 409 | if type(obj) == types.ModuleType: |
| 410 | return self.loadTestsFromModule(obj) |
| 411 | elif type(obj) == types.ClassType and issubclass(obj, TestCase): |
| 412 | return self.loadTestsFromTestCase(obj) |
| 413 | elif type(obj) == types.UnboundMethodType: |
| 414 | return obj.im_class(obj.__name__) |
| 415 | elif callable(obj): |
| 416 | test = obj() |
| 417 | if not isinstance(test, TestCase) and \ |
| 418 | not isinstance(test, TestSuite): |
| 419 | raise ValueError, \ |
| 420 | "calling %s returned %s, not a test" % obj,test |
| 421 | return test |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 422 | else: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 423 | raise ValueError, "don't know how to make test from: %s" % obj |
| 424 | |
| 425 | def loadTestsFromNames(self, names, module=None): |
| 426 | suites = [] |
| 427 | for name in names: |
| 428 | suites.append(self.loadTestsFromName(name, module)) |
| 429 | return self.suiteClass(suites) |
| 430 | |
| 431 | def getTestCaseNames(self, testCaseClass): |
| 432 | testFnNames = filter(lambda n,p=self.testMethodPrefix: n[:len(p)] == p, |
| 433 | dir(testCaseClass)) |
| 434 | for baseclass in testCaseClass.__bases__: |
| 435 | for testFnName in self.getTestCaseNames(baseclass): |
| 436 | if testFnName not in testFnNames: # handle overridden methods |
| 437 | testFnNames.append(testFnName) |
| 438 | if self.sortTestMethodsUsing: |
| 439 | testFnNames.sort(self.sortTestMethodsUsing) |
| 440 | return testFnNames |
| 441 | |
| 442 | |
| 443 | |
| 444 | defaultTestLoader = TestLoader() |
| 445 | |
| 446 | |
| 447 | ############################################################################## |
| 448 | # Patches for old functions: these functions should be considered obsolete |
| 449 | ############################################################################## |
| 450 | |
| 451 | def _makeLoader(prefix, sortUsing, suiteClass=None): |
| 452 | loader = TestLoader() |
| 453 | loader.sortTestMethodsUsing = sortUsing |
| 454 | loader.testMethodPrefix = prefix |
| 455 | if suiteClass: loader.suiteClass = suiteClass |
| 456 | return loader |
| 457 | |
| 458 | def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): |
| 459 | return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass) |
| 460 | |
| 461 | def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite): |
| 462 | return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass) |
| 463 | |
| 464 | def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite): |
| 465 | return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 466 | |
| 467 | |
| 468 | ############################################################################## |
| 469 | # Text UI |
| 470 | ############################################################################## |
| 471 | |
| 472 | class _WritelnDecorator: |
| 473 | """Used to decorate file-like objects with a handy 'writeln' method""" |
| 474 | def __init__(self,stream): |
| 475 | self.stream = stream |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 476 | |
| 477 | def __getattr__(self, attr): |
| 478 | return getattr(self.stream,attr) |
| 479 | |
| 480 | def writeln(self, *args): |
| 481 | if args: apply(self.write, args) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 482 | self.write('\n') # text-mode streams translate to \r\n if needed |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 483 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 484 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 485 | class _TextTestResult(TestResult): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 486 | """A test result class that can print formatted text results to a stream. |
| 487 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 488 | Used by TextTestRunner. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 489 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 490 | separator1 = '=' * 70 |
| 491 | separator2 = '-' * 70 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 492 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 493 | def __init__(self, stream, descriptions, verbosity): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 494 | TestResult.__init__(self) |
| 495 | self.stream = stream |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 496 | self.showAll = verbosity > 1 |
| 497 | self.dots = verbosity == 1 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 498 | self.descriptions = descriptions |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 499 | |
| 500 | def getDescription(self, test): |
| 501 | if self.descriptions: |
| 502 | return test.shortDescription() or str(test) |
| 503 | else: |
| 504 | return str(test) |
| 505 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 506 | def startTest(self, test): |
| 507 | TestResult.startTest(self, test) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 508 | if self.showAll: |
| 509 | self.stream.write(self.getDescription(test)) |
| 510 | self.stream.write(" ... ") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 511 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 512 | def addSuccess(self, test): |
| 513 | TestResult.addSuccess(self, test) |
| 514 | if self.showAll: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 515 | self.stream.writeln("ok") |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 516 | elif self.dots: |
| 517 | self.stream.write('.') |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 518 | |
| 519 | def addError(self, test, err): |
| 520 | TestResult.addError(self, test, err) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 521 | if self.showAll: |
| 522 | self.stream.writeln("ERROR") |
| 523 | elif self.dots: |
| 524 | self.stream.write('E') |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 525 | if err[0] is KeyboardInterrupt: |
| 526 | self.shouldStop = 1 |
| 527 | |
| 528 | def addFailure(self, test, err): |
| 529 | TestResult.addFailure(self, test, err) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 530 | if self.showAll: |
| 531 | self.stream.writeln("FAIL") |
| 532 | elif self.dots: |
| 533 | self.stream.write('F') |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 534 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 535 | def printErrors(self): |
| 536 | if self.dots or self.showAll: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 537 | self.stream.writeln() |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 538 | self.printErrorList('ERROR', self.errors) |
| 539 | self.printErrorList('FAIL', self.failures) |
| 540 | |
| 541 | def printErrorList(self, flavour, errors): |
| 542 | for test, err in errors: |
| 543 | self.stream.writeln(self.separator1) |
| 544 | self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) |
| 545 | self.stream.writeln(self.separator2) |
| 546 | for line in apply(traceback.format_exception, err): |
| 547 | for l in string.split(line,"\n")[:-1]: |
| 548 | self.stream.writeln("%s" % l) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 549 | |
| 550 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 551 | class TextTestRunner: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 552 | """A test runner class that displays results in textual form. |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 553 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 554 | It prints out the names of tests as they are run, errors as they |
| 555 | occur, and a summary of the results at the end of the test run. |
| 556 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 557 | def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 558 | self.stream = _WritelnDecorator(stream) |
| 559 | self.descriptions = descriptions |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 560 | self.verbosity = verbosity |
| 561 | |
| 562 | def _makeResult(self): |
| 563 | return _TextTestResult(self.stream, self.descriptions, self.verbosity) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 564 | |
| 565 | def run(self, test): |
| 566 | "Run the given test case or test suite." |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 567 | result = self._makeResult() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 568 | startTime = time.time() |
| 569 | test(result) |
| 570 | stopTime = time.time() |
| 571 | timeTaken = float(stopTime - startTime) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 572 | result.printErrors() |
| 573 | self.stream.writeln(result.separator2) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 574 | run = result.testsRun |
| 575 | self.stream.writeln("Ran %d test%s in %.3fs" % |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 576 | (run, run == 1 and "" or "s", timeTaken)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 577 | self.stream.writeln() |
| 578 | if not result.wasSuccessful(): |
| 579 | self.stream.write("FAILED (") |
| 580 | failed, errored = map(len, (result.failures, result.errors)) |
| 581 | if failed: |
| 582 | self.stream.write("failures=%d" % failed) |
| 583 | if errored: |
| 584 | if failed: self.stream.write(", ") |
| 585 | self.stream.write("errors=%d" % errored) |
| 586 | self.stream.writeln(")") |
| 587 | else: |
| 588 | self.stream.writeln("OK") |
| 589 | return result |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 590 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 591 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 592 | |
| 593 | ############################################################################## |
| 594 | # Facilities for running tests from the command line |
| 595 | ############################################################################## |
| 596 | |
| 597 | class TestProgram: |
| 598 | """A command-line program that runs a set of tests; this is primarily |
| 599 | for making test modules conveniently executable. |
| 600 | """ |
| 601 | USAGE = """\ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 602 | Usage: %(progName)s [options] [test[:(casename|prefix-)]] [...] |
| 603 | |
| 604 | Options: |
| 605 | -h, --help Show this message |
| 606 | -v, --verbose Verbose output |
| 607 | -q, --quiet Minimal output |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 608 | |
| 609 | Examples: |
| 610 | %(progName)s - run default set of tests |
| 611 | %(progName)s MyTestSuite - run suite 'MyTestSuite' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 612 | %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething |
| 613 | %(progName)s MyTestCase - run all 'test*' test methods |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 614 | in MyTestCase |
| 615 | """ |
| 616 | def __init__(self, module='__main__', defaultTest=None, |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 617 | argv=None, testRunner=None, testLoader=defaultTestLoader): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 618 | if type(module) == type(''): |
| 619 | self.module = __import__(module) |
| 620 | for part in string.split(module,'.')[1:]: |
| 621 | self.module = getattr(self.module, part) |
| 622 | else: |
| 623 | self.module = module |
| 624 | if argv is None: |
| 625 | argv = sys.argv |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 626 | self.verbosity = 1 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 627 | self.defaultTest = defaultTest |
| 628 | self.testRunner = testRunner |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 629 | self.testLoader = testLoader |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 630 | self.progName = os.path.basename(argv[0]) |
| 631 | self.parseArgs(argv) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 632 | self.runTests() |
| 633 | |
| 634 | def usageExit(self, msg=None): |
| 635 | if msg: print msg |
| 636 | print self.USAGE % self.__dict__ |
| 637 | sys.exit(2) |
| 638 | |
| 639 | def parseArgs(self, argv): |
| 640 | import getopt |
| 641 | try: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 642 | options, args = getopt.getopt(argv[1:], 'hHvq', |
| 643 | ['help','verbose','quiet']) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 644 | opts = {} |
| 645 | for opt, value in options: |
| 646 | if opt in ('-h','-H','--help'): |
| 647 | self.usageExit() |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 648 | if opt in ('-q','--quiet'): |
| 649 | self.verbosity = 0 |
| 650 | if opt in ('-v','--verbose'): |
| 651 | self.verbosity = 2 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 652 | if len(args) == 0 and self.defaultTest is None: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 653 | self.test = self.testLoader.loadTestsFromModule(self.module) |
| 654 | return |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 655 | if len(args) > 0: |
| 656 | self.testNames = args |
| 657 | else: |
| 658 | self.testNames = (self.defaultTest,) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 659 | self.createTests() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 660 | except getopt.error, msg: |
| 661 | self.usageExit(msg) |
| 662 | |
| 663 | def createTests(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 664 | self.test = self.testLoader.loadTestsFromNames(self.testNames, |
| 665 | self.module) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 666 | |
| 667 | def runTests(self): |
| 668 | if self.testRunner is None: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 669 | self.testRunner = TextTestRunner(verbosity=self.verbosity) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 670 | result = self.testRunner.run(self.test) |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 671 | sys.exit(not result.wasSuccessful()) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 672 | |
| 673 | main = TestProgram |
| 674 | |
| 675 | |
| 676 | ############################################################################## |
| 677 | # Executing this module from the command line |
| 678 | ############################################################################## |
| 679 | |
| 680 | if __name__ == "__main__": |
| 681 | main(module=None) |