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