Updated for hfsplus module, new gusi libs.
[python/dscho.git] / Lib / unittest.py
blob3f59916760da3e23b9a2f152c3869d419f07e3fc
1 #!/usr/bin/env python
2 '''
3 Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
4 Smalltalk testing framework.
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).
11 Simple usage:
13 import unittest
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)
23 if __name__ == '__main__':
24 unittest.main()
26 Further information is available in the bundled documentation, and from
28 http://pyunit.sourceforge.net/
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.
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.
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.
45 '''
47 __author__ = "Steve Purcell"
48 __email__ = "stephen_purcell at yahoo dot com"
49 __version__ = "$Revision$"[11:-2]
51 import time
52 import sys
53 import traceback
54 import string
55 import os
56 import types
58 ##############################################################################
59 # Test framework core
60 ##############################################################################
62 class TestResult:
63 """Holder for test result information.
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.
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 the
71 formatted traceback of the error that occurred.
72 """
73 def __init__(self):
74 self.failures = []
75 self.errors = []
76 self.testsRun = 0
77 self.shouldStop = 0
79 def startTest(self, test):
80 "Called when the given test is about to be run"
81 self.testsRun = self.testsRun + 1
83 def stopTest(self, test):
84 "Called when the given test has been run"
85 pass
87 def addError(self, test, err):
88 """Called when an error has occurred. 'err' is a tuple of values as
89 returned by sys.exc_info().
90 """
91 self.errors.append((test, self._exc_info_to_string(err)))
93 def addFailure(self, test, err):
94 """Called when an error has occurred. 'err' is a tuple of values as
95 returned by sys.exc_info()."""
96 self.failures.append((test, self._exc_info_to_string(err)))
98 def addSuccess(self, test):
99 "Called when a test has completed successfully"
100 pass
102 def wasSuccessful(self):
103 "Tells whether or not this result was a success"
104 return len(self.failures) == len(self.errors) == 0
106 def stop(self):
107 "Indicates that the tests should be aborted"
108 self.shouldStop = 1
110 def _exc_info_to_string(self, err):
111 """Converts a sys.exc_info()-style tuple of values into a string."""
112 return string.join(apply(traceback.format_exception, err), '')
114 def __repr__(self):
115 return "<%s run=%i errors=%i failures=%i>" % \
116 (self.__class__, self.testsRun, len(self.errors),
117 len(self.failures))
120 class TestCase:
121 """A class whose instances are single test cases.
123 By default, the test code itself should be placed in a method named
124 'runTest'.
126 If the fixture may be used for many test cases, create as
127 many test methods as are needed. When instantiating such a TestCase
128 subclass, specify in the constructor arguments the name of the test method
129 that the instance is to execute.
131 Test authors should subclass TestCase for their own tests. Construction
132 and deconstruction of the test's environment ('fixture') can be
133 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
135 If it is necessary to override the __init__ method, the base class
136 __init__ method must always be called. It is important that subclasses
137 should not change the signature of their __init__ method, since instances
138 of the classes are instantiated automatically by parts of the framework
139 in order to be run.
142 # This attribute determines which exception will be raised when
143 # the instance's assertion methods fail; test methods raising this
144 # exception will be deemed to have 'failed' rather than 'errored'
146 failureException = AssertionError
148 def __init__(self, methodName='runTest'):
149 """Create an instance of the class that will use the named test
150 method when executed. Raises a ValueError if the instance does
151 not have a method with the specified name.
153 try:
154 self.__testMethodName = methodName
155 testMethod = getattr(self, methodName)
156 self.__testMethodDoc = testMethod.__doc__
157 except AttributeError:
158 raise ValueError, "no such test method in %s: %s" % \
159 (self.__class__, methodName)
161 def setUp(self):
162 "Hook method for setting up the test fixture before exercising it."
163 pass
165 def tearDown(self):
166 "Hook method for deconstructing the test fixture after testing it."
167 pass
169 def countTestCases(self):
170 return 1
172 def defaultTestResult(self):
173 return TestResult()
175 def shortDescription(self):
176 """Returns a one-line description of the test, or None if no
177 description has been provided.
179 The default implementation of this method returns the first line of
180 the specified test method's docstring.
182 doc = self.__testMethodDoc
183 return doc and string.strip(string.split(doc, "\n")[0]) or None
185 def id(self):
186 return "%s.%s" % (self.__class__, self.__testMethodName)
188 def __str__(self):
189 return "%s (%s)" % (self.__testMethodName, self.__class__)
191 def __repr__(self):
192 return "<%s testMethod=%s>" % \
193 (self.__class__, self.__testMethodName)
195 def run(self, result=None):
196 return self(result)
198 def __call__(self, result=None):
199 if result is None: result = self.defaultTestResult()
200 result.startTest(self)
201 testMethod = getattr(self, self.__testMethodName)
202 try:
203 try:
204 self.setUp()
205 except KeyboardInterrupt:
206 raise
207 except:
208 result.addError(self, self.__exc_info())
209 return
211 ok = 0
212 try:
213 testMethod()
214 ok = 1
215 except self.failureException, e:
216 result.addFailure(self, self.__exc_info())
217 except KeyboardInterrupt:
218 raise
219 except:
220 result.addError(self, self.__exc_info())
222 try:
223 self.tearDown()
224 except KeyboardInterrupt:
225 raise
226 except:
227 result.addError(self, self.__exc_info())
228 ok = 0
229 if ok: result.addSuccess(self)
230 finally:
231 result.stopTest(self)
233 def debug(self):
234 """Run the test without collecting errors in a TestResult"""
235 self.setUp()
236 getattr(self, self.__testMethodName)()
237 self.tearDown()
239 def __exc_info(self):
240 """Return a version of sys.exc_info() with the traceback frame
241 minimised; usually the top level of the traceback frame is not
242 needed.
244 exctype, excvalue, tb = sys.exc_info()
245 if sys.platform[:4] == 'java': ## tracebacks look different in Jython
246 return (exctype, excvalue, tb)
247 newtb = tb.tb_next
248 if newtb is None:
249 return (exctype, excvalue, tb)
250 return (exctype, excvalue, newtb)
252 def fail(self, msg=None):
253 """Fail immediately, with the given message."""
254 raise self.failureException, msg
256 def failIf(self, expr, msg=None):
257 "Fail the test if the expression is true."
258 if expr: raise self.failureException, msg
260 def failUnless(self, expr, msg=None):
261 """Fail the test unless the expression is true."""
262 if not expr: raise self.failureException, msg
264 def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
265 """Fail unless an exception of class excClass is thrown
266 by callableObj when invoked with arguments args and keyword
267 arguments kwargs. If a different type of exception is
268 thrown, it will not be caught, and the test case will be
269 deemed to have suffered an error, exactly as for an
270 unexpected exception.
272 try:
273 apply(callableObj, args, kwargs)
274 except excClass:
275 return
276 else:
277 if hasattr(excClass,'__name__'): excName = excClass.__name__
278 else: excName = str(excClass)
279 raise self.failureException, excName
281 def failUnlessEqual(self, first, second, msg=None):
282 """Fail if the two objects are unequal as determined by the '!='
283 operator.
285 if first != second:
286 raise self.failureException, (msg or '%s != %s' % (first, second))
288 def failIfEqual(self, first, second, msg=None):
289 """Fail if the two objects are equal as determined by the '=='
290 operator.
292 if first == second:
293 raise self.failureException, (msg or '%s == %s' % (first, second))
295 assertEqual = assertEquals = failUnlessEqual
297 assertNotEqual = assertNotEquals = failIfEqual
299 assertRaises = failUnlessRaises
301 assert_ = failUnless
305 class TestSuite:
306 """A test suite is a composite test consisting of a number of TestCases.
308 For use, create an instance of TestSuite, then add test case instances.
309 When all tests have been added, the suite can be passed to a test
310 runner, such as TextTestRunner. It will run the individual test cases
311 in the order in which they were added, aggregating the results. When
312 subclassing, do not forget to call the base class constructor.
314 def __init__(self, tests=()):
315 self._tests = []
316 self.addTests(tests)
318 def __repr__(self):
319 return "<%s tests=%s>" % (self.__class__, self._tests)
321 __str__ = __repr__
323 def countTestCases(self):
324 cases = 0
325 for test in self._tests:
326 cases = cases + test.countTestCases()
327 return cases
329 def addTest(self, test):
330 self._tests.append(test)
332 def addTests(self, tests):
333 for test in tests:
334 self.addTest(test)
336 def run(self, result):
337 return self(result)
339 def __call__(self, result):
340 for test in self._tests:
341 if result.shouldStop:
342 break
343 test(result)
344 return result
346 def debug(self):
347 """Run the tests without collecting errors in a TestResult"""
348 for test in self._tests: test.debug()
351 class FunctionTestCase(TestCase):
352 """A test case that wraps a test function.
354 This is useful for slipping pre-existing test functions into the
355 PyUnit framework. Optionally, set-up and tidy-up functions can be
356 supplied. As with TestCase, the tidy-up ('tearDown') function will
357 always be called if the set-up ('setUp') function ran successfully.
360 def __init__(self, testFunc, setUp=None, tearDown=None,
361 description=None):
362 TestCase.__init__(self)
363 self.__setUpFunc = setUp
364 self.__tearDownFunc = tearDown
365 self.__testFunc = testFunc
366 self.__description = description
368 def setUp(self):
369 if self.__setUpFunc is not None:
370 self.__setUpFunc()
372 def tearDown(self):
373 if self.__tearDownFunc is not None:
374 self.__tearDownFunc()
376 def runTest(self):
377 self.__testFunc()
379 def id(self):
380 return self.__testFunc.__name__
382 def __str__(self):
383 return "%s (%s)" % (self.__class__, self.__testFunc.__name__)
385 def __repr__(self):
386 return "<%s testFunc=%s>" % (self.__class__, self.__testFunc)
388 def shortDescription(self):
389 if self.__description is not None: return self.__description
390 doc = self.__testFunc.__doc__
391 return doc and string.strip(string.split(doc, "\n")[0]) or None
395 ##############################################################################
396 # Locating and loading tests
397 ##############################################################################
399 class TestLoader:
400 """This class is responsible for loading tests according to various
401 criteria and returning them wrapped in a Test
403 testMethodPrefix = 'test'
404 sortTestMethodsUsing = cmp
405 suiteClass = TestSuite
407 def loadTestsFromTestCase(self, testCaseClass):
408 """Return a suite of all tests cases contained in testCaseClass"""
409 return self.suiteClass(map(testCaseClass,
410 self.getTestCaseNames(testCaseClass)))
412 def loadTestsFromModule(self, module):
413 """Return a suite of all tests cases contained in the given module"""
414 tests = []
415 for name in dir(module):
416 obj = getattr(module, name)
417 if type(obj) == types.ClassType and issubclass(obj, TestCase):
418 tests.append(self.loadTestsFromTestCase(obj))
419 return self.suiteClass(tests)
421 def loadTestsFromName(self, name, module=None):
422 """Return a suite of all tests cases given a string specifier.
424 The name may resolve either to a module, a test case class, a
425 test method within a test case class, or a callable object which
426 returns a TestCase or TestSuite instance.
428 The method optionally resolves the names relative to a given module.
430 parts = string.split(name, '.')
431 if module is None:
432 if not parts:
433 raise ValueError, "incomplete test name: %s" % name
434 else:
435 parts_copy = parts[:]
436 while parts_copy:
437 try:
438 module = __import__(string.join(parts_copy,'.'))
439 break
440 except ImportError:
441 del parts_copy[-1]
442 if not parts_copy: raise
443 parts = parts[1:]
444 obj = module
445 for part in parts:
446 obj = getattr(obj, part)
448 import unittest
449 if type(obj) == types.ModuleType:
450 return self.loadTestsFromModule(obj)
451 elif type(obj) == types.ClassType and issubclass(obj, unittest.TestCase):
452 return self.loadTestsFromTestCase(obj)
453 elif type(obj) == types.UnboundMethodType:
454 return obj.im_class(obj.__name__)
455 elif callable(obj):
456 test = obj()
457 if not isinstance(test, unittest.TestCase) and \
458 not isinstance(test, unittest.TestSuite):
459 raise ValueError, \
460 "calling %s returned %s, not a test" % (obj,test)
461 return test
462 else:
463 raise ValueError, "don't know how to make test from: %s" % obj
465 def loadTestsFromNames(self, names, module=None):
466 """Return a suite of all tests cases found using the given sequence
467 of string specifiers. See 'loadTestsFromName()'.
469 suites = []
470 for name in names:
471 suites.append(self.loadTestsFromName(name, module))
472 return self.suiteClass(suites)
474 def getTestCaseNames(self, testCaseClass):
475 """Return a sorted sequence of method names found within testCaseClass
477 testFnNames = filter(lambda n,p=self.testMethodPrefix: n[:len(p)] == p,
478 dir(testCaseClass))
479 for baseclass in testCaseClass.__bases__:
480 for testFnName in self.getTestCaseNames(baseclass):
481 if testFnName not in testFnNames: # handle overridden methods
482 testFnNames.append(testFnName)
483 if self.sortTestMethodsUsing:
484 testFnNames.sort(self.sortTestMethodsUsing)
485 return testFnNames
489 defaultTestLoader = TestLoader()
492 ##############################################################################
493 # Patches for old functions: these functions should be considered obsolete
494 ##############################################################################
496 def _makeLoader(prefix, sortUsing, suiteClass=None):
497 loader = TestLoader()
498 loader.sortTestMethodsUsing = sortUsing
499 loader.testMethodPrefix = prefix
500 if suiteClass: loader.suiteClass = suiteClass
501 return loader
503 def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
504 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
506 def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
507 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
509 def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
510 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
513 ##############################################################################
514 # Text UI
515 ##############################################################################
517 class _WritelnDecorator:
518 """Used to decorate file-like objects with a handy 'writeln' method"""
519 def __init__(self,stream):
520 self.stream = stream
522 def __getattr__(self, attr):
523 return getattr(self.stream,attr)
525 def writeln(self, *args):
526 if args: apply(self.write, args)
527 self.write('\n') # text-mode streams translate to \r\n if needed
530 class _TextTestResult(TestResult):
531 """A test result class that can print formatted text results to a stream.
533 Used by TextTestRunner.
535 separator1 = '=' * 70
536 separator2 = '-' * 70
538 def __init__(self, stream, descriptions, verbosity):
539 TestResult.__init__(self)
540 self.stream = stream
541 self.showAll = verbosity > 1
542 self.dots = verbosity == 1
543 self.descriptions = descriptions
545 def getDescription(self, test):
546 if self.descriptions:
547 return test.shortDescription() or str(test)
548 else:
549 return str(test)
551 def startTest(self, test):
552 TestResult.startTest(self, test)
553 if self.showAll:
554 self.stream.write(self.getDescription(test))
555 self.stream.write(" ... ")
557 def addSuccess(self, test):
558 TestResult.addSuccess(self, test)
559 if self.showAll:
560 self.stream.writeln("ok")
561 elif self.dots:
562 self.stream.write('.')
564 def addError(self, test, err):
565 TestResult.addError(self, test, err)
566 if self.showAll:
567 self.stream.writeln("ERROR")
568 elif self.dots:
569 self.stream.write('E')
570 if err[0] is KeyboardInterrupt:
571 self.shouldStop = 1
573 def addFailure(self, test, err):
574 TestResult.addFailure(self, test, err)
575 if self.showAll:
576 self.stream.writeln("FAIL")
577 elif self.dots:
578 self.stream.write('F')
580 def printErrors(self):
581 if self.dots or self.showAll:
582 self.stream.writeln()
583 self.printErrorList('ERROR', self.errors)
584 self.printErrorList('FAIL', self.failures)
586 def printErrorList(self, flavour, errors):
587 for test, err in errors:
588 self.stream.writeln(self.separator1)
589 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
590 self.stream.writeln(self.separator2)
591 self.stream.writeln("%s" % err)
594 class TextTestRunner:
595 """A test runner class that displays results in textual form.
597 It prints out the names of tests as they are run, errors as they
598 occur, and a summary of the results at the end of the test run.
600 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
601 self.stream = _WritelnDecorator(stream)
602 self.descriptions = descriptions
603 self.verbosity = verbosity
605 def _makeResult(self):
606 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
608 def run(self, test):
609 "Run the given test case or test suite."
610 result = self._makeResult()
611 startTime = time.time()
612 test(result)
613 stopTime = time.time()
614 timeTaken = float(stopTime - startTime)
615 result.printErrors()
616 self.stream.writeln(result.separator2)
617 run = result.testsRun
618 self.stream.writeln("Ran %d test%s in %.3fs" %
619 (run, run == 1 and "" or "s", timeTaken))
620 self.stream.writeln()
621 if not result.wasSuccessful():
622 self.stream.write("FAILED (")
623 failed, errored = map(len, (result.failures, result.errors))
624 if failed:
625 self.stream.write("failures=%d" % failed)
626 if errored:
627 if failed: self.stream.write(", ")
628 self.stream.write("errors=%d" % errored)
629 self.stream.writeln(")")
630 else:
631 self.stream.writeln("OK")
632 return result
636 ##############################################################################
637 # Facilities for running tests from the command line
638 ##############################################################################
640 class TestProgram:
641 """A command-line program that runs a set of tests; this is primarily
642 for making test modules conveniently executable.
644 USAGE = """\
645 Usage: %(progName)s [options] [test] [...]
647 Options:
648 -h, --help Show this message
649 -v, --verbose Verbose output
650 -q, --quiet Minimal output
652 Examples:
653 %(progName)s - run default set of tests
654 %(progName)s MyTestSuite - run suite 'MyTestSuite'
655 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
656 %(progName)s MyTestCase - run all 'test*' test methods
657 in MyTestCase
659 def __init__(self, module='__main__', defaultTest=None,
660 argv=None, testRunner=None, testLoader=defaultTestLoader):
661 if type(module) == type(''):
662 self.module = __import__(module)
663 for part in string.split(module,'.')[1:]:
664 self.module = getattr(self.module, part)
665 else:
666 self.module = module
667 if argv is None:
668 argv = sys.argv
669 self.verbosity = 1
670 self.defaultTest = defaultTest
671 self.testRunner = testRunner
672 self.testLoader = testLoader
673 self.progName = os.path.basename(argv[0])
674 self.parseArgs(argv)
675 self.runTests()
677 def usageExit(self, msg=None):
678 if msg: print msg
679 print self.USAGE % self.__dict__
680 sys.exit(2)
682 def parseArgs(self, argv):
683 import getopt
684 try:
685 options, args = getopt.getopt(argv[1:], 'hHvq',
686 ['help','verbose','quiet'])
687 for opt, value in options:
688 if opt in ('-h','-H','--help'):
689 self.usageExit()
690 if opt in ('-q','--quiet'):
691 self.verbosity = 0
692 if opt in ('-v','--verbose'):
693 self.verbosity = 2
694 if len(args) == 0 and self.defaultTest is None:
695 self.test = self.testLoader.loadTestsFromModule(self.module)
696 return
697 if len(args) > 0:
698 self.testNames = args
699 else:
700 self.testNames = (self.defaultTest,)
701 self.createTests()
702 except getopt.error, msg:
703 self.usageExit(msg)
705 def createTests(self):
706 self.test = self.testLoader.loadTestsFromNames(self.testNames,
707 self.module)
709 def runTests(self):
710 if self.testRunner is None:
711 self.testRunner = TextTestRunner(verbosity=self.verbosity)
712 result = self.testRunner.run(self.test)
713 sys.exit(not result.wasSuccessful())
715 main = TestProgram
718 ##############################################################################
719 # Executing this module from the command line
720 ##############################################################################
722 if __name__ == "__main__":
723 main(module=None)