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
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__':
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
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.
47 __author__
= "Steve Purcell"
48 __email__
= "stephen_purcell at yahoo dot com"
49 __version__
= "#Revision: 1.46 $"[11:-2]
58 ##############################################################################
60 ##############################################################################
62 # All classes defined herein are 'new-style' classes, allowing use of 'super()'
66 return "%s.%s" % (cls
.__module
__, cls
.__name
__)
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.
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"
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().
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"
108 def wasSuccessful(self
):
109 "Tells whether or not this result was a success"
110 return len(self
.failures
) == len(self
.errors
) == 0
113 "Indicates that the tests should be aborted"
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
), '')
121 return "<%s run=%i errors=%i failures=%i>" % \
122 (_strclass(self
.__class
__), self
.testsRun
, len(self
.errors
),
127 """A class whose instances are single test cases.
129 By default, the test code itself should be placed in a method named
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
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.
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
)
168 "Hook method for setting up the test fixture before exercising it."
172 "Hook method for deconstructing the test fixture after testing it."
175 def countTestCases(self
):
178 def defaultTestResult(self
):
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
192 return "%s.%s" % (_strclass(self
.__class
__), self
.__testMethodName
)
195 return "%s (%s)" % (self
.__testMethodName
, _strclass(self
.__class
__))
198 return "<%s testMethod=%s>" % \
199 (_strclass(self
.__class
__), self
.__testMethodName
)
201 def run(self
, result
=None):
204 def __call__(self
, result
=None):
205 if result
is None: result
= self
.defaultTestResult()
206 result
.startTest(self
)
207 testMethod
= getattr(self
, self
.__testMethodName
)
211 except KeyboardInterrupt:
214 result
.addError(self
, self
.__exc
_info
())
221 except self
.failureException
, e
:
222 result
.addFailure(self
, self
.__exc
_info
())
223 except KeyboardInterrupt:
226 result
.addError(self
, self
.__exc
_info
())
230 except KeyboardInterrupt:
233 result
.addError(self
, self
.__exc
_info
())
235 if ok
: result
.addSuccess(self
)
237 result
.stopTest(self
)
240 """Run the test without collecting errors in a TestResult"""
242 getattr(self
, self
.__testMethodName
)()
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
250 exctype
, excvalue
, tb
= sys
.exc_info()
251 if sys
.platform
[:4] == 'java': ## tracebacks look different in Jython
252 return (exctype
, excvalue
, tb
)
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.
279 callableObj(*args
, **kwargs
)
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 '=='
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 '=='
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
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
=()):
355 return "<%s tests=%s>" % (_strclass(self
.__class
__), self
._tests
)
359 def countTestCases(self
):
361 for test
in self
._tests
:
362 cases
= cases
+ test
.countTestCases()
365 def addTest(self
, test
):
366 self
._tests
.append(test
)
368 def addTests(self
, tests
):
372 def run(self
, result
):
375 def __call__(self
, result
):
376 for test
in self
._tests
:
377 if result
.shouldStop
:
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,
398 TestCase
.__init
__(self
)
399 self
.__setUpFunc
= setUp
400 self
.__tearDownFunc
= tearDown
401 self
.__testFunc
= testFunc
402 self
.__description
= description
405 if self
.__setUpFunc
is not None:
409 if self
.__tearDownFunc
is not None:
410 self
.__tearDownFunc
()
416 return self
.__testFunc
.__name
__
419 return "%s (%s)" % (_strclass(self
.__class
__), self
.__testFunc
.__name
__)
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 ##############################################################################
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"""
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
, '.')
470 raise ValueError, "incomplete test name: %s" % name
472 parts_copy
= parts
[:]
475 module
= __import__(string
.join(parts_copy
,'.'))
479 if not parts_copy
: raise
483 obj
= getattr(obj
, part
)
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
__)
495 if not isinstance(test
, unittest
.TestCase
) and \
496 not isinstance(test
, unittest
.TestSuite
):
498 "calling %s returned %s, not a test" % (obj
,test
)
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()'.
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
,
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
)
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
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 ##############################################################################
553 ##############################################################################
555 class _WritelnDecorator
:
556 """Used to decorate file-like objects with a handy 'writeln' method"""
557 def __init__(self
,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
)
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
)
589 def startTest(self
, test
):
590 TestResult
.startTest(self
, test
)
592 self
.stream
.write(self
.getDescription(test
))
593 self
.stream
.write(" ... ")
595 def addSuccess(self
, test
):
596 TestResult
.addSuccess(self
, test
)
598 self
.stream
.writeln("ok")
600 self
.stream
.write('.')
602 def addError(self
, test
, err
):
603 TestResult
.addError(self
, test
, err
)
605 self
.stream
.writeln("ERROR")
607 self
.stream
.write('E')
609 def addFailure(self
, test
, err
):
610 TestResult
.addFailure(self
, test
, err
)
612 self
.stream
.writeln("FAIL")
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
)
645 "Run the given test case or test suite."
646 result
= self
._makeResult
()
647 startTime
= time
.time()
649 stopTime
= time
.time()
650 timeTaken
= float(stopTime
- startTime
)
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
))
661 self
.stream
.write("failures=%d" % failed
)
663 if failed
: self
.stream
.write(", ")
664 self
.stream
.write("errors=%d" % errored
)
665 self
.stream
.writeln(")")
667 self
.stream
.writeln("OK")
672 ##############################################################################
673 # Facilities for running tests from the command line
674 ##############################################################################
677 """A command-line program that runs a set of tests; this is primarily
678 for making test modules conveniently executable.
681 Usage: %(progName)s [options] [test] [...]
684 -h, --help Show this message
685 -v, --verbose Verbose output
686 -q, --quiet Minimal output
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
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
)
706 self
.defaultTest
= defaultTest
707 self
.testRunner
= testRunner
708 self
.testLoader
= testLoader
709 self
.progName
= os
.path
.basename(argv
[0])
713 def usageExit(self
, msg
=None):
715 print self
.USAGE
% self
.__dict
__
718 def parseArgs(self
, argv
):
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'):
726 if opt
in ('-q','--quiet'):
728 if opt
in ('-v','--verbose'):
730 if len(args
) == 0 and self
.defaultTest
is None:
731 self
.test
= self
.testLoader
.loadTestsFromModule(self
.module
)
734 self
.testNames
= args
736 self
.testNames
= (self
.defaultTest
,)
738 except getopt
.error
, msg
:
741 def createTests(self
):
742 self
.test
= self
.testLoader
.loadTestsFromNames(self
.testNames
,
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())
754 ##############################################################################
755 # Executing this module from the command line
756 ##############################################################################
758 if __name__
== "__main__":