The unittest unit testing framework was originally inspired by JUnitand has a similar flavor as major unit testing frameworks in otherlanguages. It supports test automation, sharing of setup and shutdown codefor tests, aggregation of tests into collections, and independence of thetests from the reporting framework.
The Test sub download
A test fixture represents the preparation needed to perform one or moretests, and any associated cleanup actions. This may involve, for example,creating temporary or proxy databases, directories, or starting a serverprocess.
A test 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 script Tools/unittestgui/unittestgui.py in the Python source distribution isa GUI tool for test discovery and execution. This is intended largely for ease of usefor those new to unit testing. For production environments it isrecommended that tests be driven by a continuous integration system such asBuildbot, Jenkins,GitHub Actions, orAppVeyor.
A testcase is created by subclassing unittest.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 to assertEqual() to check for anexpected result; assertTrue() or assertFalse()to verify a condition; or assertRaises() 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.
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:
The above examples show the most commonly used unittest features whichare sufficient to meet many everyday testing needs. The remainder of thedocumentation explores the full feature set from first principles.
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.
Unittest supports simple test discovery. In order to be compatible with testdiscovery, all of the test files must be modules orpackages importable from the top-level directory ofthe project (this means that their filenames must be valid identifiers).
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.
Test discovery loads tests by importing them. Once test discovery has foundall the test files from the start directory you specify it turns the pathsinto package names to import. For example foo/bar/baz.py will beimported as foo.bar.baz.
If you have a package installed globally and attempt test discovery ona different copy of the package then the import could happen from thewrong place. If this happens test discovery will warn you and exit.
Changed in version 3.4: Test discovery supports namespace packagesfor the start directory. Note that you need to specify the top leveldirectory too (e.g.python -m unittest discover -s root/namespace -t root).
Changed in version 3.11: Python 3.11 dropped the namespace packagessupport. It has been broken since Python 3.7. Start directory andsubdirectories containing tests must be regular package that have__init__.py file.
Note that in order to test something, we use one of the assert*()methods provided by the TestCase base class. If the test fails, anexception will be raised with an explanatory message, and unittestwill identify the test case as a failure. Any other exceptions will betreated as errors.
Tests can be numerous, and their set-up can be repetitive. Luckily, wecan factor out set-up code by implementing a method calledsetUp(), which the testing framework will automaticallycall for every single test we run:
Such a working environment for the testing code is called atest fixture. A new TestCase instance is created as a uniquetest fixture used to execute each individual test method. ThussetUp(), tearDown(), and __init__()will be called once per test.
You can place the definitions of test cases and test suites in the same modulesas the code they are to test (such as widget.py), but there are severaladvantages to placing the test code in a separate module, such astest_widget.py:
Even though FunctionTestCase can be used to quickly convert anexisting test base over to a unittest-based system, this approach isnot recommended. Taking the time to set up proper TestCasesubclasses will make future test refactorings infinitely easier.
In some cases, the existing tests may have been written using the doctestmodule. If so, doctest provides a DocTestSuite class that canautomatically build unittest.TestSuite instances from the existingdoctest-based tests.
Mark the test as an expected failure or error. If the test fails or errorsin the test function itself (rather than in one of the test fixturemethods) then it will be considered a success. If the test passes, it willbe considered a failure.
Skipped tests will not have setUp() or tearDown() run around them.Skipped classes will not have setUpClass() or tearDownClass() run.Skipped modules will not have setUpModule() or tearDownModule() run.
Instances of the TestCase class represent the logical test unitsin the unittest universe. 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 thetests, and methods that the test code can use to check for and report variouskinds of failure.
TestCase instances 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.
Method called to prepare the test fixture. This is called immediatelybefore calling the test method; other than AssertionError or SkipTest,any exception raised by this method will be considered an error rather thana test failure. The default implementation does nothing.
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 thanAssertionError or SkipTest, 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 ifthe setUp() succeeds, regardless of the outcome of the test method.The default implementation does nothing.
Return a context manager which executes the enclosed code block as asubtest. msg and params are optional, arbitrary values which aredisplayed whenever a subtest fails, allowing you to identify themclearly.
Test that an exception is raised when callable is called with anypositional or keyword arguments that are also passed toassertRaises(). The test passes if exception 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 as exception.
Like assertRaises() but also tests that regex matcheson the string representation of the raised exception. regex may bea regular expression object or a string containing a regular expressionsuitable for use by re.search(). Examples:
Like assertWarns() but also tests that regex matches on themessage of the triggered warning. regex may be a regular expressionobject or a string containing a regular expression suitable for useby re.search(). Example:
Changed in version 3.1: In 3.1 this was changed to add the test name to the short descriptioneven in the presence of a docstring. This caused compatibility issueswith unittest extensions and adding the test name was moved to theTextTestResult in Python 3.2.
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). Theyare called with any arguments and keyword arguments passed intoaddCleanup() when they are added.
Add a function to be called after tearDownClass() to cleanupresources used during the test class. Functions will be called in reverseorder to the order they are added (LIFO).They are called with any arguments and keyword arguments passed intoaddClassCleanup() when they are added.
Method called to prepare the test fixture. This is called after setUp().This is called immediately before calling the test method; other thanAssertionError or SkipTest, any exception raised by this methodwill be considered an error rather than a test failure. The default implementationdoes nothing.
Method called immediately after the test method has been called and theresult recorded. This is called before tearDown(). This is called even ifthe test method raised an exception, so the implementation in subclasses may needto be particularly careful about checking internal state. Any exception, other thanAssertionError or SkipTest, 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 ifthe asyncSetUp() succeeds, regardless of the outcome of the test method.The default implementation does nothing.
This class implements the portion of the TestCase interface 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. 2ff7e9595c
Comments