25.3.unittest — Unit testing framework¶
New in version 2.1.
(If you are already familiar with the basic concepts of testing, you might wantto skip tothe list of assert methods.)
The Python unit testing framework, sometimes referred to as “PyUnit,” is aPython language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, inturn, a Java version of Kent’s Smalltalk testing framework. Each is the defacto standard unit testing framework for its respective language.
unittest supports test automation, sharing of setup and shutdown code fortests, aggregation of tests into collections, and independence of the tests fromthe reporting framework. Theunittest module provides classes that makeit easy to support these qualities for a set of tests.
To achieve this,unittest supports some important concepts:
- test fixture
Atest fixture represents the preparation needed to perform one or moretests, and any associate cleanup actions. This may involve, for example,creating temporary or proxy databases, directories, or starting a serverprocess.
- test case
Atest case is the smallest unit of testing. It checks for a specificresponse to a particular set of inputs.
unittestprovides a base class,TestCase, which may be used to create new test cases.- test suite
Atest suite is a collection of test cases, test suites, or both. It isused to aggregate tests that should be executed together.
- test runner
Atest runner is a component which orchestrates the execution of testsand provides the outcome to the user. The runner may use a graphical interface,a textual interface, or return a special value to indicate the results ofexecuting the tests.
The test case and test fixture concepts are supported through theTestCase andFunctionTestCase classes; the former should beused when creating new tests, and the latter can be used when integratingexisting test code with aunittest-driven framework. When building testfixtures usingTestCase, thesetUp() andtearDown() methods can be overridden to provide initializationand cleanup for the fixture. WithFunctionTestCase, existing functionscan be passed to the constructor for these purposes. When the test is run, thefixture initialization is run first; if it succeeds, the cleanup method is runafter the test has been executed, regardless of the outcome of the test. Eachinstance of theTestCase will only be used to run a single test method,so a new fixture is created for each test.
Test suites are implemented by theTestSuite class. This class allowsindividual tests and test suites to be aggregated; when the suite is executed,all tests added directly to the suite and in “child” test suites are run.
A test runner is an object that provides a single method,run(), which accepts aTestCase orTestSuiteobject as a parameter, and returns a result object. The classTestResult is provided for use as the result object.unittestprovides theTextTestRunner as an example test runner which reportstest results on the standard error stream by default. Alternate runners can beimplemented for other environments (such as graphical environments) without anyneed to derive from a specific class.
See also
- Module
doctest Another test-support module with a very different flavor.
- unittest2: A backport of new unittest features for Python 2.4-2.6
Many new features were added to unittest in Python 2.7, including testdiscovery. unittest2 allows you to use these features with earlierversions of Python.
- Simple Smalltalk Testing: With Patterns
Kent Beck’s original paper on testing frameworks using the pattern sharedby
unittest.- Nose andpytest
Third-party unittest frameworks with a lighter-weight syntax for writingtests. For example,
assertfunc(10)==42.- The Python Testing Tools Taxonomy
An extensive list of Python testing tools including functional testingframeworks and mock object libraries.
- Testing in Python Mailing List
A special-interest-group for discussion of testing, and testing tools,in Python.
25.3.1.Basic example¶
Theunittest module provides a rich set of tools for constructing andrunning tests. This section demonstrates that a small subset of the toolssuffice to meet the needs of most users.
Here is a short script to test three string methods:
importunittestclassTestStringMethods(unittest.TestCase):deftest_upper(self):self.assertEqual('foo'.upper(),'FOO')deftest_isupper(self):self.assertTrue('FOO'.isupper())self.assertFalse('Foo'.isupper())deftest_split(self):s='hello world'self.assertEqual(s.split(),['hello','world'])# check that s.split fails when the separator is not a stringwithself.assertRaises(TypeError):s.split(2)if__name__=='__main__':unittest.main()
A testcase is created by subclassingunittest.TestCase. The threeindividual tests are defined with methods whose names start with the letterstest. This naming convention informs the test runner about which methodsrepresent tests.
The crux of each test is a call toassertEqual() to check for anexpected result;assertTrue() orassertFalse()to verify a condition; orassertRaises() to verify that aspecific exception gets raised. These methods are used instead of theassert statement so the test runner can accumulate all test resultsand produce a report.
ThesetUp() andtearDown() methods allow youto define instructions that will be executed before and after each test method.They are covered in more detail in the sectionOrganizing test code.
The final block shows a simple way to run the tests.unittest.main()provides a command-line interface to the test script. When run from the commandline, the above script produces an output that looks like this:
...----------------------------------------------------------------------Ran3testsin0.000sOK
Instead ofunittest.main(), there are other ways to run the tests with afiner level of control, less terse output, and no requirement to be run from thecommand line. For example, the last two lines may be replaced with:
suite=unittest.TestLoader().loadTestsFromTestCase(TestStringMethods)unittest.TextTestRunner(verbosity=2).run(suite)
Running the revised script from the interpreter or another script produces thefollowing output:
test_isupper(__main__.TestStringMethods)...oktest_split(__main__.TestStringMethods)...oktest_upper(__main__.TestStringMethods)...ok----------------------------------------------------------------------Ran3testsin0.001sOK
The above examples show the most commonly usedunittest features whichare sufficient to meet many everyday testing needs. The remainder of thedocumentation explores the full feature set from first principles.
25.3.2.Command-Line Interface¶
The unittest module can be used from the command line to run tests frommodules, classes or even individual test methods:
python-munittesttest_module1test_module2python-munittesttest_module.TestClasspython-munittesttest_module.TestClass.test_method
You can pass in a list with any combination of module names, and fullyqualified class or method names.
You can run tests with more detail (higher verbosity) by passing in the -v flag:
python-munittest-vtest_module
For a list of all the command-line options:
python-munittest-h
Changed in version 2.7:In earlier versions it was only possible to run individual test methods andnot modules or classes.
25.3.2.1.Command-line options¶
unittest supports these command-line options:
-b,--buffer¶The standard output and standard error streams are buffered during the testrun. Output during a passing test is discarded. Output is echoed normallyon test fail or error and is added to the failure messages.
-c,--catch¶Control-C during the test run waits for the current test to end and thenreports all the results so far. A secondControl-C raises the normal
KeyboardInterruptexception.SeeSignal Handling for the functions that provide this functionality.
-f,--failfast¶Stop the test run on the first error or failure.
New in version 2.7:The command-line options-b,-c and-f were added.
The command line can also be used for test discovery, for running all of thetests in a project or just a subset.
25.3.3.Test Discovery¶
New in version 2.7.
Unittest supports simple test discovery. In order to be compatible with testdiscovery, all of the test files must bemodules orpackages importable from the top-level directory ofthe project (this means that their filenames must be valididentifiers).
Test discovery is implemented inTestLoader.discover(), but can also beused from the command line. The basic command-line usage is:
cdproject_directorypython-munittestdiscover
Thediscover sub-command has the following options:
-v,--verbose¶Verbose output
-s,--start-directorydirectory¶Directory to start discovery (
.default)
-p,--patternpattern¶Pattern to match test files (
test*.pydefault)
-t,--top-level-directorydirectory¶Top level directory of project (defaults to start directory)
The-s,-p, and-t options can be passed inas positional arguments in that order. The following two command linesare equivalent:
python-munittestdiscover-sproject_directory-p"*_test.py"python-munittestdiscoverproject_directory"*_test.py"
As well as being a path it is possible to pass a package name, for examplemyproject.subpackage.test, as the start directory. The package name yousupply will then be imported and its location on the filesystem will be usedas the start directory.
Caution
Test discovery loads tests by importing them. Once test discovery hasfound all the test files from the start directory you specify it turns thepaths into package names to import. For examplefoo/bar/baz.py will beimported asfoo.bar.baz.
If you have a package installed globally and attempt test discovery ona different copy of the package then the importcould happen from thewrong place. If this happens test discovery will warn you and exit.
If you supply the start directory as a package name rather than apath to a directory then discover assumes that whichever location itimports from is the location you intended, so you will not get thewarning.
Test modules and packages can customize test loading and discovery by throughtheload_tests protocol.
25.3.4.Organizing test code¶
The basic building blocks of unit testing aretest cases — singlescenarios that must be set up and checked for correctness. Inunittest,test cases are represented by instances ofunittest’sTestCaseclass. To make your own test cases you must write subclasses ofTestCase, or useFunctionTestCase.
An instance of aTestCase-derived class is an object that cancompletely run a single test method, together with optional set-up and tidy-upcode.
The testing code of aTestCase instance should be entirely selfcontained, such that it can be run either in isolation or in arbitrarycombination with any number of other test cases.
The simplestTestCase subclass will simply override therunTest() method in order to perform specific testing code:
importunittestclassDefaultWidgetSizeTestCase(unittest.TestCase):defrunTest(self):widget=Widget('The widget')self.assertEqual(widget.size(),(50,50),'incorrect default size')
Note that in order to test something, we use one of theassert*()methods provided by theTestCase base class. If the test fails, anexception will be raised, andunittest will identify the test case as afailure. Any other exceptions will be treated aserrors. Thishelps you identify where the problem is:failures are caused by incorrectresults - a 5 where you expected a 6.Errors are caused by incorrectcode - e.g., aTypeError caused by an incorrect function call.
The way to run a test case will be described later. For now, note that toconstruct an instance of such a test case, we call its constructor withoutarguments:
testCase=DefaultWidgetSizeTestCase()
Now, such test cases can be numerous, and their set-up can be repetitive. Inthe above case, constructing aWidget in each of 100 Widget test casesubclasses would mean unsightly duplication.
Luckily, we can factor out such set-up code by implementing a method calledsetUp(), which the testing framework will automatically call forus when we run the test:
importunittestclassSimpleWidgetTestCase(unittest.TestCase):defsetUp(self):self.widget=Widget('The widget')classDefaultWidgetSizeTestCase(SimpleWidgetTestCase):defrunTest(self):self.assertEqual(self.widget.size(),(50,50),'incorrect default size')classWidgetResizeTestCase(SimpleWidgetTestCase):defrunTest(self):self.widget.resize(100,150)self.assertEqual(self.widget.size(),(100,150),'wrong size after resize')
If thesetUp() method raises an exception while the test isrunning, the framework will consider the test to have suffered an error, and therunTest() method will not be executed.
Similarly, we can provide atearDown() method that tidies upafter therunTest() method has been run:
importunittestclassSimpleWidgetTestCase(unittest.TestCase):defsetUp(self):self.widget=Widget('The widget')deftearDown(self):self.widget.dispose()self.widget=None
IfsetUp() succeeded, thetearDown() method willbe run whetherrunTest() succeeded or not.
Such a working environment for the testing code is called afixture.
Often, many small test cases will use the same fixture. In this case, we wouldend up subclassingSimpleWidgetTestCase into many small one-methodclasses such asDefaultWidgetSizeTestCase. This is time-consuming anddiscouraging, so in the same vein as JUnit,unittest provides a simplermechanism:
importunittestclassWidgetTestCase(unittest.TestCase):defsetUp(self):self.widget=Widget('The widget')deftearDown(self):self.widget.dispose()self.widget=Nonedeftest_default_size(self):self.assertEqual(self.widget.size(),(50,50),'incorrect default size')deftest_resize(self):self.widget.resize(100,150)self.assertEqual(self.widget.size(),(100,150),'wrong size after resize')
Here we have not provided arunTest() method, but have insteadprovided two different test methods. Class instances will now each run one ofthetest_*() methods, withself.widget created and destroyedseparately for each instance. When creating an instance we must specify thetest method it is to run. We do this by passing the method name in theconstructor:
defaultSizeTestCase=WidgetTestCase('test_default_size')resizeTestCase=WidgetTestCase('test_resize')
Test case instances are grouped together according to the features they test.unittest provides a mechanism for this: thetest suite,represented byunittest’sTestSuite class:
widgetTestSuite=unittest.TestSuite()widgetTestSuite.addTest(WidgetTestCase('test_default_size'))widgetTestSuite.addTest(WidgetTestCase('test_resize'))
For the ease of running tests, as we will see later, it is a good idea toprovide in each test module a callable object that returns a pre-built testsuite:
defsuite():suite=unittest.TestSuite()suite.addTest(WidgetTestCase('test_default_size'))suite.addTest(WidgetTestCase('test_resize'))returnsuite
or even:
defsuite():tests=['test_default_size','test_resize']returnunittest.TestSuite(map(WidgetTestCase,tests))
Since it is a common pattern to create aTestCase subclass with manysimilarly named test functions,unittest provides aTestLoaderclass that can be used to automate the process of creating a test suite andpopulating it with individual tests. For example,
suite=unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
will create a test suite that will runWidgetTestCase.test_default_size() andWidgetTestCase.test_resize.TestLoader uses the'test' methodname prefix to identify test methods automatically.
Note that the order in which the various test cases will be run isdetermined by sorting the test function names with respect to thebuilt-in ordering for strings.
Often it is desirable to group suites of test cases together, so as to run testsfor the whole system at once. This is easy, sinceTestSuite instancescan be added to aTestSuite just asTestCase instances can beadded to aTestSuite:
suite1=module1.TheTestSuite()suite2=module2.TheTestSuite()alltests=unittest.TestSuite([suite1,suite2])
You can place the definitions of test cases and test suites in the same modulesas the code they are to test (such aswidget.py), but there are severaladvantages to placing the test code in a separate module, such astest_widget.py:
The test module can be run standalone from the command line.
The test code can more easily be separated from shipped code.
There is less temptation to change test code to fit the code it tests withouta good reason.
Test code should be modified much less frequently than the code it tests.
Tested code can be refactored more easily.
Tests for modules written in C must be in separate modules anyway, so why notbe consistent?
If the testing strategy changes, there is no need to change the source code.
25.3.5.Re-using old test code¶
Some users will find that they have existing test code that they would like torun fromunittest, without converting every old test function to aTestCase subclass.
For this reason,unittest provides aFunctionTestCase class.This subclass ofTestCase can be used to wrap an existing testfunction. Set-up and tear-down functions can also be provided.
Given the following test function:
deftestSomething():something=makeSomething()assertsomething.nameisnotNone# ...
one can create an equivalent test case instance as follows:
testcase=unittest.FunctionTestCase(testSomething)
If there are additional set-up and tear-down methods that should be called aspart of the test case’s operation, they can also be provided like so:
testcase=unittest.FunctionTestCase(testSomething,setUp=makeSomethingDB,tearDown=deleteSomethingDB)
To make migrating existing test suites easier,unittest supports testsraisingAssertionError to indicate test failure. However, it isrecommended that you use the explicitTestCase.fail*() andTestCase.assert*() methods instead, as future versions ofunittestmay treatAssertionError differently.
Note
Even thoughFunctionTestCase can be used to quickly convert anexisting test base over to aunittest-based system, this approach isnot recommended. Taking the time to set up properTestCasesubclasses will make future test refactorings infinitely easier.
In some cases, the existing tests may have been written using thedoctestmodule. If so,doctest provides aDocTestSuite class that canautomatically buildunittest.TestSuite instances from the existingdoctest-based tests.
25.3.6.Skipping tests and expected failures¶
New in version 2.7.
Unittest supports skipping individual test methods and even whole classes oftests. In addition, it supports marking a test as an “expected failure,” a testthat is broken and will fail, but shouldn’t be counted as a failure on aTestResult.
Skipping a test is simply a matter of using theskip()decoratoror one of its conditional variants.
Basic skipping looks like this:
classMyTestCase(unittest.TestCase):@unittest.skip("demonstrating skipping")deftest_nothing(self):self.fail("shouldn't happen")@unittest.skipIf(mylib.__version__<(1,3),"not supported in this library version")deftest_format(self):# Tests that work for only a certain version of the library.pass@unittest.skipUnless(sys.platform.startswith("win"),"requires Windows")deftest_windows_support(self):# windows specific testing codepass
This is the output of running the example above in verbose mode:
test_format(__main__.MyTestCase)...skipped'not supported in this library version'test_nothing(__main__.MyTestCase)...skipped'demonstrating skipping'test_windows_support(__main__.MyTestCase)...skipped'requires Windows'----------------------------------------------------------------------Ran3testsin0.005sOK(skipped=3)
Classes can be skipped just like methods:
@unittest.skip("showing class skipping")classMySkippedTestCase(unittest.TestCase):deftest_not_run(self):pass
TestCase.setUp() can also skip the test. This is useful when a resourcethat needs to be set up is not available.
Expected failures use theexpectedFailure() decorator.
classExpectedFailureTestCase(unittest.TestCase):@unittest.expectedFailuredeftest_fail(self):self.assertEqual(1,0,"broken")
It’s easy to roll your own skipping decorators by making a decorator that callsskip() on the test when it wants it to be skipped. This decorator skipsthe test unless the passed object has a certain attribute:
defskipUnlessHasattr(obj,attr):ifhasattr(obj,attr):returnlambdafunc:funcreturnunittest.skip("{!r} doesn't have{!r}".format(obj,attr))
The following decorators implement test skipping and expected failures:
unittest.skip(reason)¶Unconditionally skip the decorated test.reason should describe why thetest is being skipped.
unittest.skipIf(condition,reason)¶Skip the decorated test ifcondition is true.
unittest.skipUnless(condition,reason)¶Skip the decorated test unlesscondition is true.
unittest.expectedFailure()¶Mark the test as an expected failure. If the test fails when run, the testis not counted as a failure.
- exception
unittest.SkipTest(reason)¶ This exception is raised to skip a test.
Usually you can use
TestCase.skipTest()or one of the skippingdecorators instead of raising this directly.
Skipped tests will not havesetUp() ortearDown() run around them.Skipped classes will not havesetUpClass() ortearDownClass() run.
25.3.7.Classes and functions¶
This section describes in depth the API ofunittest.
25.3.7.1.Test cases¶
- class
unittest.TestCase(methodName='runTest')¶ Instances of the
TestCaseclass represent the smallest testable unitsin theunittestuniverse. This class is intended to be used as a baseclass, with specific tests being implemented by concrete subclasses. This classimplements the interface needed by the test runner to allow it to drive thetest, and methods that the test code can use to check for and report variouskinds of failure.Each instance of
TestCasewill run a single test method: the methodnamedmethodName. If you remember, we had an earlier example that wentsomething like this:defsuite():suite=unittest.TestSuite()suite.addTest(WidgetTestCase('test_default_size'))suite.addTest(WidgetTestCase('test_resize'))returnsuite
Here, we create two instances of
WidgetTestCase, each of which runs asingle test.methodName defaults to
runTest().TestCaseinstances provide three groups of methods: one group usedto run the test, another used by the test implementation to check conditionsand report failures, and some inquiry methods allowing information about thetest itself to be gathered.Methods in the first group (running the test) are:
setUp()¶Method called to prepare the test fixture. This is called immediatelybefore calling the test method; other than
AssertionErrororSkipTest,any exception raised by this method will be considered an error rather thana test failure. The default implementation does nothing.
tearDown()¶Method called immediately after the test method has been called and theresult recorded. This is called even if the test method raised anexception, so the implementation in subclasses may need to be particularlycareful about checking internal state. Any exception, other than
AssertionErrororSkipTest, raised by this method will beconsidered an additional error rather than a test failure (thus increasingthe total number of reported errors). This method will only be called ifthesetUp()succeeds, regardless of the outcome of the test method.The default implementation does nothing.
setUpClass()¶A class method called before tests in an individual class are run.
setUpClassis called with the class as the only argumentand must be decorated as aclassmethod():@classmethoddefsetUpClass(cls):...
SeeClass and Module Fixtures for more details.
New in version 2.7.
tearDownClass()¶A class method called after tests in an individual class have run.
tearDownClassis called with the class as the only argumentand must be decorated as aclassmethod():@classmethoddeftearDownClass(cls):...
SeeClass and Module Fixtures for more details.
New in version 2.7.
run(result=None)¶Run the test, collecting the result into the test result object passed asresult. Ifresult is omitted or
None, a temporary resultobject is created (by calling thedefaultTestResult()method) andused. The result object is not returned torun()’s caller.The same effect may be had by simply calling the
TestCaseinstance.
skipTest(reason)¶Calling this during a test method or
setUp()skips the currenttest. SeeSkipping tests and expected failures for more information.New in version 2.7.
debug()¶Run the test without collecting the result. This allows exceptions raisedby the test to be propagated to the caller, and can be used to supportrunning tests under a debugger.
The
TestCaseclass provides several assert methods to check for andreport failures. The following table lists the most commonly used methods(see the tables below for more assert methods):Method
Checks that
New in
a==ba!=bbool(x)isTruebool(x)isFalseaisb2.7
aisnotb2.7
xisNone2.7
xisnotNone2.7
ainb2.7
anotinb2.7
isinstance(a,b)2.7
notisinstance(a,b)2.7
All the assert methods (except
assertRaises(),assertRaisesRegexp())accept amsg argument that, if specified, is used as the error message onfailure (see alsolongMessage).assertEqual(first,second,msg=None)¶Test thatfirst andsecond are equal. If the values do not compareequal, the test will fail.
In addition, iffirst andsecond are the exact same type and one oflist, tuple, dict, set, frozenset or unicode or any type that a subclassregisters with
addTypeEqualityFunc()the type-specific equalityfunction will be called in order to generate a more useful defaulterror message (see also thelist of type-specific methods).Changed in version 2.7:Added the automatic calling of type-specific equality function.
assertNotEqual(first,second,msg=None)¶Test thatfirst andsecond are not equal. If the values do compareequal, the test will fail.
assertTrue(expr,msg=None)¶assertFalse(expr,msg=None)¶Test thatexpr is true (or false).
Note that this is equivalent to
bool(expr)isTrueand not toexprisTrue(useassertIs(expr,True)for the latter). This methodshould also be avoided when more specific methods are available (e.g.assertEqual(a,b)instead ofassertTrue(a==b)), because theyprovide a better error message in case of failure.
assertIs(first,second,msg=None)¶assertIsNot(first,second,msg=None)¶Test thatfirst andsecond evaluate (or don’t evaluate) to the same object.
New in version 2.7.
assertIsNone(expr,msg=None)¶assertIsNotNone(expr,msg=None)¶Test thatexpr is (or is not)
None.New in version 2.7.
assertIn(first,second,msg=None)¶assertNotIn(first,second,msg=None)¶Test thatfirst is (or is not) insecond.
New in version 2.7.
assertIsInstance(obj,cls,msg=None)¶assertNotIsInstance(obj,cls,msg=None)¶Test thatobj is (or is not) an instance ofcls (which can be aclass or a tuple of classes, as supported by
isinstance()).To check for the exact type, useassertIs(type(obj),cls).New in version 2.7.
It is also possible to check that exceptions and warnings are raised usingthe following methods:
Method
Checks that
New in
fun(*args,**kwds)raisesexcfun(*args,**kwds)raisesexcand the message matches regexr2.7
assertRaises(exception,callable,*args,**kwds)¶assertRaises(exception)Test that an exception is raised whencallable is called with anypositional or keyword arguments that are also passed to
assertRaises(). The test passes ifexception is raised, is anerror if another exception is raised, or fails if no exception is raised.To catch any of a group of exceptions, a tuple containing the exceptionclasses may be passed asexception.If only theexception argument is given, returns a context manager sothat the code under test can be written inline rather than as a function:
withself.assertRaises(SomeException):do_something()
The context manager will store the caught exception object in its
exceptionattribute. This can be useful if the intentionis to perform additional checks on the exception raised:withself.assertRaises(SomeException)ascm:do_something()the_exception=cm.exceptionself.assertEqual(the_exception.error_code,3)
Changed in version 2.7:Added the ability to use
assertRaises()as a context manager.
assertRaisesRegexp(exception,regexp,callable,*args,**kwds)¶assertRaisesRegexp(exception,regexp)Like
assertRaises()but also tests thatregexp matcheson the string representation of the raised exception.regexp may bea regular expression object or a string containing a regular expressionsuitable for use byre.search(). Examples:self.assertRaisesRegexp(ValueError,"invalid literal for.*XYZ'$",int,'XYZ')
or:
withself.assertRaisesRegexp(ValueError,'literal'):int('XYZ')
New in version 2.7.
There are also other methods used to perform more specific checks, such as:
Method
Checks that
New in
round(a-b,7)==0round(a-b,7)!=0a>b2.7
a>=b2.7
a<b2.7
a<=b2.7
r.search(s)2.7
notr.search(s)2.7
sorted(a) == sorted(b) andworks with unhashable objs
2.7
all the key/value pairsina exist inb
2.7
assertAlmostEqual(first,second,places=7,msg=None,delta=None)¶assertNotAlmostEqual(first,second,places=7,msg=None,delta=None)¶Test thatfirst andsecond are approximately (or not approximately)equal by computing the difference, rounding to the given number ofdecimalplaces (default 7), and comparing to zero. Note that thesemethods round the values to the given number ofdecimal places (i.e.like the
round()function) and notsignificant digits.Ifdelta is supplied instead ofplaces then the differencebetweenfirst andsecond must be less or equal to (or greater than)delta.
Supplying bothdelta andplaces raises a
TypeError.Changed in version 2.7:
assertAlmostEqual()automatically considers almost equal objectsthat compare equal.assertNotAlmostEqual()automatically failsif the objects compare equal. Added thedelta keyword argument.
assertGreater(first,second,msg=None)¶assertGreaterEqual(first,second,msg=None)¶assertLess(first,second,msg=None)¶assertLessEqual(first,second,msg=None)¶Test thatfirst is respectively >, >=, < or <= thansecond dependingon the method name. If not, the test will fail:
>>>self.assertGreaterEqual(3,4)AssertionError: "3" unexpectedly not greater than or equal to "4"
New in version 2.7.
assertRegexpMatches(text,regexp,msg=None)¶Test that aregexp search matchestext. In caseof failure, the error message will include the pattern and thetext (orthe pattern and the part oftext that unexpectedly matched).regexpmay be a regular expression object or a string containing a regularexpression suitable for use by
re.search().New in version 2.7.
assertNotRegexpMatches(text,regexp,msg=None)¶Verifies that aregexp search does not matchtext. Fails with an errormessage including the pattern and the part oftext that matches.regexpmay be a regular expression object or a string containing a regularexpression suitable for use by
re.search().New in version 2.7.
assertItemsEqual(actual,expected,msg=None)¶Test that sequenceexpected contains the same elements asactual,regardless of their order. When they don’t, an error message listing thedifferences between the sequences will be generated.
Duplicate elements arenot ignored when comparingactual andexpected. It verifies if each element has the same count in bothsequences. It is the equivalent of
assertEqual(sorted(expected),sorted(actual))but it works with sequences of unhashable objects aswell.In Python 3, this method is named
assertCountEqual.New in version 2.7.
assertDictContainsSubset(expected,actual,msg=None)¶Tests whether the key/value pairs in dictionaryactual are asuperset of those inexpected. If not, an error message listingthe missing keys and mismatched values is generated.
New in version 2.7.
Deprecated since version 3.2.
The
assertEqual()method dispatches the equality check for objects ofthe same type to different type-specific methods. These methods are alreadyimplemented for most of the built-in types, but it’s also possible toregister new methods usingaddTypeEqualityFunc():addTypeEqualityFunc(typeobj,function)¶Registers a type-specific method called by
assertEqual()to checkif two objects of exactly the sametypeobj (not subclasses) compareequal.function must take two positional arguments and a third msg=Nonekeyword argument just asassertEqual()does. It must raiseself.failureException(msg)when inequalitybetween the first two parameters is detected – possibly providing usefulinformation and explaining the inequalities in details in the errormessage.New in version 2.7.
The list of type-specific methods automatically used by
assertEqual()are summarized in the following table. Notethat it’s usually not necessary to invoke these methods directly.Method
Used to compare
New in
strings
2.7
sequences
2.7
lists
2.7
tuples
2.7
sets or frozensets
2.7
dicts
2.7
assertMultiLineEqual(first,second,msg=None)¶Test that the multiline stringfirst is equal to the stringsecond.When not equal a diff of the two strings highlighting the differenceswill be included in the error message. This method is used by defaultwhen comparing Unicode strings with
assertEqual().New in version 2.7.
assertSequenceEqual(seq1,seq2,msg=None,seq_type=None)¶Tests that two sequences are equal. If aseq_type is supplied, bothseq1 andseq2 must be instances ofseq_type or a failure willbe raised. If the sequences are different an error message isconstructed that shows the difference between the two.
This method is not called directly by
assertEqual(), butit’s used to implementassertListEqual()andassertTupleEqual().New in version 2.7.
assertListEqual(list1,list2,msg=None)¶assertTupleEqual(tuple1,tuple2,msg=None)¶Tests that two lists or tuples are equal. If not, an error message isconstructed that shows only the differences between the two. An erroris also raised if either of the parameters are of the wrong type.These methods are used by default when comparing lists or tuples with
assertEqual().New in version 2.7.
assertSetEqual(set1,set2,msg=None)¶Tests that two sets are equal. If not, an error message is constructedthat lists the differences between the sets. This method is used bydefault when comparing sets or frozensets with
assertEqual().Fails if either ofset1 orset2 does not have a
set.difference()method.New in version 2.7.
assertDictEqual(expected,actual,msg=None)¶Test that two dictionaries are equal. If not, an error message isconstructed that shows the differences in the dictionaries. Thismethod will be used by default to compare dictionaries incalls to
assertEqual().New in version 2.7.
Finally the
TestCaseprovides the following methods and attributes:fail(msg=None)¶Signals a test failure unconditionally, withmsg or
Noneforthe error message.
failureException¶This class attribute gives the exception raised by the test method. If atest framework needs to use a specialized exception, possibly to carryadditional information, it must subclass this exception in order to “playfair” with the framework. The initial value of this attribute is
AssertionError.
longMessage¶If set to
Truethen any explicit failure message you pass in to theassert methods will be appended to the end of thenormal failure message. The normal messages contain useful informationabout the objects involved, for example the message from assertEqualshows you the repr of the two unequal objects. Setting this attributetoTrueallows you to have a custom error message in addition to thenormal one.This attribute defaults to
False, meaning that a custom message passedto an assert method will silence the normal message.The class setting can be overridden in individual tests by assigning aninstance attribute to
TrueorFalsebefore calling the assert methods.New in version 2.7.
maxDiff¶This attribute controls the maximum length of diffs output by assertmethods that report diffs on failure. It defaults to 80*8 characters.Assert methods affected by this attribute are
assertSequenceEqual()(including all the sequence comparisonmethods that delegate to it),assertDictEqual()andassertMultiLineEqual().Setting
maxDifftoNonemeans that there is no maximum length ofdiffs.New in version 2.7.
Testing frameworks can use the following methods to collect information onthe test:
countTestCases()¶Return the number of tests represented by this test object. For
TestCaseinstances, this will always be1.
defaultTestResult()¶Return an instance of the test result class that should be used for thistest case class (if no other result instance is provided to the
run()method).For
TestCaseinstances, this will always be an instance ofTestResult; subclasses ofTestCaseshould override thisas necessary.
id()¶Return a string identifying the specific test case. This is usually thefull name of the test method, including the module and class name.
shortDescription()¶Returns a description of the test, or
Noneif no descriptionhas been provided. The default implementation of this methodreturns the first line of the test method’s docstring, if available,orNone.
addCleanup(function,*args,**kwargs)¶Add a function to be called after
tearDown()to cleanup resourcesused during the test. Functions will be called in reverse order to theorder they are added (LIFO). They are called with any arguments andkeyword arguments passed intoaddCleanup()when they areadded.If
setUp()fails, meaning thattearDown()is not called,then any cleanup functions added will still be called.New in version 2.7.
doCleanups()¶This method is called unconditionally after
tearDown(), oraftersetUp()ifsetUp()raises an exception.It is responsible for calling all the cleanup functions added by
addCleanup(). If you need cleanup functions to be calledprior totearDown()then you can calldoCleanups()yourself.doCleanups()pops methods off the stack of cleanupfunctions one at a time, so it can be called at any time.New in version 2.7.
- class
unittest.FunctionTestCase(testFunc,setUp=None,tearDown=None,description=None)¶ This class implements the portion of the
TestCaseinterface whichallows the test runner to drive the test, but does not provide the methodswhich test code can use to check and report errors. This is used to createtest cases using legacy test code, allowing it to be integrated into aunittest-based test framework.
25.3.7.1.1.Deprecated aliases¶
For historical reasons, some of theTestCase methods had one or morealiases that are now deprecated. The following table lists the correct namesalong with their deprecated aliases:
Method Name
Deprecated alias(es)
failUnlessEqual, assertEquals
failIfEqual
failUnless, assert_
failIf
failUnlessRaises
failUnlessAlmostEqual
failIfAlmostEqual
Deprecated since version 2.7:the aliases listed in the second column
25.3.7.2.Grouping tests¶
- class
unittest.TestSuite(tests=())¶ This class represents an aggregation of individual test cases and test suites.The class presents the interface needed by the test runner to allow it to be runas any other test case. Running a
TestSuiteinstance is the same asiterating over the suite, running each test individually.Iftests is given, it must be an iterable of individual test cases or othertest suites that will be used to build the suite initially. Additional methodsare provided to add test cases and suites to the collection later on.
TestSuiteobjects behave much likeTestCaseobjects, exceptthey do not actually implement a test. Instead, they are used to aggregatetests into groups of tests that should be run together. Some additionalmethods are available to add tests toTestSuiteinstances:addTests(tests)¶Add all the tests from an iterable of
TestCaseandTestSuiteinstances to this test suite.This is equivalent to iterating overtests, calling
addTest()foreach element.
TestSuiteshares the following methods withTestCase:run(result)¶Run the tests associated with this suite, collecting the result into thetest result object passed asresult. Note that unlike
TestCase.run(),TestSuite.run()requires the result object tobe passed in.
debug()¶Run the tests associated with this suite without collecting theresult. This allows exceptions raised by the test to be propagated to thecaller and can be used to support running tests under a debugger.
countTestCases()¶Return the number of tests represented by this test object, including allindividual tests and sub-suites.
__iter__()¶Tests grouped by a
TestSuiteare always accessed by iteration.Subclasses can lazily provide tests by overriding__iter__(). Notethat this method maybe called several times on a single suite(for example when counting tests or comparing for equality)so the tests returned must be the same for repeated iterations.Changed in version 2.7:In earlier versions the
TestSuiteaccessed tests directly ratherthan through iteration, so overriding__iter__()wasn’t sufficientfor providing tests.
In the typical usage of a
TestSuiteobject, therun()methodis invoked by aTestRunnerrather than by the end-user test harness.
25.3.7.3.Loading and running tests¶
- class
unittest.TestLoader¶ The
TestLoaderclass is used to create test suites from classes andmodules. Normally, there is no need to create an instance of this class; theunittestmodule provides an instance that can be shared asunittest.defaultTestLoader. Using a subclass or instance, however,allows customization of some configurable properties.TestLoaderobjects have the following methods:loadTestsFromTestCase(testCaseClass)¶Return a suite of all test cases contained in the
TestCase-derivedtestCaseClass.
loadTestsFromModule(module)¶Return a suite of all test cases contained in the given module. Thismethod searchesmodule for classes derived from
TestCaseandcreates an instance of the class for each test method defined for theclass.Note
While using a hierarchy of
TestCase-derived classes can beconvenient in sharing fixtures and helper functions, defining testmethods on base classes that are not intended to be instantiateddirectly does not play well with this method. Doing so, however, canbe useful when the fixtures are different and defined in subclasses.If a module provides a
load_testsfunction it will be called toload the tests. This allows modules to customize test loading.This is theload_tests protocol.Changed in version 2.7:Support for
load_testsadded.
loadTestsFromName(name,module=None)¶Return a suite of all test cases given a string specifier.
The specifiername is a “dotted name” that may resolve either to amodule, a test case class, a test method within a test case class, a
TestSuiteinstance, or a callable object which returns aTestCaseorTestSuiteinstance. These checks areapplied in the order listed here; that is, a method on a possible testcase class will be picked up as “a test method within a test case class”,rather than “a callable object”.For example, if you have a module
SampleTestscontaining aTestCase-derived classSampleTestCasewith three testmethods (test_one(),test_two(), andtest_three()), thespecifier'SampleTests.SampleTestCase'would cause this method toreturn a suite which will run all three test methods. Using the specifier'SampleTests.SampleTestCase.test_two'would cause it to return a testsuite which will run only thetest_two()test method. The specifiercan refer to modules and packages which have not been imported; they willbe imported as a side-effect.The method optionally resolvesname relative to the givenmodule.
loadTestsFromNames(names,module=None)¶Similar to
loadTestsFromName(), but takes a sequence of names ratherthan a single name. The return value is a test suite which supports allthe tests defined for each name.
getTestCaseNames(testCaseClass)¶Return a sorted sequence of method names found withintestCaseClass;this should be a subclass of
TestCase.
discover(start_dir,pattern='test*.py',top_level_dir=None)¶Find all the test modules by recursing into subdirectories from thespecified start directory, and return a TestSuite object containing them.Only test files that matchpattern will be loaded. (Using shell stylepattern matching.) Only module names that are importable (i.e. are validPython identifiers) will be loaded.
All test modules must be importable from the top level of the project. Ifthe start directory is not the top level directory then the top leveldirectory must be specified separately.
If importing a module fails, for example due to a syntax error, then thiswill be recorded as a single error and discovery will continue.
If a test package name (directory with
__init__.py) matches thepattern then the package will be checked for aload_testsfunction. If this exists then it will be called withloader,tests,pattern.If load_tests exists then discovery doesnot recurse into the package,
load_testsis responsible for loading all tests in the package.The pattern is deliberately not stored as a loader attribute so thatpackages can continue discovery themselves.top_level_dir is stored so
load_testsdoes not need to pass this argument in toloader.discover().start_dir can be a dotted module name as well as a directory.
New in version 2.7.
The following attributes of a
TestLoadercan be configured either bysubclassing or assignment on an instance:testMethodPrefix¶String giving the prefix of method names which will be interpreted as testmethods. The default value is
'test'.This affects
getTestCaseNames()and all theloadTestsFrom*()methods.
sortTestMethodsUsing¶Function to be used to compare method names when sorting them in
getTestCaseNames()and all theloadTestsFrom*()methods. Thedefault value is the built-incmp()function; the attribute can alsobe set toNoneto disable the sort.
- class
unittest.TestResult¶ This class is used to compile information about which tests have succeededand which have failed.
A
TestResultobject stores the results of a set of tests. TheTestCaseandTestSuiteclasses ensure that results areproperly recorded; test authors do not need to worry about recording theoutcome of tests.Testing frameworks built on top of
unittestmay want access to theTestResultobject generated by running a set of tests for reportingpurposes; aTestResultinstance is returned by theTestRunner.run()method for this purpose.TestResultinstances have the following attributes that will be ofinterest when inspecting the results of running a set of tests:errors¶A list containing 2-tuples of
TestCaseinstances and stringsholding formatted tracebacks. Each tuple represents a test which raised anunexpected exception.Changed in version 2.2:Contains formatted tracebacks instead of
sys.exc_info()results.
failures¶A list containing 2-tuples of
TestCaseinstances and stringsholding formatted tracebacks. Each tuple represents a test where a failurewas explicitly signalled using theTestCase.assert*()methods.Changed in version 2.2:Contains formatted tracebacks instead of
sys.exc_info()results.
skipped¶A list containing 2-tuples of
TestCaseinstances and stringsholding the reason for skipping the test.New in version 2.7.
expectedFailures¶A list containing 2-tuples of
TestCaseinstances and stringsholding formatted tracebacks. Each tuple represents an expected failureof the test case.
unexpectedSuccesses¶A list containing
TestCaseinstances that were marked as expectedfailures, but succeeded.
testsRun¶The total number of tests run so far.
buffer¶If set to true,
sys.stdoutandsys.stderrwill be buffered in betweenstartTest()andstopTest()being called. Collected output willonly be echoed onto the realsys.stdoutandsys.stderrif the testfails or errors. Any output is also attached to the failure / error message.New in version 2.7.
failfast¶If set to true
stop()will be called on the first failure or error,halting the test run.New in version 2.7.
wasSuccessful()¶Return
Trueif all tests run so far have passed, otherwise returnsFalse.
stop()¶This method can be called to signal that the set of tests being run shouldbe aborted by setting the
shouldStopattribute toTrue.TestRunnerobjects should respect this flag and return withoutrunning any additional tests.For example, this feature is used by the
TextTestRunnerclass tostop the test framework when the user signals an interrupt from thekeyboard. Interactive tools which provideTestRunnerimplementations can use this in a similar manner.
The following methods of the
TestResultclass are used to maintainthe internal data structures, and may be extended in subclasses to supportadditional reporting requirements. This is particularly useful in buildingtools which support interactive reporting while tests are being run.startTest(test)¶Called when the test casetest is about to be run.
stopTest(test)¶Called after the test casetest has been executed, regardless of theoutcome.
startTestRun()¶Called once before any tests are executed.
New in version 2.7.
stopTestRun()¶Called once after all tests are executed.
New in version 2.7.
addError(test,err)¶Called when the test casetest raises an unexpected exception.err is atuple of the form returned by
sys.exc_info():(type,value,traceback).The default implementation appends a tuple
(test,formatted_err)tothe instance’serrorsattribute, whereformatted_err is aformatted traceback derived fromerr.
addFailure(test,err)¶Called when the test casetest signals a failure.err is a tuple ofthe form returned by
sys.exc_info():(type,value,traceback).The default implementation appends a tuple
(test,formatted_err)tothe instance’sfailuresattribute, whereformatted_err is aformatted traceback derived fromerr.
addSuccess(test)¶Called when the test casetest succeeds.
The default implementation does nothing.
addSkip(test,reason)¶Called when the test casetest is skipped.reason is the reason thetest gave for skipping.
The default implementation appends a tuple
(test,reason)to theinstance’sskippedattribute.
addExpectedFailure(test,err)¶Called when the test casetest fails, but was marked with the
expectedFailure()decorator.The default implementation appends a tuple
(test,formatted_err)tothe instance’sexpectedFailuresattribute, whereformatted_erris a formatted traceback derived fromerr.
addUnexpectedSuccess(test)¶Called when the test casetest was marked with the
expectedFailure()decorator, but succeeded.The default implementation appends the test to the instance’s
unexpectedSuccessesattribute.
- class
unittest.TextTestResult(stream,descriptions,verbosity)¶ A concrete implementation of
TestResultused by theTextTestRunner.New in version 2.7:This class was previously named
_TextTestResult. The old name stillexists as an alias but is deprecated.
unittest.defaultTestLoader¶Instance of the
TestLoaderclass intended to be shared. If nocustomization of theTestLoaderis needed, this instance can be usedinstead of repeatedly creating new instances.
- class
unittest.TextTestRunner(stream=sys.stderr,descriptions=True,verbosity=1,failfast=False,buffer=False,resultclass=None)¶ A basic test runner implementation which prints results on standard error. Ithas a few configurable parameters, but is essentially very simple. Graphicalapplications which run test suites should provide alternate implementations.
_makeResult()¶This method returns the instance of
TestResultused byrun().It is not intended to be called directly, but can be overridden insubclasses to provide a customTestResult._makeResult()instantiates the class or callable passed in theTextTestRunnerconstructor as theresultclassargument. Itdefaults toTextTestResultif noresultclassis provided.The result class is instantiated with the following arguments:stream,descriptions,verbosity
unittest.main([module[,defaultTest[,argv[,testRunner[,testLoader[,exit[,verbosity[,failfast[,catchbreak[,buffer]]]]]]]]]])¶A command-line program that loads a set of tests frommodule and runs them;this is primarily for making test modules conveniently executable.The simplest use for this function is to include the following line at theend of a test script:
if__name__=='__main__':unittest.main()
You can run tests with more detailed information by passing in the verbosityargument:
if__name__=='__main__':unittest.main(verbosity=2)
ThedefaultTest argument is the name of the test to run if no test namesare specified viaargv. If not specified or
Noneand no test names areprovided viaargv, all tests found inmodule are run.Theargv argument can be a list of options passed to the program, with thefirst element being the program name. If not specified or
None,the values ofsys.argvare used.ThetestRunner argument can either be a test runner class or an alreadycreated instance of it. By default
maincallssys.exit()withan exit code indicating success or failure of the tests run.ThetestLoader argument has to be a
TestLoaderinstance,and defaults todefaultTestLoader.mainsupports being used from the interactive interpreter by passing in theargumentexit=False. This displays the result on standard output withoutcallingsys.exit():>>>fromunittestimportmain>>>main(module='test_module',exit=False)
Thefailfast,catchbreak andbuffer parameters have the sameeffect as the same-namecommand-line options.
Calling
mainactually returns an instance of theTestProgramclass.This stores the result of the tests run as theresultattribute.Changed in version 2.7:Theexit,verbosity,failfast,catchbreak andbufferparameters were added.
25.3.7.3.1.load_tests Protocol¶
New in version 2.7.
Modules or packages can customize how tests are loaded from them during normaltest runs or test discovery by implementing a function calledload_tests.
If a test module definesload_tests it will be called byTestLoader.loadTestsFromModule() with the following arguments:
load_tests(loader,standard_tests,None)
It should return aTestSuite.
loader is the instance ofTestLoader doing the loading.standard_tests are the tests that would be loaded by default from themodule. It is common for test modules to only want to add or remove testsfrom the standard set of tests.The third argument is used when loading packages as part of test discovery.
A typicalload_tests function that loads tests from a specific set ofTestCase classes may look like:
test_cases=(TestCase1,TestCase2,TestCase3)defload_tests(loader,tests,pattern):suite=TestSuite()fortest_classintest_cases:tests=loader.loadTestsFromTestCase(test_class)suite.addTests(tests)returnsuite
If discovery is started, either from the command line or by callingTestLoader.discover(), with a pattern that matches a packagename then the package__init__.py will be checked forload_tests.
Note
The default pattern is'test*.py'. This matches all Python filesthat start with'test' butwon’t match any test directories.
A pattern like'test*' will match test packages as well asmodules.
If the package__init__.py definesload_tests then it will becalled and discovery not continued into the package.load_testsis called with the following arguments:
load_tests(loader,standard_tests,pattern)
This should return aTestSuite representing all the testsfrom the package. (standard_tests will only contain testscollected from__init__.py.)
Because the pattern is passed intoload_tests the package is free tocontinue (and potentially modify) test discovery. A ‘do nothing’load_tests function for a test package would look like:
defload_tests(loader,standard_tests,pattern):# top level directory cached on loader instancethis_dir=os.path.dirname(__file__)package_tests=loader.discover(start_dir=this_dir,pattern=pattern)standard_tests.addTests(package_tests)returnstandard_tests
25.3.8.Class and Module Fixtures¶
Class and module level fixtures are implemented inTestSuite. Whenthe test suite encounters a test from a new class thentearDownClass()from the previous class (if there is one) is called, followed bysetUpClass() from the new class.
Similarly if a test is from a different module from the previous test thentearDownModule from the previous module is run, followed bysetUpModule from the new module.
After all the tests have run the finaltearDownClass andtearDownModule are run.
Note that shared fixtures do not play well with [potential] features like testparallelization and they break test isolation. They should be used with care.
The default ordering of tests created by the unittest test loaders is to groupall tests from the same modules and classes together. This will lead tosetUpClass /setUpModule (etc) being called exactly once per class andmodule. If you randomize the order, so that tests from different modules andclasses are adjacent to each other, then these shared fixture functions may becalled multiple times in a single test run.
Shared fixtures are not intended to work with suites with non-standardordering. ABaseTestSuite still exists for frameworks that don’t want tosupport shared fixtures.
If there are any exceptions raised during one of the shared fixture functionsthe test is reported as an error. Because there is no corresponding testinstance an_ErrorHolder object (that has the same interface as aTestCase) is created to represent the error. If you are just usingthe standard unittest test runner then this detail doesn’t matter, but if youare a framework author it may be relevant.
25.3.8.1.setUpClass and tearDownClass¶
These must be implemented as class methods:
importunittestclassTest(unittest.TestCase):@classmethoddefsetUpClass(cls):cls._connection=createExpensiveConnectionObject()@classmethoddeftearDownClass(cls):cls._connection.destroy()
If you want thesetUpClass andtearDownClass on base classes calledthen you must call up to them yourself. The implementations inTestCase are empty.
If an exception is raised during asetUpClass then the tests in the classare not run and thetearDownClass is not run. Skipped classes will nothavesetUpClass ortearDownClass run. If the exception is aSkipTest exception then the class will be reported as having been skippedinstead of as an error.
25.3.8.2.setUpModule and tearDownModule¶
These should be implemented as functions:
defsetUpModule():createConnection()deftearDownModule():closeConnection()
If an exception is raised in asetUpModule then none of the tests in themodule will be run and thetearDownModule will not be run. If the exception is aSkipTest exception then the module will be reported as having been skippedinstead of as an error.
25.3.9.Signal Handling¶
The-c/--catch command-line option to unittest,along with thecatchbreak parameter tounittest.main(), providemore friendly handling of control-C during a test run. With catch breakbehavior enabled control-C will allow the currently running test to complete,and the test run will then end and report all the results so far. A secondcontrol-c will raise aKeyboardInterrupt in the usual way.
The control-c handling signal handler attempts to remain compatible with code ortests that install their ownsignal.SIGINT handler. If theunittesthandler is called butisn’t the installedsignal.SIGINT handler,i.e. it has been replaced by the system under test and delegated to, then itcalls the default handler. This will normally be the expected behavior by codethat replaces an installed handler and delegates to it. For individual teststhat needunittest control-c handling disabled theremoveHandler()decorator can be used.
There are a few utility functions for framework authors to enable control-chandling functionality within test frameworks.
unittest.installHandler()¶Install the control-c handler. When a
signal.SIGINTis received(usually in response to the user pressing control-c) all registered resultshavestop()called.New in version 2.7.
unittest.registerResult(result)¶Register a
TestResultobject for control-c handling. Registering aresult stores a weak reference to it, so it doesn’t prevent the result frombeing garbage collected.Registering a
TestResultobject has no side-effects if control-chandling is not enabled, so test frameworks can unconditionally registerall results they create independently of whether or not handling is enabled.New in version 2.7.
unittest.removeResult(result)¶Remove a registered result. Once a result has been removed then
stop()will no longer be called on that result object inresponse to a control-c.New in version 2.7.
unittest.removeHandler(function=None)¶When called without arguments this function removes the control-c handlerif it has been installed. This function can also be used as a test decoratorto temporarily remove the handler while the test is being executed:
@unittest.removeHandlerdeftest_signal_handling(self):...
New in version 2.7.
