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: 5816 $"[11:-2]
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.
80 "Called when the given test is about to be run"
84 "Called when the given test has been run"
88 """Called when an error has occurred. 'err' is a tuple of values as
89 returned by sys.exc_info().
91 self.errors.append((test, self._exc_info_to_string(err)))
94 """Called when an error has occurred. 'err' is a tuple of values as
95 returned by sys.exc_info()."""
99 "Called when a test has completed successfully"
103 "Tells whether or not this result was a success"
104 return len(self.failures) == len(self.errors) == 0
107 "Indicates that the tests should be aborted"
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),
'')
115 return "<%s run=%i errors=%i failures=%i>" % \
121 """A class whose instances are single test cases.
123 By default, the test code itself should be placed in a method named
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
146 failureException = AssertionError
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.
155 testMethod = getattr(self, methodName)
157 except AttributeError:
158 raise ValueError,
"no such test method in %s: %s" % \
159 (self.__class__, methodName)
162 "Hook method for setting up the test fixture before exercising it."
166 "Hook method for deconstructing the test fixture after testing it."
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.
192 return "<%s testMethod=%s>" % \
195 def run(self, result=None):
200 result.startTest(self)
205 except KeyboardInterrupt:
217 except KeyboardInterrupt:
224 except KeyboardInterrupt:
229 if ok: result.addSuccess(self)
231 result.stopTest(self)
234 """Run the test without collecting errors in a TestResult"""
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
244 exctype, excvalue, tb = sys.exc_info()
245 if sys.platform[:4] ==
'java':
246 return (exctype, excvalue, tb)
249 return (exctype, excvalue, tb)
250 return (exctype, excvalue, newtb)
253 """Fail immediately, with the given message."""
257 "Fail the test if the expression is true."
261 """Fail the test unless the expression is true."""
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.
273 apply(callableObj, args, kwargs)
277 if hasattr(excClass,
'__name__'): excName = excClass.__name__
278 else: excName =
str(excClass)
282 """Fail if the two objects are unequal as determined by the '!='
287 (msg
or '%s != %s' % (`first`, `second`))
290 """Fail if the two objects are equal as determined by the '=='
295 (msg
or '%s == %s' % (`first`, `second`))
297 assertEqual = assertEquals = failUnlessEqual
299 assertNotEqual = assertNotEquals = failIfEqual
301 assertRaises = failUnlessRaises
308 """A test suite is a composite test consisting of a number of TestCases.
310 For use, create an instance of TestSuite, then add test case instances.
311 When all tests have been added, the suite can be passed to a test
312 runner, such as TextTestRunner. It will run the individual test cases
313 in the order in which they were added, aggregating the results. When
314 subclassing, do not forget to call the base class constructor.
321 return "<%s tests=%s>" % (self.__class__, self.
_tests)
328 cases = cases + test.countTestCases()
332 self._tests.append(test)
343 if result.shouldStop:
349 """Run the tests without collecting errors in a TestResult"""
350 for test
in self.
_tests: test.debug()
354 """A test case that wraps a test function.
356 This is useful for slipping pre-existing test functions into the
357 PyUnit framework. Optionally, set-up and tidy-up functions can be
358 supplied. As with TestCase, the tidy-up ('tearDown') function will
359 always be called if the set-up ('setUp') function ran successfully.
362 def __init__(self, testFunc, setUp=None, tearDown=None,
364 TestCase.__init__(self)
382 return self.__testFunc.__name__
385 return "%s (%s)" % (self.__class__, self.__testFunc.__name__)
388 return "<%s testFunc=%s>" % (self.__class__, self.
__testFunc)
392 doc = self.__testFunc.__doc__
402 """This class is responsible for loading tests according to various
403 criteria and returning them wrapped in a Test
405 testMethodPrefix =
'test'
406 sortTestMethodsUsing = cmp
407 suiteClass = TestSuite
410 """Return a suite of all tests cases contained in testCaseClass"""
415 """Return a suite of all tests cases contained in the given module"""
417 for name
in dir(module):
418 obj = getattr(module, name)
419 if type(obj) == types.ClassType
and issubclass(obj, TestCase):
424 """Return a suite of all tests cases given a string specifier.
426 The name may resolve either to a module, a test case class, a
427 test method within a test case class, or a callable object which
428 returns a TestCase or TestSuite instance.
430 The method optionally resolves the names relative to a given module.
435 raise ValueError,
"incomplete test name: %s" % name
437 parts_copy = parts[:]
444 if not parts_copy:
raise
448 obj = getattr(obj, part)
451 if type(obj) == types.ModuleType:
455 elif type(obj) == types.UnboundMethodType:
456 return obj.im_class(obj.__name__)
462 "calling %s returned %s, not a test" % (obj,test)
465 raise ValueError,
"don't know how to make test from: %s" % obj
468 """Return a suite of all tests cases found using the given sequence
469 of string specifiers. See 'loadTestsFromName()'.
477 """Return a sorted sequence of method names found within testCaseClass
481 for baseclass
in testCaseClass.__bases__:
483 if testFnName
not in testFnNames:
484 testFnNames.append(testFnName)
498 def _makeLoader(prefix, sortUsing, suiteClass=None):
500 loader.sortTestMethodsUsing = sortUsing
501 loader.testMethodPrefix = prefix
502 if suiteClass: loader.suiteClass = suiteClass
508 def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
509 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
511 def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
512 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
520 """Used to decorate file-like objects with a handy 'writeln' method"""
525 return getattr(self.
stream,attr)
528 if args: apply(self.write, args)
533 """A test result class that can print formatted text results to a stream.
535 Used by TextTestRunner.
537 separator1 =
'=' * 70
538 separator2 =
'-' * 70
540 def __init__(self, stream, descriptions, verbosity):
541 TestResult.__init__(self)
549 return test.shortDescription()
or str(test)
554 TestResult.startTest(self, test)
557 self.stream.write(
" ... ")
560 TestResult.addSuccess(self, test)
562 self.stream.writeln(
"ok")
564 self.stream.write(
'.')
567 TestResult.addError(self, test, err)
569 self.stream.writeln(
"ERROR")
571 self.stream.write(
'E')
574 TestResult.addFailure(self, test, err)
576 self.stream.writeln(
"FAIL")
578 self.stream.write(
'F')
582 self.stream.writeln()
587 for test, err
in errors:
589 self.stream.writeln(
"%s: %s" % (flavour,self.
getDescription(test)))
591 self.stream.writeln(
"%s" % err)
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):
605 def _makeResult(self):
609 "Run the given test case or test suite."
611 startTime = time.time()
613 stopTime = time.time()
614 timeTaken = float(stopTime - startTime)
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))
625 self.stream.write(
"failures=%d" % failed)
627 if failed: self.stream.write(
", ")
628 self.stream.write(
"errors=%d" % errored)
629 self.stream.writeln(
")")
631 self.stream.writeln(
"OK")
641 """A command-line program that runs a set of tests; this is primarily
642 for making test modules conveniently executable.
645 Usage: %(progName)s [options] [test] [...]
648 -h, --help Show this message
649 -v, --verbose Verbose output
650 -q, --quiet Minimal output
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
659 def __init__(self, module='__main__', defaultTest=None,
660 argv=
None, testRunner=
None, testLoader=defaultTestLoader):
661 if type(module) == type(
''):
679 print self.
USAGE % self.__dict__
686 [
'help',
'verbose',
'quiet'])
687 for opt, value
in options:
688 if opt
in (
'-h',
'-H',
'--help'):
690 if opt
in (
'-q',
'--quiet'):
692 if opt
in (
'-v',
'--verbose'):
702 except getopt.error, msg:
706 self.
test = self.testLoader.loadTestsFromNames(self.
testNames,
712 result = self.testRunner.run(self.
test)
713 sys.exit(
not result.wasSuccessful())
722 if __name__ ==
"__main__":