summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Funittest.html
diff options
context:
space:
mode:
authorCraig Jennings <c@cjennings.net>2024-04-07 13:41:34 -0500
committerCraig Jennings <c@cjennings.net>2024-04-07 13:41:34 -0500
commit754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 (patch)
treef1190704f78f04a2b0b4c977d20fe96a828377f1 /devdocs/python~3.12/library%2Funittest.html
new repository
Diffstat (limited to 'devdocs/python~3.12/library%2Funittest.html')
-rw-r--r--devdocs/python~3.12/library%2Funittest.html761
1 files changed, 761 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Funittest.html b/devdocs/python~3.12/library%2Funittest.html
new file mode 100644
index 00000000..e21aa765
--- /dev/null
+++ b/devdocs/python~3.12/library%2Funittest.html
@@ -0,0 +1,761 @@
+ <span id="unittest-unit-testing-framework"></span><h1>unittest — Unit testing framework</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/unittest/__init__.py">Lib/unittest/__init__.py</a></p> <p>(If you are already familiar with the basic concepts of testing, you might want to skip to <a class="reference internal" href="#assert-methods"><span class="std std-ref">the list of assert methods</span></a>.)</p> <p>The <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.</p> <p>To achieve this, <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> supports some important concepts in an object-oriented way:</p> <dl class="simple"> <dt>test fixture</dt>
+<dd>
+<p>A <em class="dfn">test fixture</em> represents the preparation needed to perform one or more tests, and any associated cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process.</p> </dd> <dt>test case</dt>
+<dd>
+<p>A <em class="dfn">test case</em> is the individual unit of testing. It checks for a specific response to a particular set of inputs. <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> provides a base class, <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a>, which may be used to create new test cases.</p> </dd> <dt>test suite</dt>
+<dd>
+<p>A <em class="dfn">test suite</em> is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.</p> </dd> <dt>test runner</dt>
+<dd>
+<p>A <em class="dfn">test runner</em> is a component which orchestrates the execution of tests and 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 of executing the tests.</p> </dd> </dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
+<code>Module</code> <a class="reference internal" href="doctest#module-doctest" title="doctest: Test pieces of code within docstrings."><code>doctest</code></a>
+</dt>
+<dd>
+<p>Another test-support module with a very different flavor.</p> </dd> <dt><a class="reference external" href="https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm">Simple Smalltalk Testing: With Patterns</a></dt>
+<dd>
+<p>Kent Beck’s original paper on testing frameworks using the pattern shared by <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a>.</p> </dd> <dt><a class="reference external" href="https://docs.pytest.org/">pytest</a></dt>
+<dd>
+<p>Third-party unittest framework with a lighter-weight syntax for writing tests. For example, <code>assert func(10) == 42</code>.</p> </dd> <dt><a class="reference external" href="https://wiki.python.org/moin/PythonTestingToolsTaxonomy">The Python Testing Tools Taxonomy</a></dt>
+<dd>
+<p>An extensive list of Python testing tools including functional testing frameworks and mock object libraries.</p> </dd> <dt><a class="reference external" href="http://lists.idyll.org/listinfo/testing-in-python">Testing in Python Mailing List</a></dt>
+<dd>
+<p>A special-interest-group for discussion of testing, and testing tools, in Python.</p> </dd> </dl> <p>The script <code>Tools/unittestgui/unittestgui.py</code> in the Python source distribution is a GUI tool for test discovery and execution. This is intended largely for ease of use for those new to unit testing. For production environments it is recommended that tests be driven by a continuous integration system such as <a class="reference external" href="https://buildbot.net/">Buildbot</a>, <a class="reference external" href="https://www.jenkins.io/">Jenkins</a>, <a class="reference external" href="https://github.com/features/actions">GitHub Actions</a>, or <a class="reference external" href="https://www.appveyor.com/">AppVeyor</a>.</p> </div> <section id="basic-example"> <span id="unittest-minimal-example"></span><h2>Basic example</h2> <p>The <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users.</p> <p>Here is a short script to test three string methods:</p> <pre data-language="python">import unittest
+
+class TestStringMethods(unittest.TestCase):
+
+ def test_upper(self):
+ self.assertEqual('foo'.upper(), 'FOO')
+
+ def test_isupper(self):
+ self.assertTrue('FOO'.isupper())
+ self.assertFalse('Foo'.isupper())
+
+ def test_split(self):
+ s = 'hello world'
+ self.assertEqual(s.split(), ['hello', 'world'])
+ # check that s.split fails when the separator is not a string
+ with self.assertRaises(TypeError):
+ s.split(2)
+
+if __name__ == '__main__':
+ unittest.main()
+</pre> <p>A testcase is created by subclassing <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>unittest.TestCase</code></a>. The three individual tests are defined with methods whose names start with the letters <code>test</code>. This naming convention informs the test runner about which methods represent tests.</p> <p>The crux of each test is a call to <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual()</code></a> to check for an expected result; <a class="reference internal" href="#unittest.TestCase.assertTrue" title="unittest.TestCase.assertTrue"><code>assertTrue()</code></a> or <a class="reference internal" href="#unittest.TestCase.assertFalse" title="unittest.TestCase.assertFalse"><code>assertFalse()</code></a> to verify a condition; or <a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code>assertRaises()</code></a> to verify that a specific exception gets raised. These methods are used instead of the <a class="reference internal" href="../reference/simple_stmts#assert"><code>assert</code></a> statement so the test runner can accumulate all test results and produce a report.</p> <p>The <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a> and <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code>tearDown()</code></a> methods allow you to define instructions that will be executed before and after each test method. They are covered in more detail in the section <a class="reference internal" href="#organizing-tests"><span class="std std-ref">Organizing test code</span></a>.</p> <p>The final block shows a simple way to run the tests. <a class="reference internal" href="#unittest.main" title="unittest.main"><code>unittest.main()</code></a> provides a command-line interface to the test script. When run from the command line, the above script produces an output that looks like this:</p> <pre data-language="python">...
+----------------------------------------------------------------------
+Ran 3 tests in 0.000s
+
+OK
+</pre> <p>Passing the <code>-v</code> option to your test script will instruct <a class="reference internal" href="#unittest.main" title="unittest.main"><code>unittest.main()</code></a> to enable a higher level of verbosity, and produce the following output:</p> <pre data-language="python">test_isupper (__main__.TestStringMethods.test_isupper) ... ok
+test_split (__main__.TestStringMethods.test_split) ... ok
+test_upper (__main__.TestStringMethods.test_upper) ... ok
+
+----------------------------------------------------------------------
+Ran 3 tests in 0.001s
+
+OK
+</pre> <p>The above examples show the most commonly used <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> features which are sufficient to meet many everyday testing needs. The remainder of the documentation explores the full feature set from first principles.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The behavior of returning a value from a test method (other than the default <code>None</code> value), is now deprecated.</p> </div> </section> <section id="command-line-interface"> <span id="unittest-command-line-interface"></span><h2>Command-Line Interface</h2> <p>The unittest module can be used from the command line to run tests from modules, classes or even individual test methods:</p> <pre data-language="python">python -m unittest test_module1 test_module2
+python -m unittest test_module.TestClass
+python -m unittest test_module.TestClass.test_method
+</pre> <p>You can pass in a list with any combination of module names, and fully qualified class or method names.</p> <p>Test modules can be specified by file path as well:</p> <pre data-language="python">python -m unittest tests/test_something.py
+</pre> <p>This allows you to use the shell filename completion to specify the test module. The file specified must still be importable as a module. The path is converted to a module name by removing the ‘.py’ and converting path separators into ‘.’. If you want to execute a test file that isn’t importable as a module you should execute the file directly instead.</p> <p>You can run tests with more detail (higher verbosity) by passing in the -v flag:</p> <pre data-language="python">python -m unittest -v test_module
+</pre> <p>When executed without arguments <a class="reference internal" href="#unittest-test-discovery"><span class="std std-ref">Test Discovery</span></a> is started:</p> <pre data-language="python">python -m unittest
+</pre> <p>For a list of all the command-line options:</p> <pre data-language="python">python -m unittest -h
+</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>In earlier versions it was only possible to run individual test methods and not modules or classes.</p> </div> <section id="command-line-options"> <h3>Command-line options</h3> <p><strong class="program">unittest</strong> supports these command-line options:</p> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-unittest-b">
+<code>-b, --buffer</code> </dt> <dd>
+<p>The standard output and standard error streams are buffered during the test run. Output during a passing test is discarded. Output is echoed normally on test fail or error and is added to the failure messages.</p> </dd>
+</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-unittest-c">
+<code>-c, --catch</code> </dt> <dd>
+<p><kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd></kbd> during the test run waits for the current test to end and then reports all the results so far. A second <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd></kbd> raises the normal <a class="reference internal" href="exceptions#KeyboardInterrupt" title="KeyboardInterrupt"><code>KeyboardInterrupt</code></a> exception.</p> <p>See <a class="reference internal" href="#signal-handling">Signal Handling</a> for the functions that provide this functionality.</p> </dd>
+</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-unittest-f">
+<code>-f, --failfast</code> </dt> <dd>
+<p>Stop the test run on the first error or failure.</p> </dd>
+</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-unittest-k">
+<code>-k</code> </dt> <dd>
+<p>Only run test methods and classes that match the pattern or substring. This option may be used multiple times, in which case all test cases that match any of the given patterns are included.</p> <p>Patterns that contain a wildcard character (<code>*</code>) are matched against the test name using <a class="reference internal" href="fnmatch#fnmatch.fnmatchcase" title="fnmatch.fnmatchcase"><code>fnmatch.fnmatchcase()</code></a>; otherwise simple case-sensitive substring matching is used.</p> <p>Patterns are matched against the fully qualified test method name as imported by the test loader.</p> <p>For example, <code>-k foo</code> matches <code>foo_tests.SomeTest.test_something</code>, <code>bar_tests.SomeTest.test_foo</code>, but not <code>bar_tests.FooTest.test_something</code>.</p> </dd>
+</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-unittest-locals">
+<code>--locals</code> </dt> <dd>
+<p>Show local variables in tracebacks.</p> </dd>
+</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-unittest-durations">
+<code>--durations N</code> </dt> <dd>
+<p>Show the N slowest test cases (N=0 for all).</p> </dd>
+</dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span>The command-line options <code>-b</code>, <code>-c</code> and <code>-f</code> were added.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5: </span>The command-line option <code>--locals</code>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7: </span>The command-line option <code>-k</code>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12: </span>The command-line option <code>--durations</code>.</p> </div> <p>The command line can also be used for test discovery, for running all of the tests in a project or just a subset.</p> </section> </section> <section id="test-discovery"> <span id="unittest-test-discovery"></span><h2>Test Discovery</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <p>Unittest supports simple test discovery. In order to be compatible with test discovery, all of the test files must be <a class="reference internal" href="../tutorial/modules#tut-modules"><span class="std std-ref">modules</span></a> or <a class="reference internal" href="../tutorial/modules#tut-packages"><span class="std std-ref">packages</span></a> importable from the top-level directory of the project (this means that their filenames must be valid <a class="reference internal" href="../reference/lexical_analysis#identifiers"><span class="std std-ref">identifiers</span></a>).</p> <p>Test discovery is implemented in <a class="reference internal" href="#unittest.TestLoader.discover" title="unittest.TestLoader.discover"><code>TestLoader.discover()</code></a>, but can also be used from the command line. The basic command-line usage is:</p> <pre data-language="python">cd project_directory
+python -m unittest discover
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>As a shortcut, <code>python -m unittest</code> is the equivalent of <code>python -m unittest discover</code>. If you want to pass arguments to test discovery the <code>discover</code> sub-command must be used explicitly.</p> </div> <p>The <code>discover</code> sub-command has the following options:</p> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-unittest-discover-v">
+<code>-v, --verbose</code> </dt> <dd>
+<p>Verbose output</p> </dd>
+</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-unittest-discover-s">
+<code>-s, --start-directory directory</code> </dt> <dd>
+<p>Directory to start discovery (<code>.</code> default)</p> </dd>
+</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-unittest-discover-p">
+<code>-p, --pattern pattern</code> </dt> <dd>
+<p>Pattern to match test files (<code>test*.py</code> default)</p> </dd>
+</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-unittest-discover-t">
+<code>-t, --top-level-directory directory</code> </dt> <dd>
+<p>Top level directory of project (defaults to start directory)</p> </dd>
+</dl> <p>The <a class="reference internal" href="#cmdoption-unittest-discover-s"><code>-s</code></a>, <a class="reference internal" href="#cmdoption-unittest-discover-p"><code>-p</code></a>, and <a class="reference internal" href="#cmdoption-unittest-discover-t"><code>-t</code></a> options can be passed in as positional arguments in that order. The following two command lines are equivalent:</p> <pre data-language="python">python -m unittest discover -s project_directory -p "*_test.py"
+python -m unittest discover project_directory "*_test.py"
+</pre> <p>As well as being a path it is possible to pass a package name, for example <code>myproject.subpackage.test</code>, as the start directory. The package name you supply will then be imported and its location on the filesystem will be used as the start directory.</p> <div class="admonition caution"> <p class="admonition-title">Caution</p> <p>Test discovery loads tests by importing them. Once test discovery has found all the test files from the start directory you specify it turns the paths into package names to import. For example <code>foo/bar/baz.py</code> will be imported as <code>foo.bar.baz</code>.</p> <p>If you have a package installed globally and attempt test discovery on a different copy of the package then the import <em>could</em> happen from the wrong place. If this happens test discovery will warn you and exit.</p> <p>If you supply the start directory as a package name rather than a path to a directory then discover assumes that whichever location it imports from is the location you intended, so you will not get the warning.</p> </div> <p>Test modules and packages can customize test loading and discovery by through the <a class="reference internal" href="#id1">load_tests protocol</a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Test discovery supports <a class="reference internal" href="../glossary#term-namespace-package"><span class="xref std std-term">namespace packages</span></a> for the start directory. Note that you need to specify the top level directory too (e.g. <code>python -m unittest discover -s root/namespace -t root</code>).</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> dropped the <a class="reference internal" href="../glossary#term-namespace-package"><span class="xref std std-term">namespace packages</span></a> support in Python 3.11. It has been broken since Python 3.7. Start directory and subdirectories containing tests must be regular package that have <code>__init__.py</code> file.</p> <p>Directories containing start directory still can be a namespace package. In this case, you need to specify start directory as dotted package name, and target directory explicitly. For example:</p> <pre data-language="python"># proj/ &lt;-- current directory
+# namespace/
+# mypkg/
+# __init__.py
+# test_mypkg.py
+
+python -m unittest discover -s namespace.mypkg -t .
+</pre> </div> </section> <section id="organizing-test-code"> <span id="organizing-tests"></span><h2>Organizing test code</h2> <p>The basic building blocks of unit testing are <em class="dfn">test cases</em> — single scenarios that must be set up and checked for correctness. In <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a>, test cases are represented by <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>unittest.TestCase</code></a> instances. To make your own test cases you must write subclasses of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> or use <a class="reference internal" href="#unittest.FunctionTestCase" title="unittest.FunctionTestCase"><code>FunctionTestCase</code></a>.</p> <p>The testing code of a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instance should be entirely self contained, such that it can be run either in isolation or in arbitrary combination with any number of other test cases.</p> <p>The simplest <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> subclass will simply implement a test method (i.e. a method whose name starts with <code>test</code>) in order to perform specific testing code:</p> <pre data-language="python">import unittest
+
+class DefaultWidgetSizeTestCase(unittest.TestCase):
+ def test_default_widget_size(self):
+ widget = Widget('The widget')
+ self.assertEqual(widget.size(), (50, 50))
+</pre> <p>Note that in order to test something, we use one of the <a class="reference internal" href="#assert-methods"><span class="std std-ref">assert* methods</span></a> provided by the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> base class. If the test fails, an exception will be raised with an explanatory message, and <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> will identify the test case as a <em class="dfn">failure</em>. Any other exceptions will be treated as <em class="dfn">errors</em>.</p> <p>Tests can be numerous, and their set-up can be repetitive. Luckily, we can factor out set-up code by implementing a method called <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a>, which the testing framework will automatically call for every single test we run:</p> <pre data-language="python">import unittest
+
+class WidgetTestCase(unittest.TestCase):
+ def setUp(self):
+ self.widget = Widget('The widget')
+
+ def test_default_widget_size(self):
+ self.assertEqual(self.widget.size(), (50,50),
+ 'incorrect default size')
+
+ def test_widget_resize(self):
+ self.widget.resize(100,150)
+ self.assertEqual(self.widget.size(), (100,150),
+ 'wrong size after resize')
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The order in which the various tests will be run is determined by sorting the test method names with respect to the built-in ordering for strings.</p> </div> <p>If the <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a> method raises an exception while the test is running, the framework will consider the test to have suffered an error, and the test method will not be executed.</p> <p>Similarly, we can provide a <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code>tearDown()</code></a> method that tidies up after the test method has been run:</p> <pre data-language="python">import unittest
+
+class WidgetTestCase(unittest.TestCase):
+ def setUp(self):
+ self.widget = Widget('The widget')
+
+ def tearDown(self):
+ self.widget.dispose()
+</pre> <p>If <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a> succeeded, <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code>tearDown()</code></a> will be run whether the test method succeeded or not.</p> <p>Such a working environment for the testing code is called a <em class="dfn">test fixture</em>. A new TestCase instance is created as a unique test fixture used to execute each individual test method. Thus <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a>, <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code>tearDown()</code></a>, and <code>__init__()</code> will be called once per test.</p> <p>It is recommended that you use TestCase implementations to group tests together according to the features they test. <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> provides a mechanism for this: the <em class="dfn">test suite</em>, represented by <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a>’s <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> class. In most cases, calling <a class="reference internal" href="#unittest.main" title="unittest.main"><code>unittest.main()</code></a> will do the right thing and collect all the module’s test cases for you and execute them.</p> <p>However, should you want to customize the building of your test suite, you can do it yourself:</p> <pre data-language="python">def suite():
+ suite = unittest.TestSuite()
+ suite.addTest(WidgetTestCase('test_default_widget_size'))
+ suite.addTest(WidgetTestCase('test_widget_resize'))
+ return suite
+
+if __name__ == '__main__':
+ runner = unittest.TextTestRunner()
+ runner.run(suite())
+</pre> <p>You can place the definitions of test cases and test suites in the same modules as the code they are to test (such as <code>widget.py</code>), but there are several advantages to placing the test code in a separate module, such as <code>test_widget.py</code>:</p> <ul class="simple"> <li>The test module can be run standalone from the command line.</li> <li>The test code can more easily be separated from shipped code.</li> <li>There is less temptation to change test code to fit the code it tests without a good reason.</li> <li>Test code should be modified much less frequently than the code it tests.</li> <li>Tested code can be refactored more easily.</li> <li>Tests for modules written in C must be in separate modules anyway, so why not be consistent?</li> <li>If the testing strategy changes, there is no need to change the source code.</li> </ul> </section> <section id="re-using-old-test-code"> <span id="legacy-unit-tests"></span><h2>Re-using old test code</h2> <p>Some users will find that they have existing test code that they would like to run from <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a>, without converting every old test function to a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> subclass.</p> <p>For this reason, <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> provides a <a class="reference internal" href="#unittest.FunctionTestCase" title="unittest.FunctionTestCase"><code>FunctionTestCase</code></a> class. This subclass of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> can be used to wrap an existing test function. Set-up and tear-down functions can also be provided.</p> <p>Given the following test function:</p> <pre data-language="python">def testSomething():
+ something = makeSomething()
+ assert something.name is not None
+ # ...
+</pre> <p>one can create an equivalent test case instance as follows, with optional set-up and tear-down methods:</p> <pre data-language="python">testcase = unittest.FunctionTestCase(testSomething,
+ setUp=makeSomethingDB,
+ tearDown=deleteSomethingDB)
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Even though <a class="reference internal" href="#unittest.FunctionTestCase" title="unittest.FunctionTestCase"><code>FunctionTestCase</code></a> can be used to quickly convert an existing test base over to a <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a>-based system, this approach is not recommended. Taking the time to set up proper <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> subclasses will make future test refactorings infinitely easier.</p> </div> <p>In some cases, the existing tests may have been written using the <a class="reference internal" href="doctest#module-doctest" title="doctest: Test pieces of code within docstrings."><code>doctest</code></a> module. If so, <a class="reference internal" href="doctest#module-doctest" title="doctest: Test pieces of code within docstrings."><code>doctest</code></a> provides a <code>DocTestSuite</code> class that can automatically build <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>unittest.TestSuite</code></a> instances from the existing <a class="reference internal" href="doctest#module-doctest" title="doctest: Test pieces of code within docstrings."><code>doctest</code></a>-based tests.</p> </section> <section id="skipping-tests-and-expected-failures"> <span id="unittest-skipping"></span><h2>Skipping tests and expected failures</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> <p>Unittest supports skipping individual test methods and even whole classes of tests. In addition, it supports marking a test as an “expected failure,” a test that is broken and will fail, but shouldn’t be counted as a failure on a <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a>.</p> <p>Skipping a test is simply a matter of using the <a class="reference internal" href="#unittest.skip" title="unittest.skip"><code>skip()</code></a> <a class="reference internal" href="../glossary#term-decorator"><span class="xref std std-term">decorator</span></a> or one of its conditional variants, calling <a class="reference internal" href="#unittest.TestCase.skipTest" title="unittest.TestCase.skipTest"><code>TestCase.skipTest()</code></a> within a <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a> or test method, or raising <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code>SkipTest</code></a> directly.</p> <p>Basic skipping looks like this:</p> <pre data-language="python">class MyTestCase(unittest.TestCase):
+
+ @unittest.skip("demonstrating skipping")
+ def test_nothing(self):
+ self.fail("shouldn't happen")
+
+ @unittest.skipIf(mylib.__version__ &lt; (1, 3),
+ "not supported in this library version")
+ def test_format(self):
+ # Tests that work for only a certain version of the library.
+ pass
+
+ @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
+ def test_windows_support(self):
+ # windows specific testing code
+ pass
+
+ def test_maybe_skipped(self):
+ if not external_resource_available():
+ self.skipTest("external resource not available")
+ # test code that depends on the external resource
+ pass
+</pre> <p>This is the output of running the example above in verbose mode:</p> <pre data-language="python">test_format (__main__.MyTestCase.test_format) ... skipped 'not supported in this library version'
+test_nothing (__main__.MyTestCase.test_nothing) ... skipped 'demonstrating skipping'
+test_maybe_skipped (__main__.MyTestCase.test_maybe_skipped) ... skipped 'external resource not available'
+test_windows_support (__main__.MyTestCase.test_windows_support) ... skipped 'requires Windows'
+
+----------------------------------------------------------------------
+Ran 4 tests in 0.005s
+
+OK (skipped=4)
+</pre> <p>Classes can be skipped just like methods:</p> <pre data-language="python">@unittest.skip("showing class skipping")
+class MySkippedTestCase(unittest.TestCase):
+ def test_not_run(self):
+ pass
+</pre> <p><a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>TestCase.setUp()</code></a> can also skip the test. This is useful when a resource that needs to be set up is not available.</p> <p>Expected failures use the <a class="reference internal" href="#unittest.expectedFailure" title="unittest.expectedFailure"><code>expectedFailure()</code></a> decorator.</p> <pre data-language="python">class ExpectedFailureTestCase(unittest.TestCase):
+ @unittest.expectedFailure
+ def test_fail(self):
+ self.assertEqual(1, 0, "broken")
+</pre> <p>It’s easy to roll your own skipping decorators by making a decorator that calls <a class="reference internal" href="#unittest.skip" title="unittest.skip"><code>skip()</code></a> on the test when it wants it to be skipped. This decorator skips the test unless the passed object has a certain attribute:</p> <pre data-language="python">def skipUnlessHasattr(obj, attr):
+ if hasattr(obj, attr):
+ return lambda func: func
+ return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
+</pre> <p>The following decorators and exception implement test skipping and expected failures:</p> <dl class="py function"> <dt class="sig sig-object py" id="unittest.skip">
+<code>@unittest.skip(reason)</code> </dt> <dd>
+<p>Unconditionally skip the decorated test. <em>reason</em> should describe why the test is being skipped.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="unittest.skipIf">
+<code>@unittest.skipIf(condition, reason)</code> </dt> <dd>
+<p>Skip the decorated test if <em>condition</em> is true.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="unittest.skipUnless">
+<code>@unittest.skipUnless(condition, reason)</code> </dt> <dd>
+<p>Skip the decorated test unless <em>condition</em> is true.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="unittest.expectedFailure">
+<code>@unittest.expectedFailure</code> </dt> <dd>
+<p>Mark the test as an expected failure or error. If the test fails or errors in the test function itself (rather than in one of the <em class="dfn">test fixture</em> methods) then it will be considered a success. If the test passes, it will be considered a failure.</p> </dd>
+</dl> <dl class="py exception"> <dt class="sig sig-object py" id="unittest.SkipTest">
+<code>exception unittest.SkipTest(reason)</code> </dt> <dd>
+<p>This exception is raised to skip a test.</p> <p>Usually you can use <a class="reference internal" href="#unittest.TestCase.skipTest" title="unittest.TestCase.skipTest"><code>TestCase.skipTest()</code></a> or one of the skipping decorators instead of raising this directly.</p> </dd>
+</dl> <p>Skipped tests will not have <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a> or <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code>tearDown()</code></a> run around them. Skipped classes will not have <a class="reference internal" href="#unittest.TestCase.setUpClass" title="unittest.TestCase.setUpClass"><code>setUpClass()</code></a> or <a class="reference internal" href="#unittest.TestCase.tearDownClass" title="unittest.TestCase.tearDownClass"><code>tearDownClass()</code></a> run. Skipped modules will not have <code>setUpModule()</code> or <code>tearDownModule()</code> run.</p> </section> <section id="distinguishing-test-iterations-using-subtests"> <span id="subtests"></span><h2>Distinguishing test iterations using subtests</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <p>When there are very small differences among your tests, for instance some parameters, unittest allows you to distinguish them inside the body of a test method using the <a class="reference internal" href="#unittest.TestCase.subTest" title="unittest.TestCase.subTest"><code>subTest()</code></a> context manager.</p> <p>For example, the following test:</p> <pre data-language="python">class NumbersTest(unittest.TestCase):
+
+ def test_even(self):
+ """
+ Test that numbers between 0 and 5 are all even.
+ """
+ for i in range(0, 6):
+ with self.subTest(i=i):
+ self.assertEqual(i % 2, 0)
+</pre> <p>will produce the following output:</p> <pre data-language="python">======================================================================
+FAIL: test_even (__main__.NumbersTest.test_even) (i=1)
+Test that numbers between 0 and 5 are all even.
+----------------------------------------------------------------------
+Traceback (most recent call last):
+ File "subtests.py", line 11, in test_even
+ self.assertEqual(i % 2, 0)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
+AssertionError: 1 != 0
+
+======================================================================
+FAIL: test_even (__main__.NumbersTest.test_even) (i=3)
+Test that numbers between 0 and 5 are all even.
+----------------------------------------------------------------------
+Traceback (most recent call last):
+ File "subtests.py", line 11, in test_even
+ self.assertEqual(i % 2, 0)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
+AssertionError: 1 != 0
+
+======================================================================
+FAIL: test_even (__main__.NumbersTest.test_even) (i=5)
+Test that numbers between 0 and 5 are all even.
+----------------------------------------------------------------------
+Traceback (most recent call last):
+ File "subtests.py", line 11, in test_even
+ self.assertEqual(i % 2, 0)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
+AssertionError: 1 != 0
+</pre> <p>Without using a subtest, execution would stop after the first failure, and the error would be less easy to diagnose because the value of <code>i</code> wouldn’t be displayed:</p> <pre data-language="python">======================================================================
+FAIL: test_even (__main__.NumbersTest.test_even)
+----------------------------------------------------------------------
+Traceback (most recent call last):
+ File "subtests.py", line 32, in test_even
+ self.assertEqual(i % 2, 0)
+AssertionError: 1 != 0
+</pre> </section> <section id="classes-and-functions"> <span id="unittest-contents"></span><h2>Classes and functions</h2> <p>This section describes in depth the API of <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a>.</p> <section id="test-cases"> <span id="testcase-objects"></span><h3>Test cases</h3> <dl class="py class"> <dt class="sig sig-object py" id="unittest.TestCase">
+<code>class unittest.TestCase(methodName='runTest')</code> </dt> <dd>
+<p>Instances of the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> class represent the logical test units in the <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> universe. This class is intended to be used as a base class, with specific tests being implemented by concrete subclasses. This class implements the interface needed by the test runner to allow it to drive the tests, and methods that the test code can use to check for and report various kinds of failure.</p> <p>Each instance of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> will run a single base method: the method named <em>methodName</em>. In most uses of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a>, you will neither change the <em>methodName</em> nor reimplement the default <code>runTest()</code> method.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span><a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> can be instantiated successfully without providing a <em>methodName</em>. This makes it easier to experiment with <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> from the interactive interpreter.</p> </div> <p><a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instances provide three groups of methods: one group used to run the test, another used by the test implementation to check conditions and report failures, and some inquiry methods allowing information about the test itself to be gathered.</p> <p>Methods in the first group (running the test) are:</p> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.setUp">
+<code>setUp()</code> </dt> <dd>
+<p>Method called to prepare the test fixture. This is called immediately before calling the test method; other than <a class="reference internal" href="exceptions#AssertionError" title="AssertionError"><code>AssertionError</code></a> or <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code>SkipTest</code></a>, any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.tearDown">
+<code>tearDown()</code> </dt> <dd>
+<p>Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception, other than <a class="reference internal" href="exceptions#AssertionError" title="AssertionError"><code>AssertionError</code></a> or <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code>SkipTest</code></a>, raised by this method will be considered an additional error rather than a test failure (thus increasing the total number of reported errors). This method will only be called if the <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a> succeeds, regardless of the outcome of the test method. The default implementation does nothing.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.setUpClass">
+<code>setUpClass()</code> </dt> <dd>
+<p>A class method called before tests in an individual class are run. <code>setUpClass</code> is called with the class as the only argument and must be decorated as a <a class="reference internal" href="functions#classmethod" title="classmethod"><code>classmethod()</code></a>:</p> <pre data-language="python">@classmethod
+def setUpClass(cls):
+ ...
+</pre> <p>See <a class="reference internal" href="#class-and-module-fixtures">Class and Module Fixtures</a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.tearDownClass">
+<code>tearDownClass()</code> </dt> <dd>
+<p>A class method called after tests in an individual class have run. <code>tearDownClass</code> is called with the class as the only argument and must be decorated as a <a class="reference internal" href="functions#classmethod" title="classmethod"><code>classmethod()</code></a>:</p> <pre data-language="python">@classmethod
+def tearDownClass(cls):
+ ...
+</pre> <p>See <a class="reference internal" href="#class-and-module-fixtures">Class and Module Fixtures</a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.run">
+<code>run(result=None)</code> </dt> <dd>
+<p>Run the test, collecting the result into the <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> object passed as <em>result</em>. If <em>result</em> is omitted or <code>None</code>, a temporary result object is created (by calling the <a class="reference internal" href="#unittest.TestCase.defaultTestResult" title="unittest.TestCase.defaultTestResult"><code>defaultTestResult()</code></a> method) and used. The result object is returned to <a class="reference internal" href="#unittest.TestCase.run" title="unittest.TestCase.run"><code>run()</code></a>’s caller.</p> <p>The same effect may be had by simply calling the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instance.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Previous versions of <code>run</code> did not return the result. Neither did calling an instance.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.skipTest">
+<code>skipTest(reason)</code> </dt> <dd>
+<p>Calling this during a test method or <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a> skips the current test. See <a class="reference internal" href="#unittest-skipping"><span class="std std-ref">Skipping tests and expected failures</span></a> for more information.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.subTest">
+<code>subTest(msg=None, **params)</code> </dt> <dd>
+<p>Return a context manager which executes the enclosed code block as a subtest. <em>msg</em> and <em>params</em> are optional, arbitrary values which are displayed whenever a subtest fails, allowing you to identify them clearly.</p> <p>A test case can contain any number of subtest declarations, and they can be arbitrarily nested.</p> <p>See <a class="reference internal" href="#subtests"><span class="std std-ref">Distinguishing test iterations using subtests</span></a> for more information.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.debug">
+<code>debug()</code> </dt> <dd>
+<p>Run the test without collecting the result. This allows exceptions raised by the test to be propagated to the caller, and can be used to support running tests under a debugger.</p> </dd>
+</dl> <p id="assert-methods">The <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> class provides several assert methods to check for and report failures. The following table lists the most commonly used methods (see the tables below for more assert methods):</p> <table class="docutils align-default"> <thead> <tr>
+<th class="head"><p>Method</p></th> <th class="head"><p>Checks that</p></th> <th class="head"><p>New in</p></th> </tr> </thead> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual(a, b)</code></a></p></td> <td><p><code>a == b</code></p></td> <td></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertNotEqual" title="unittest.TestCase.assertNotEqual"><code>assertNotEqual(a, b)</code></a></p></td> <td><p><code>a != b</code></p></td> <td></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertTrue" title="unittest.TestCase.assertTrue"><code>assertTrue(x)</code></a></p></td> <td><p><code>bool(x) is True</code></p></td> <td></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertFalse" title="unittest.TestCase.assertFalse"><code>assertFalse(x)</code></a></p></td> <td><p><code>bool(x) is False</code></p></td> <td></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertIs" title="unittest.TestCase.assertIs"><code>assertIs(a, b)</code></a></p></td> <td><p><code>a is b</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertIsNot" title="unittest.TestCase.assertIsNot"><code>assertIsNot(a, b)</code></a></p></td> <td><p><code>a is not b</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertIsNone" title="unittest.TestCase.assertIsNone"><code>assertIsNone(x)</code></a></p></td> <td><p><code>x is None</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertIsNotNone" title="unittest.TestCase.assertIsNotNone"><code>assertIsNotNone(x)</code></a></p></td> <td><p><code>x is not None</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertIn" title="unittest.TestCase.assertIn"><code>assertIn(a, b)</code></a></p></td> <td><p><code>a in b</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertNotIn" title="unittest.TestCase.assertNotIn"><code>assertNotIn(a, b)</code></a></p></td> <td><p><code>a not in b</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertIsInstance" title="unittest.TestCase.assertIsInstance"><code>assertIsInstance(a, b)</code></a></p></td> <td><p><code>isinstance(a, b)</code></p></td> <td><p>3.2</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertNotIsInstance" title="unittest.TestCase.assertNotIsInstance"><code>assertNotIsInstance(a, b)</code></a></p></td> <td><p><code>not isinstance(a, b)</code></p></td> <td><p>3.2</p></td> </tr> </table> <p>All the assert methods accept a <em>msg</em> argument that, if specified, is used as the error message on failure (see also <a class="reference internal" href="#unittest.TestCase.longMessage" title="unittest.TestCase.longMessage"><code>longMessage</code></a>). Note that the <em>msg</em> keyword argument can be passed to <a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code>assertRaises()</code></a>, <a class="reference internal" href="#unittest.TestCase.assertRaisesRegex" title="unittest.TestCase.assertRaisesRegex"><code>assertRaisesRegex()</code></a>, <a class="reference internal" href="#unittest.TestCase.assertWarns" title="unittest.TestCase.assertWarns"><code>assertWarns()</code></a>, <a class="reference internal" href="#unittest.TestCase.assertWarnsRegex" title="unittest.TestCase.assertWarnsRegex"><code>assertWarnsRegex()</code></a> only when they are used as a context manager.</p> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertEqual">
+<code>assertEqual(first, second, msg=None)</code> </dt> <dd>
+<p>Test that <em>first</em> and <em>second</em> are equal. If the values do not compare equal, the test will fail.</p> <p>In addition, if <em>first</em> and <em>second</em> are the exact same type and one of list, tuple, dict, set, frozenset or str or any type that a subclass registers with <a class="reference internal" href="#unittest.TestCase.addTypeEqualityFunc" title="unittest.TestCase.addTypeEqualityFunc"><code>addTypeEqualityFunc()</code></a> the type-specific equality function will be called in order to generate a more useful default error message (see also the <a class="reference internal" href="#type-specific-methods"><span class="std std-ref">list of type-specific methods</span></a>).</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span>Added the automatic calling of type-specific equality function.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span><a class="reference internal" href="#unittest.TestCase.assertMultiLineEqual" title="unittest.TestCase.assertMultiLineEqual"><code>assertMultiLineEqual()</code></a> added as the default type equality function for comparing strings.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertNotEqual">
+<code>assertNotEqual(first, second, msg=None)</code> </dt> <dd>
+<p>Test that <em>first</em> and <em>second</em> are not equal. If the values do compare equal, the test will fail.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertTrue">
+<code>assertTrue(expr, msg=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertFalse">
+<code>assertFalse(expr, msg=None)</code> </dt> <dd>
+<p>Test that <em>expr</em> is true (or false).</p> <p>Note that this is equivalent to <code>bool(expr) is True</code> and not to <code>expr
+is True</code> (use <code>assertIs(expr, True)</code> for the latter). This method should also be avoided when more specific methods are available (e.g. <code>assertEqual(a, b)</code> instead of <code>assertTrue(a == b)</code>), because they provide a better error message in case of failure.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertIs">
+<code>assertIs(first, second, msg=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertIsNot">
+<code>assertIsNot(first, second, msg=None)</code> </dt> <dd>
+<p>Test that <em>first</em> and <em>second</em> are (or are not) the same object.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertIsNone">
+<code>assertIsNone(expr, msg=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertIsNotNone">
+<code>assertIsNotNone(expr, msg=None)</code> </dt> <dd>
+<p>Test that <em>expr</em> is (or is not) <code>None</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertIn">
+<code>assertIn(member, container, msg=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertNotIn">
+<code>assertNotIn(member, container, msg=None)</code> </dt> <dd>
+<p>Test that <em>member</em> is (or is not) in <em>container</em>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertIsInstance">
+<code>assertIsInstance(obj, cls, msg=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertNotIsInstance">
+<code>assertNotIsInstance(obj, cls, msg=None)</code> </dt> <dd>
+<p>Test that <em>obj</em> is (or is not) an instance of <em>cls</em> (which can be a class or a tuple of classes, as supported by <a class="reference internal" href="functions#isinstance" title="isinstance"><code>isinstance()</code></a>). To check for the exact type, use <a class="reference internal" href="#unittest.TestCase.assertIs" title="unittest.TestCase.assertIs"><code>assertIs(type(obj), cls)</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <p>It is also possible to check the production of exceptions, warnings, and log messages using the following methods:</p> <table class="docutils align-default"> <thead> <tr>
+<th class="head"><p>Method</p></th> <th class="head"><p>Checks that</p></th> <th class="head"><p>New in</p></th> </tr> </thead> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code>assertRaises(exc, fun, *args, **kwds)</code></a></p></td> <td><p><code>fun(*args, **kwds)</code> raises <em>exc</em></p></td> <td></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertRaisesRegex" title="unittest.TestCase.assertRaisesRegex"><code>assertRaisesRegex(exc, r, fun, *args, **kwds)</code></a></p></td> <td><p><code>fun(*args, **kwds)</code> raises <em>exc</em> and the message matches regex <em>r</em></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertWarns" title="unittest.TestCase.assertWarns"><code>assertWarns(warn, fun, *args, **kwds)</code></a></p></td> <td><p><code>fun(*args, **kwds)</code> raises <em>warn</em></p></td> <td><p>3.2</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertWarnsRegex" title="unittest.TestCase.assertWarnsRegex"><code>assertWarnsRegex(warn, r, fun, *args, **kwds)</code></a></p></td> <td><p><code>fun(*args, **kwds)</code> raises <em>warn</em> and the message matches regex <em>r</em></p></td> <td><p>3.2</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertLogs" title="unittest.TestCase.assertLogs"><code>assertLogs(logger, level)</code></a></p></td> <td><p>The <code>with</code> block logs on <em>logger</em> with minimum <em>level</em></p></td> <td><p>3.4</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertNoLogs" title="unittest.TestCase.assertNoLogs"><code>assertNoLogs(logger, level)</code></a></p></td> <td>
+<dl class="simple"> <dt>
+<code>The with block does not log on</code> </dt>
+<dd>
+<p><em>logger</em> with minimum <em>level</em></p> </dd> </dl> </td> <td><p>3.10</p></td> </tr> </table> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertRaises">
+<code>assertRaises(exception, callable, *args, **kwds)</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">assertRaises</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">exception</span></em>, <em class="sig-param"><span class="o">*</span></em>, <em class="sig-param"><span class="n">msg</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
+</dt> <dd>
+<p>Test that an exception is raised when <em>callable</em> is called with any positional or keyword arguments that are also passed to <a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code>assertRaises()</code></a>. The test passes if <em>exception</em> is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as <em>exception</em>.</p> <p>If only the <em>exception</em> and possibly the <em>msg</em> arguments are given, return a context manager so that the code under test can be written inline rather than as a function:</p> <pre data-language="python">with self.assertRaises(SomeException):
+ do_something()
+</pre> <p>When used as a context manager, <a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code>assertRaises()</code></a> accepts the additional keyword argument <em>msg</em>.</p> <p>The context manager will store the caught exception object in its <code>exception</code> attribute. This can be useful if the intention is to perform additional checks on the exception raised:</p> <pre data-language="python">with self.assertRaises(SomeException) as cm:
+ do_something()
+
+the_exception = cm.exception
+self.assertEqual(the_exception.error_code, 3)
+</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span>Added the ability to use <a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code>assertRaises()</code></a> as a context manager.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Added the <code>exception</code> attribute.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Added the <em>msg</em> keyword argument when used as a context manager.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertRaisesRegex">
+<code>assertRaisesRegex(exception, regex, callable, *args, **kwds)</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">assertRaisesRegex</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">exception</span></em>, <em class="sig-param"><span class="n">regex</span></em>, <em class="sig-param"><span class="o">*</span></em>, <em class="sig-param"><span class="n">msg</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
+</dt> <dd>
+<p>Like <a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code>assertRaises()</code></a> but also tests that <em>regex</em> matches on the string representation of the raised exception. <em>regex</em> may be a regular expression object or a string containing a regular expression suitable for use by <a class="reference internal" href="re#re.search" title="re.search"><code>re.search()</code></a>. Examples:</p> <pre data-language="python">self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
+ int, 'XYZ')
+</pre> <p>or:</p> <pre data-language="python">with self.assertRaisesRegex(ValueError, 'literal'):
+ int('XYZ')
+</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1: </span>Added under the name <code>assertRaisesRegexp</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Renamed to <a class="reference internal" href="#unittest.TestCase.assertRaisesRegex" title="unittest.TestCase.assertRaisesRegex"><code>assertRaisesRegex()</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Added the <em>msg</em> keyword argument when used as a context manager.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertWarns">
+<code>assertWarns(warning, callable, *args, **kwds)</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">assertWarns</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">warning</span></em>, <em class="sig-param"><span class="o">*</span></em>, <em class="sig-param"><span class="n">msg</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
+</dt> <dd>
+<p>Test that a warning is triggered when <em>callable</em> is called with any positional or keyword arguments that are also passed to <a class="reference internal" href="#unittest.TestCase.assertWarns" title="unittest.TestCase.assertWarns"><code>assertWarns()</code></a>. The test passes if <em>warning</em> is triggered and fails if it isn’t. Any exception is an error. To catch any of a group of warnings, a tuple containing the warning classes may be passed as <em>warnings</em>.</p> <p>If only the <em>warning</em> and possibly the <em>msg</em> arguments are given, return a context manager so that the code under test can be written inline rather than as a function:</p> <pre data-language="python">with self.assertWarns(SomeWarning):
+ do_something()
+</pre> <p>When used as a context manager, <a class="reference internal" href="#unittest.TestCase.assertWarns" title="unittest.TestCase.assertWarns"><code>assertWarns()</code></a> accepts the additional keyword argument <em>msg</em>.</p> <p>The context manager will store the caught warning object in its <code>warning</code> attribute, and the source line which triggered the warnings in the <code>filename</code> and <code>lineno</code> attributes. This can be useful if the intention is to perform additional checks on the warning caught:</p> <pre data-language="python">with self.assertWarns(SomeWarning) as cm:
+ do_something()
+
+self.assertIn('myfile.py', cm.filename)
+self.assertEqual(320, cm.lineno)
+</pre> <p>This method works regardless of the warning filters in place when it is called.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Added the <em>msg</em> keyword argument when used as a context manager.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertWarnsRegex">
+<code>assertWarnsRegex(warning, regex, callable, *args, **kwds)</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">assertWarnsRegex</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">warning</span></em>, <em class="sig-param"><span class="n">regex</span></em>, <em class="sig-param"><span class="o">*</span></em>, <em class="sig-param"><span class="n">msg</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
+</dt> <dd>
+<p>Like <a class="reference internal" href="#unittest.TestCase.assertWarns" title="unittest.TestCase.assertWarns"><code>assertWarns()</code></a> but also tests that <em>regex</em> matches on the message of the triggered warning. <em>regex</em> may be a regular expression object or a string containing a regular expression suitable for use by <a class="reference internal" href="re#re.search" title="re.search"><code>re.search()</code></a>. Example:</p> <pre data-language="python">self.assertWarnsRegex(DeprecationWarning,
+ r'legacy_function\(\) is deprecated',
+ legacy_function, 'XYZ')
+</pre> <p>or:</p> <pre data-language="python">with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
+ frobnicate('/etc/passwd')
+</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Added the <em>msg</em> keyword argument when used as a context manager.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertLogs">
+<code>assertLogs(logger=None, level=None)</code> </dt> <dd>
+<p>A context manager to test that at least one message is logged on the <em>logger</em> or one of its children, with at least the given <em>level</em>.</p> <p>If given, <em>logger</em> should be a <a class="reference internal" href="logging#logging.Logger" title="logging.Logger"><code>logging.Logger</code></a> object or a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> giving the name of a logger. The default is the root logger, which will catch all messages that were not blocked by a non-propagating descendent logger.</p> <p>If given, <em>level</em> should be either a numeric logging level or its string equivalent (for example either <code>"ERROR"</code> or <a class="reference internal" href="logging#logging.ERROR" title="logging.ERROR"><code>logging.ERROR</code></a>). The default is <a class="reference internal" href="logging#logging.INFO" title="logging.INFO"><code>logging.INFO</code></a>.</p> <p>The test passes if at least one message emitted inside the <code>with</code> block matches the <em>logger</em> and <em>level</em> conditions, otherwise it fails.</p> <p>The object returned by the context manager is a recording helper which keeps tracks of the matching log messages. It has two attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestCase.records">
+<code>records</code> </dt> <dd>
+<p>A list of <a class="reference internal" href="logging#logging.LogRecord" title="logging.LogRecord"><code>logging.LogRecord</code></a> objects of the matching log messages.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestCase.output">
+<code>output</code> </dt> <dd>
+<p>A list of <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> objects with the formatted output of matching messages.</p> </dd>
+</dl> <p>Example:</p> <pre data-language="python">with self.assertLogs('foo', level='INFO') as cm:
+ logging.getLogger('foo').info('first message')
+ logging.getLogger('foo.bar').error('second message')
+self.assertEqual(cm.output, ['INFO:foo:first message',
+ 'ERROR:foo.bar:second message'])
+</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertNoLogs">
+<code>assertNoLogs(logger=None, level=None)</code> </dt> <dd>
+<p>A context manager to test that no messages are logged on the <em>logger</em> or one of its children, with at least the given <em>level</em>.</p> <p>If given, <em>logger</em> should be a <a class="reference internal" href="logging#logging.Logger" title="logging.Logger"><code>logging.Logger</code></a> object or a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> giving the name of a logger. The default is the root logger, which will catch all messages.</p> <p>If given, <em>level</em> should be either a numeric logging level or its string equivalent (for example either <code>"ERROR"</code> or <a class="reference internal" href="logging#logging.ERROR" title="logging.ERROR"><code>logging.ERROR</code></a>). The default is <a class="reference internal" href="logging#logging.INFO" title="logging.INFO"><code>logging.INFO</code></a>.</p> <p>Unlike <a class="reference internal" href="#unittest.TestCase.assertLogs" title="unittest.TestCase.assertLogs"><code>assertLogs()</code></a>, nothing will be returned by the context manager.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
+</dl> <p>There are also other methods used to perform more specific checks, such as:</p> <table class="docutils align-default"> <thead> <tr>
+<th class="head"><p>Method</p></th> <th class="head"><p>Checks that</p></th> <th class="head"><p>New in</p></th> </tr> </thead> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertAlmostEqual" title="unittest.TestCase.assertAlmostEqual"><code>assertAlmostEqual(a, b)</code></a></p></td> <td><p><code>round(a-b, 7) == 0</code></p></td> <td></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertNotAlmostEqual" title="unittest.TestCase.assertNotAlmostEqual"><code>assertNotAlmostEqual(a, b)</code></a></p></td> <td><p><code>round(a-b, 7) != 0</code></p></td> <td></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertGreater" title="unittest.TestCase.assertGreater"><code>assertGreater(a, b)</code></a></p></td> <td><p><code>a &gt; b</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertGreaterEqual" title="unittest.TestCase.assertGreaterEqual"><code>assertGreaterEqual(a, b)</code></a></p></td> <td><p><code>a &gt;= b</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertLess" title="unittest.TestCase.assertLess"><code>assertLess(a, b)</code></a></p></td> <td><p><code>a &lt; b</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertLessEqual" title="unittest.TestCase.assertLessEqual"><code>assertLessEqual(a, b)</code></a></p></td> <td><p><code>a &lt;= b</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertRegex" title="unittest.TestCase.assertRegex"><code>assertRegex(s, r)</code></a></p></td> <td><p><code>r.search(s)</code></p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertNotRegex" title="unittest.TestCase.assertNotRegex"><code>assertNotRegex(s, r)</code></a></p></td> <td><p><code>not r.search(s)</code></p></td> <td><p>3.2</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertCountEqual" title="unittest.TestCase.assertCountEqual"><code>assertCountEqual(a, b)</code></a></p></td> <td><p><em>a</em> and <em>b</em> have the same elements in the same number, regardless of their order.</p></td> <td><p>3.2</p></td> </tr> </table> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertAlmostEqual">
+<code>assertAlmostEqual(first, second, places=7, msg=None, delta=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertNotAlmostEqual">
+<code>assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)</code> </dt> <dd>
+<p>Test that <em>first</em> and <em>second</em> are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal <em>places</em> (default 7), and comparing to zero. Note that these methods round the values to the given number of <em>decimal places</em> (i.e. like the <a class="reference internal" href="functions#round" title="round"><code>round()</code></a> function) and not <em>significant digits</em>.</p> <p>If <em>delta</em> is supplied instead of <em>places</em> then the difference between <em>first</em> and <em>second</em> must be less or equal to (or greater than) <em>delta</em>.</p> <p>Supplying both <em>delta</em> and <em>places</em> raises a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span><a class="reference internal" href="#unittest.TestCase.assertAlmostEqual" title="unittest.TestCase.assertAlmostEqual"><code>assertAlmostEqual()</code></a> automatically considers almost equal objects that compare equal. <a class="reference internal" href="#unittest.TestCase.assertNotAlmostEqual" title="unittest.TestCase.assertNotAlmostEqual"><code>assertNotAlmostEqual()</code></a> automatically fails if the objects compare equal. Added the <em>delta</em> keyword argument.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertGreater">
+<code>assertGreater(first, second, msg=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertGreaterEqual">
+<code>assertGreaterEqual(first, second, msg=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertLess">
+<code>assertLess(first, second, msg=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertLessEqual">
+<code>assertLessEqual(first, second, msg=None)</code> </dt> <dd>
+<p>Test that <em>first</em> is respectively &gt;, &gt;=, &lt; or &lt;= than <em>second</em> depending on the method name. If not, the test will fail:</p> <pre data-language="python">&gt;&gt;&gt; self.assertGreaterEqual(3, 4)
+AssertionError: "3" unexpectedly not greater than or equal to "4"
+</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertRegex">
+<code>assertRegex(text, regex, msg=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertNotRegex">
+<code>assertNotRegex(text, regex, msg=None)</code> </dt> <dd>
+<p>Test that a <em>regex</em> search matches (or does not match) <em>text</em>. In case of failure, the error message will include the pattern and the <em>text</em> (or the pattern and the part of <em>text</em> that unexpectedly matched). <em>regex</em> may be a regular expression object or a string containing a regular expression suitable for use by <a class="reference internal" href="re#re.search" title="re.search"><code>re.search()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1: </span>Added under the name <code>assertRegexpMatches</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The method <code>assertRegexpMatches()</code> has been renamed to <a class="reference internal" href="#unittest.TestCase.assertRegex" title="unittest.TestCase.assertRegex"><code>assertRegex()</code></a>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span><a class="reference internal" href="#unittest.TestCase.assertNotRegex" title="unittest.TestCase.assertNotRegex"><code>assertNotRegex()</code></a>.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertCountEqual">
+<code>assertCountEqual(first, second, msg=None)</code> </dt> <dd>
+<p>Test that sequence <em>first</em> contains the same elements as <em>second</em>, regardless of their order. When they don’t, an error message listing the differences between the sequences will be generated.</p> <p>Duplicate elements are <em>not</em> ignored when comparing <em>first</em> and <em>second</em>. It verifies whether each element has the same count in both sequences. Equivalent to: <code>assertEqual(Counter(list(first)), Counter(list(second)))</code> but works with sequences of unhashable objects as well.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <p id="type-specific-methods">The <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual()</code></a> method dispatches the equality check for objects of the same type to different type-specific methods. These methods are already implemented for most of the built-in types, but it’s also possible to register new methods using <a class="reference internal" href="#unittest.TestCase.addTypeEqualityFunc" title="unittest.TestCase.addTypeEqualityFunc"><code>addTypeEqualityFunc()</code></a>:</p> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.addTypeEqualityFunc">
+<code>addTypeEqualityFunc(typeobj, function)</code> </dt> <dd>
+<p>Registers a type-specific method called by <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual()</code></a> to check if two objects of exactly the same <em>typeobj</em> (not subclasses) compare equal. <em>function</em> must take two positional arguments and a third msg=None keyword argument just as <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual()</code></a> does. It must raise <a class="reference internal" href="#unittest.TestCase.failureException" title="unittest.TestCase.failureException"><code>self.failureException(msg)</code></a> when inequality between the first two parameters is detected – possibly providing useful information and explaining the inequalities in details in the error message.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <p>The list of type-specific methods automatically used by <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual()</code></a> are summarized in the following table. Note that it’s usually not necessary to invoke these methods directly.</p> <table class="docutils align-default"> <thead> <tr>
+<th class="head"><p>Method</p></th> <th class="head"><p>Used to compare</p></th> <th class="head"><p>New in</p></th> </tr> </thead> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertMultiLineEqual" title="unittest.TestCase.assertMultiLineEqual"><code>assertMultiLineEqual(a, b)</code></a></p></td> <td><p>strings</p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertSequenceEqual" title="unittest.TestCase.assertSequenceEqual"><code>assertSequenceEqual(a, b)</code></a></p></td> <td><p>sequences</p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertListEqual" title="unittest.TestCase.assertListEqual"><code>assertListEqual(a, b)</code></a></p></td> <td><p>lists</p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertTupleEqual" title="unittest.TestCase.assertTupleEqual"><code>assertTupleEqual(a, b)</code></a></p></td> <td><p>tuples</p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertSetEqual" title="unittest.TestCase.assertSetEqual"><code>assertSetEqual(a, b)</code></a></p></td> <td><p>sets or frozensets</p></td> <td><p>3.1</p></td> </tr> <tr>
+<td><p><a class="reference internal" href="#unittest.TestCase.assertDictEqual" title="unittest.TestCase.assertDictEqual"><code>assertDictEqual(a, b)</code></a></p></td> <td><p>dicts</p></td> <td><p>3.1</p></td> </tr> </table> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertMultiLineEqual">
+<code>assertMultiLineEqual(first, second, msg=None)</code> </dt> <dd>
+<p>Test that the multiline string <em>first</em> is equal to the string <em>second</em>. When not equal a diff of the two strings highlighting the differences will be included in the error message. This method is used by default when comparing strings with <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertSequenceEqual">
+<code>assertSequenceEqual(first, second, msg=None, seq_type=None)</code> </dt> <dd>
+<p>Tests that two sequences are equal. If a <em>seq_type</em> is supplied, both <em>first</em> and <em>second</em> must be instances of <em>seq_type</em> or a failure will be raised. If the sequences are different an error message is constructed that shows the difference between the two.</p> <p>This method is not called directly by <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual()</code></a>, but it’s used to implement <a class="reference internal" href="#unittest.TestCase.assertListEqual" title="unittest.TestCase.assertListEqual"><code>assertListEqual()</code></a> and <a class="reference internal" href="#unittest.TestCase.assertTupleEqual" title="unittest.TestCase.assertTupleEqual"><code>assertTupleEqual()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertListEqual">
+<code>assertListEqual(first, second, msg=None)</code> </dt> <dt class="sig sig-object py" id="unittest.TestCase.assertTupleEqual">
+<code>assertTupleEqual(first, second, msg=None)</code> </dt> <dd>
+<p>Tests that two lists or tuples are equal. If not, an error message is constructed that shows only the differences between the two. An error is also raised if either of the parameters are of the wrong type. These methods are used by default when comparing lists or tuples with <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertSetEqual">
+<code>assertSetEqual(first, second, msg=None)</code> </dt> <dd>
+<p>Tests that two sets are equal. If not, an error message is constructed that lists the differences between the sets. This method is used by default when comparing sets or frozensets with <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual()</code></a>.</p> <p>Fails if either of <em>first</em> or <em>second</em> does not have a <code>set.difference()</code> method.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.assertDictEqual">
+<code>assertDictEqual(first, second, msg=None)</code> </dt> <dd>
+<p>Test that two dictionaries are equal. If not, an error message is constructed that shows the differences in the dictionaries. This method will be used by default to compare dictionaries in calls to <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code>assertEqual()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <p id="other-methods-and-attrs">Finally the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> provides the following methods and attributes:</p> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.fail">
+<code>fail(msg=None)</code> </dt> <dd>
+<p>Signals a test failure unconditionally, with <em>msg</em> or <code>None</code> for the error message.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestCase.failureException">
+<code>failureException</code> </dt> <dd>
+<p>This class attribute gives the exception raised by the test method. If a test framework needs to use a specialized exception, possibly to carry additional information, it must subclass this exception in order to “play fair” with the framework. The initial value of this attribute is <a class="reference internal" href="exceptions#AssertionError" title="AssertionError"><code>AssertionError</code></a>.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestCase.longMessage">
+<code>longMessage</code> </dt> <dd>
+<p>This class attribute determines what happens when a custom failure message is passed as the msg argument to an assertXYY call that fails. <code>True</code> is the default value. In this case, the custom message is appended to the end of the standard failure message. When set to <code>False</code>, the custom message replaces the standard message.</p> <p>The class setting can be overridden in individual test methods by assigning an instance attribute, self.longMessage, to <code>True</code> or <code>False</code> before calling the assert methods.</p> <p>The class setting gets reset before each test call.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestCase.maxDiff">
+<code>maxDiff</code> </dt> <dd>
+<p>This attribute controls the maximum length of diffs output by assert methods that report diffs on failure. It defaults to 80*8 characters. Assert methods affected by this attribute are <a class="reference internal" href="#unittest.TestCase.assertSequenceEqual" title="unittest.TestCase.assertSequenceEqual"><code>assertSequenceEqual()</code></a> (including all the sequence comparison methods that delegate to it), <a class="reference internal" href="#unittest.TestCase.assertDictEqual" title="unittest.TestCase.assertDictEqual"><code>assertDictEqual()</code></a> and <a class="reference internal" href="#unittest.TestCase.assertMultiLineEqual" title="unittest.TestCase.assertMultiLineEqual"><code>assertMultiLineEqual()</code></a>.</p> <p>Setting <code>maxDiff</code> to <code>None</code> means that there is no maximum length of diffs.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <p>Testing frameworks can use the following methods to collect information on the test:</p> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.countTestCases">
+<code>countTestCases()</code> </dt> <dd>
+<p>Return the number of tests represented by this test object. For <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instances, this will always be <code>1</code>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.defaultTestResult">
+<code>defaultTestResult()</code> </dt> <dd>
+<p>Return an instance of the test result class that should be used for this test case class (if no other result instance is provided to the <a class="reference internal" href="#unittest.TestCase.run" title="unittest.TestCase.run"><code>run()</code></a> method).</p> <p>For <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instances, this will always be an instance of <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a>; subclasses of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> should override this as necessary.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.id">
+<code>id()</code> </dt> <dd>
+<p>Return a string identifying the specific test case. This is usually the full name of the test method, including the module and class name.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.shortDescription">
+<code>shortDescription()</code> </dt> <dd>
+<p>Returns a description of the test, or <code>None</code> if no description has been provided. The default implementation of this method returns the first line of the test method’s docstring, if available, or <code>None</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span>In 3.1 this was changed to add the test name to the short description even in the presence of a docstring. This caused compatibility issues with unittest extensions and adding the test name was moved to the <a class="reference internal" href="#unittest.TextTestResult" title="unittest.TextTestResult"><code>TextTestResult</code></a> in Python 3.2.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.addCleanup">
+<code>addCleanup(function, /, *args, **kwargs)</code> </dt> <dd>
+<p>Add a function to be called after <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code>tearDown()</code></a> to cleanup resources used during the test. Functions will be called in reverse order to the order they are added (<abbr title="last-in, first-out">LIFO</abbr>). They are called with any arguments and keyword arguments passed into <a class="reference internal" href="#unittest.TestCase.addCleanup" title="unittest.TestCase.addCleanup"><code>addCleanup()</code></a> when they are added.</p> <p>If <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a> fails, meaning that <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code>tearDown()</code></a> is not called, then any cleanup functions added will still be called.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.enterContext">
+<code>enterContext(cm)</code> </dt> <dd>
+<p>Enter the supplied <a class="reference internal" href="../glossary#term-context-manager"><span class="xref std std-term">context manager</span></a>. If successful, also add its <a class="reference internal" href="../reference/datamodel#object.__exit__" title="object.__exit__"><code>__exit__()</code></a> method as a cleanup function by <a class="reference internal" href="#unittest.TestCase.addCleanup" title="unittest.TestCase.addCleanup"><code>addCleanup()</code></a> and return the result of the <a class="reference internal" href="../reference/datamodel#object.__enter__" title="object.__enter__"><code>__enter__()</code></a> method.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.doCleanups">
+<code>doCleanups()</code> </dt> <dd>
+<p>This method is called unconditionally after <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code>tearDown()</code></a>, or after <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a> if <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code>setUp()</code></a> raises an exception.</p> <p>It is responsible for calling all the cleanup functions added by <a class="reference internal" href="#unittest.TestCase.addCleanup" title="unittest.TestCase.addCleanup"><code>addCleanup()</code></a>. If you need cleanup functions to be called <em>prior</em> to <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code>tearDown()</code></a> then you can call <a class="reference internal" href="#unittest.TestCase.doCleanups" title="unittest.TestCase.doCleanups"><code>doCleanups()</code></a> yourself.</p> <p><a class="reference internal" href="#unittest.TestCase.doCleanups" title="unittest.TestCase.doCleanups"><code>doCleanups()</code></a> pops methods off the stack of cleanup functions one at a time, so it can be called at any time.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.addClassCleanup">
+<code>classmethod addClassCleanup(function, /, *args, **kwargs)</code> </dt> <dd>
+<p>Add a function to be called after <a class="reference internal" href="#unittest.TestCase.tearDownClass" title="unittest.TestCase.tearDownClass"><code>tearDownClass()</code></a> to cleanup resources used during the test class. Functions will be called in reverse order to the order they are added (<abbr title="last-in, first-out">LIFO</abbr>). They are called with any arguments and keyword arguments passed into <a class="reference internal" href="#unittest.TestCase.addClassCleanup" title="unittest.TestCase.addClassCleanup"><code>addClassCleanup()</code></a> when they are added.</p> <p>If <a class="reference internal" href="#unittest.TestCase.setUpClass" title="unittest.TestCase.setUpClass"><code>setUpClass()</code></a> fails, meaning that <a class="reference internal" href="#unittest.TestCase.tearDownClass" title="unittest.TestCase.tearDownClass"><code>tearDownClass()</code></a> is not called, then any cleanup functions added will still be called.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.enterClassContext">
+<code>classmethod enterClassContext(cm)</code> </dt> <dd>
+<p>Enter the supplied <a class="reference internal" href="../glossary#term-context-manager"><span class="xref std std-term">context manager</span></a>. If successful, also add its <a class="reference internal" href="../reference/datamodel#object.__exit__" title="object.__exit__"><code>__exit__()</code></a> method as a cleanup function by <a class="reference internal" href="#unittest.TestCase.addClassCleanup" title="unittest.TestCase.addClassCleanup"><code>addClassCleanup()</code></a> and return the result of the <a class="reference internal" href="../reference/datamodel#object.__enter__" title="object.__enter__"><code>__enter__()</code></a> method.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestCase.doClassCleanups">
+<code>classmethod doClassCleanups()</code> </dt> <dd>
+<p>This method is called unconditionally after <a class="reference internal" href="#unittest.TestCase.tearDownClass" title="unittest.TestCase.tearDownClass"><code>tearDownClass()</code></a>, or after <a class="reference internal" href="#unittest.TestCase.setUpClass" title="unittest.TestCase.setUpClass"><code>setUpClass()</code></a> if <a class="reference internal" href="#unittest.TestCase.setUpClass" title="unittest.TestCase.setUpClass"><code>setUpClass()</code></a> raises an exception.</p> <p>It is responsible for calling all the cleanup functions added by <a class="reference internal" href="#unittest.TestCase.addClassCleanup" title="unittest.TestCase.addClassCleanup"><code>addClassCleanup()</code></a>. If you need cleanup functions to be called <em>prior</em> to <a class="reference internal" href="#unittest.TestCase.tearDownClass" title="unittest.TestCase.tearDownClass"><code>tearDownClass()</code></a> then you can call <a class="reference internal" href="#unittest.TestCase.doClassCleanups" title="unittest.TestCase.doClassCleanups"><code>doClassCleanups()</code></a> yourself.</p> <p><a class="reference internal" href="#unittest.TestCase.doClassCleanups" title="unittest.TestCase.doClassCleanups"><code>doClassCleanups()</code></a> pops methods off the stack of cleanup functions one at a time, so it can be called at any time.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="unittest.IsolatedAsyncioTestCase">
+<code>class unittest.IsolatedAsyncioTestCase(methodName='runTest')</code> </dt> <dd>
+<p>This class provides an API similar to <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> and also accepts coroutines as test functions.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> <dl class="py method"> <dt class="sig sig-object py" id="unittest.IsolatedAsyncioTestCase.asyncSetUp">
+<code>coroutine asyncSetUp()</code> </dt> <dd>
+<p>Method called to prepare the test fixture. This is called after <code>setUp()</code>. This is called immediately before calling the test method; other than <a class="reference internal" href="exceptions#AssertionError" title="AssertionError"><code>AssertionError</code></a> or <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code>SkipTest</code></a>, any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.IsolatedAsyncioTestCase.asyncTearDown">
+<code>coroutine asyncTearDown()</code> </dt> <dd>
+<p>Method called immediately after the test method has been called and the result recorded. This is called before <code>tearDown()</code>. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception, other than <a class="reference internal" href="exceptions#AssertionError" title="AssertionError"><code>AssertionError</code></a> or <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code>SkipTest</code></a>, raised by this method will be considered an additional error rather than a test failure (thus increasing the total number of reported errors). This method will only be called if the <a class="reference internal" href="#unittest.IsolatedAsyncioTestCase.asyncSetUp" title="unittest.IsolatedAsyncioTestCase.asyncSetUp"><code>asyncSetUp()</code></a> succeeds, regardless of the outcome of the test method. The default implementation does nothing.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.IsolatedAsyncioTestCase.addAsyncCleanup">
+<code>addAsyncCleanup(function, /, *args, **kwargs)</code> </dt> <dd>
+<p>This method accepts a coroutine that can be used as a cleanup function.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.IsolatedAsyncioTestCase.enterAsyncContext">
+<code>coroutine enterAsyncContext(cm)</code> </dt> <dd>
+<p>Enter the supplied <a class="reference internal" href="../glossary#term-asynchronous-context-manager"><span class="xref std std-term">asynchronous context manager</span></a>. If successful, also add its <a class="reference internal" href="../reference/datamodel#object.__aexit__" title="object.__aexit__"><code>__aexit__()</code></a> method as a cleanup function by <a class="reference internal" href="#unittest.IsolatedAsyncioTestCase.addAsyncCleanup" title="unittest.IsolatedAsyncioTestCase.addAsyncCleanup"><code>addAsyncCleanup()</code></a> and return the result of the <a class="reference internal" href="../reference/datamodel#object.__aenter__" title="object.__aenter__"><code>__aenter__()</code></a> method.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.IsolatedAsyncioTestCase.run">
+<code>run(result=None)</code> </dt> <dd>
+<p>Sets up a new event loop to run the test, collecting the result into the <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> object passed as <em>result</em>. If <em>result</em> is omitted or <code>None</code>, a temporary result object is created (by calling the <code>defaultTestResult()</code> method) and used. The result object is returned to <a class="reference internal" href="#unittest.IsolatedAsyncioTestCase.run" title="unittest.IsolatedAsyncioTestCase.run"><code>run()</code></a>’s caller. At the end of the test all the tasks in the event loop are cancelled.</p> </dd>
+</dl> <p>An example illustrating the order:</p> <pre data-language="python">from unittest import IsolatedAsyncioTestCase
+
+events = []
+
+
+class Test(IsolatedAsyncioTestCase):
+
+
+ def setUp(self):
+ events.append("setUp")
+
+ async def asyncSetUp(self):
+ self._async_connection = await AsyncConnection()
+ events.append("asyncSetUp")
+
+ async def test_response(self):
+ events.append("test_response")
+ response = await self._async_connection.get("https://example.com")
+ self.assertEqual(response.status_code, 200)
+ self.addAsyncCleanup(self.on_cleanup)
+
+ def tearDown(self):
+ events.append("tearDown")
+
+ async def asyncTearDown(self):
+ await self._async_connection.close()
+ events.append("asyncTearDown")
+
+ async def on_cleanup(self):
+ events.append("cleanup")
+
+if __name__ == "__main__":
+ unittest.main()
+</pre> <p>After running the test, <code>events</code> would contain <code>["setUp", "asyncSetUp", "test_response", "asyncTearDown", "tearDown", "cleanup"]</code>.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="unittest.FunctionTestCase">
+<code>class unittest.FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)</code> </dt> <dd>
+<p>This class implements the portion of the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> interface which allows the test runner to drive the test, but does not provide the methods which test code can use to check and report errors. This is used to create test cases using legacy test code, allowing it to be integrated into a <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a>-based test framework.</p> </dd>
+</dl> </section> <section id="grouping-tests"> <span id="testsuite-objects"></span><h3>Grouping tests</h3> <dl class="py class"> <dt class="sig sig-object py" id="unittest.TestSuite">
+<code>class unittest.TestSuite(tests=())</code> </dt> <dd>
+<p>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 run as any other test case. Running a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> instance is the same as iterating over the suite, running each test individually.</p> <p>If <em>tests</em> is given, it must be an iterable of individual test cases or other test suites that will be used to build the suite initially. Additional methods are provided to add test cases and suites to the collection later on.</p> <p><a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> objects behave much like <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> objects, except they do not actually implement a test. Instead, they are used to aggregate tests into groups of tests that should be run together. Some additional methods are available to add tests to <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> instances:</p> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestSuite.addTest">
+<code>addTest(test)</code> </dt> <dd>
+<p>Add a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> or <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> to the suite.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestSuite.addTests">
+<code>addTests(tests)</code> </dt> <dd>
+<p>Add all the tests from an iterable of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> and <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> instances to this test suite.</p> <p>This is equivalent to iterating over <em>tests</em>, calling <a class="reference internal" href="#unittest.TestSuite.addTest" title="unittest.TestSuite.addTest"><code>addTest()</code></a> for each element.</p> </dd>
+</dl> <p><a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> shares the following methods with <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a>:</p> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestSuite.run">
+<code>run(result)</code> </dt> <dd>
+<p>Run the tests associated with this suite, collecting the result into the test result object passed as <em>result</em>. Note that unlike <a class="reference internal" href="#unittest.TestCase.run" title="unittest.TestCase.run"><code>TestCase.run()</code></a>, <a class="reference internal" href="#unittest.TestSuite.run" title="unittest.TestSuite.run"><code>TestSuite.run()</code></a> requires the result object to be passed in.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestSuite.debug">
+<code>debug()</code> </dt> <dd>
+<p>Run the tests associated with this suite without collecting the result. This allows exceptions raised by the test to be propagated to the caller and can be used to support running tests under a debugger.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestSuite.countTestCases">
+<code>countTestCases()</code> </dt> <dd>
+<p>Return the number of tests represented by this test object, including all individual tests and sub-suites.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestSuite.__iter__">
+<code>__iter__()</code> </dt> <dd>
+<p>Tests grouped by a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> are always accessed by iteration. Subclasses can lazily provide tests by overriding <code>__iter__()</code>. Note that this method may be called several times on a single suite (for example when counting tests or comparing for equality) so the tests returned by repeated iterations before <a class="reference internal" href="#unittest.TestSuite.run" title="unittest.TestSuite.run"><code>TestSuite.run()</code></a> must be the same for each call iteration. After <a class="reference internal" href="#unittest.TestSuite.run" title="unittest.TestSuite.run"><code>TestSuite.run()</code></a>, callers should not rely on the tests returned by this method unless the caller uses a subclass that overrides <code>TestSuite._removeTestAtIndex()</code> to preserve test references.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>In earlier versions the <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> accessed tests directly rather than through iteration, so overriding <code>__iter__()</code> wasn’t sufficient for providing tests.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>In earlier versions the <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> held references to each <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> after <a class="reference internal" href="#unittest.TestSuite.run" title="unittest.TestSuite.run"><code>TestSuite.run()</code></a>. Subclasses can restore that behavior by overriding <code>TestSuite._removeTestAtIndex()</code>.</p> </div> </dd>
+</dl> <p>In the typical usage of a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> object, the <a class="reference internal" href="#unittest.TestSuite.run" title="unittest.TestSuite.run"><code>run()</code></a> method is invoked by a <code>TestRunner</code> rather than by the end-user test harness.</p> </dd>
+</dl> </section> <section id="loading-and-running-tests"> <h3>Loading and running tests</h3> <dl class="py class"> <dt class="sig sig-object py" id="unittest.TestLoader">
+<code>class unittest.TestLoader</code> </dt> <dd>
+<p>The <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code>TestLoader</code></a> class is used to create test suites from classes and modules. Normally, there is no need to create an instance of this class; the <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> module provides an instance that can be shared as <a class="reference internal" href="#unittest.defaultTestLoader" title="unittest.defaultTestLoader"><code>unittest.defaultTestLoader</code></a>. Using a subclass or instance, however, allows customization of some configurable properties.</p> <p><a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code>TestLoader</code></a> objects have the following attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestLoader.errors">
+<code>errors</code> </dt> <dd>
+<p>A list of the non-fatal errors encountered while loading tests. Not reset by the loader at any point. Fatal errors are signalled by the relevant method raising an exception to the caller. Non-fatal errors are also indicated by a synthetic test that will raise the original error when run.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
+</dl> <p><a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code>TestLoader</code></a> objects have the following methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestLoader.loadTestsFromTestCase">
+<code>loadTestsFromTestCase(testCaseClass)</code> </dt> <dd>
+<p>Return a suite of all test cases contained in the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a>-derived <code>testCaseClass</code>.</p> <p>A test case instance is created for each method named by <a class="reference internal" href="#unittest.TestLoader.getTestCaseNames" title="unittest.TestLoader.getTestCaseNames"><code>getTestCaseNames()</code></a>. By default these are the method names beginning with <code>test</code>. If <a class="reference internal" href="#unittest.TestLoader.getTestCaseNames" title="unittest.TestLoader.getTestCaseNames"><code>getTestCaseNames()</code></a> returns no methods, but the <code>runTest()</code> method is implemented, a single test case is created for that method instead.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestLoader.loadTestsFromModule">
+<code>loadTestsFromModule(module, *, pattern=None)</code> </dt> <dd>
+<p>Return a suite of all test cases contained in the given module. This method searches <em>module</em> for classes derived from <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> and creates an instance of the class for each test method defined for the class.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>While using a hierarchy of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a>-derived classes can be convenient in sharing fixtures and helper functions, defining test methods on base classes that are not intended to be instantiated directly does not play well with this method. Doing so, however, can be useful when the fixtures are different and defined in subclasses.</p> </div> <p>If a module provides a <code>load_tests</code> function it will be called to load the tests. This allows modules to customize test loading. This is the <a class="reference internal" href="#id1">load_tests protocol</a>. The <em>pattern</em> argument is passed as the third argument to <code>load_tests</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Support for <code>load_tests</code> added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Support for a keyword-only argument <em>pattern</em> has been added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The undocumented and unofficial <em>use_load_tests</em> parameter has been removed.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestLoader.loadTestsFromName">
+<code>loadTestsFromName(name, module=None)</code> </dt> <dd>
+<p>Return a suite of all test cases given a string specifier.</p> <p>The specifier <em>name</em> is a “dotted name” that may resolve either to a module, a test case class, a test method within a test case class, a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> instance, or a callable object which returns a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> or <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> instance. These checks are applied in the order listed here; that is, a method on a possible test case class will be picked up as “a test method within a test case class”, rather than “a callable object”.</p> <p>For example, if you have a module <code>SampleTests</code> containing a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a>-derived class <code>SampleTestCase</code> with three test methods (<code>test_one()</code>, <code>test_two()</code>, and <code>test_three()</code>), the specifier <code>'SampleTests.SampleTestCase'</code> would cause this method to return a suite which will run all three test methods. Using the specifier <code>'SampleTests.SampleTestCase.test_two'</code> would cause it to return a test suite which will run only the <code>test_two()</code> test method. The specifier can refer to modules and packages which have not been imported; they will be imported as a side-effect.</p> <p>The method optionally resolves <em>name</em> relative to the given <em>module</em>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>If an <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> or <a class="reference internal" href="exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a> occurs while traversing <em>name</em> then a synthetic test that raises that error when run will be returned. These errors are included in the errors accumulated by self.errors.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestLoader.loadTestsFromNames">
+<code>loadTestsFromNames(names, module=None)</code> </dt> <dd>
+<p>Similar to <a class="reference internal" href="#unittest.TestLoader.loadTestsFromName" title="unittest.TestLoader.loadTestsFromName"><code>loadTestsFromName()</code></a>, but takes a sequence of names rather than a single name. The return value is a test suite which supports all the tests defined for each name.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestLoader.getTestCaseNames">
+<code>getTestCaseNames(testCaseClass)</code> </dt> <dd>
+<p>Return a sorted sequence of method names found within <em>testCaseClass</em>; this should be a subclass of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestLoader.discover">
+<code>discover(start_dir, pattern='test*.py', top_level_dir=None)</code> </dt> <dd>
+<p>Find all the test modules by recursing into subdirectories from the specified start directory, and return a TestSuite object containing them. Only test files that match <em>pattern</em> will be loaded. (Using shell style pattern matching.) Only module names that are importable (i.e. are valid Python identifiers) will be loaded.</p> <p>All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately.</p> <p>If importing a module fails, for example due to a syntax error, then this will be recorded as a single error and discovery will continue. If the import failure is due to <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code>SkipTest</code></a> being raised, it will be recorded as a skip instead of an error.</p> <p>If a package (a directory containing a file named <code>__init__.py</code>) is found, the package will be checked for a <code>load_tests</code> function. If this exists then it will be called <code>package.load_tests(loader, tests, pattern)</code>. Test discovery takes care to ensure that a package is only checked for tests once during an invocation, even if the load_tests function itself calls <code>loader.discover</code>.</p> <p>If <code>load_tests</code> exists then discovery does <em>not</em> recurse into the package, <code>load_tests</code> is responsible for loading all tests in the package.</p> <p>The pattern is deliberately not stored as a loader attribute so that packages can continue discovery themselves. <em>top_level_dir</em> is stored so <code>load_tests</code> does not need to pass this argument in to <code>loader.discover()</code>.</p> <p><em>start_dir</em> can be a dotted module name as well as a directory.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Modules that raise <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code>SkipTest</code></a> on import are recorded as skips, not errors.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span><em>start_dir</em> can be a <a class="reference internal" href="../glossary#term-namespace-package"><span class="xref std std-term">namespace packages</span></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Paths are sorted before being imported so that execution order is the same even if the underlying file system’s ordering is not dependent on file name.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Found packages are now checked for <code>load_tests</code> regardless of whether their path matches <em>pattern</em>, because it is impossible for a package name to match the default pattern.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><em>start_dir</em> can not be a <a class="reference internal" href="../glossary#term-namespace-package"><span class="xref std std-term">namespace packages</span></a>. It has been broken since Python 3.7 and Python 3.11 officially remove it.</p> </div> </dd>
+</dl> <p>The following attributes of a <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code>TestLoader</code></a> can be configured either by subclassing or assignment on an instance:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestLoader.testMethodPrefix">
+<code>testMethodPrefix</code> </dt> <dd>
+<p>String giving the prefix of method names which will be interpreted as test methods. The default value is <code>'test'</code>.</p> <p>This affects <a class="reference internal" href="#unittest.TestLoader.getTestCaseNames" title="unittest.TestLoader.getTestCaseNames"><code>getTestCaseNames()</code></a> and all the <code>loadTestsFrom*</code> methods.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestLoader.sortTestMethodsUsing">
+<code>sortTestMethodsUsing</code> </dt> <dd>
+<p>Function to be used to compare method names when sorting them in <a class="reference internal" href="#unittest.TestLoader.getTestCaseNames" title="unittest.TestLoader.getTestCaseNames"><code>getTestCaseNames()</code></a> and all the <code>loadTestsFrom*</code> methods.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestLoader.suiteClass">
+<code>suiteClass</code> </dt> <dd>
+<p>Callable object that constructs a test suite from a list of tests. No methods on the resulting object are needed. The default value is the <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> class.</p> <p>This affects all the <code>loadTestsFrom*</code> methods.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestLoader.testNamePatterns">
+<code>testNamePatterns</code> </dt> <dd>
+<p>List of Unix shell-style wildcard test name patterns that test methods have to match to be included in test suites (see <code>-k</code> option).</p> <p>If this attribute is not <code>None</code> (the default), all test methods to be included in test suites must match one of the patterns in this list. Note that matches are always performed using <a class="reference internal" href="fnmatch#fnmatch.fnmatchcase" title="fnmatch.fnmatchcase"><code>fnmatch.fnmatchcase()</code></a>, so unlike patterns passed to the <code>-k</code> option, simple substring patterns will have to be converted using <code>*</code> wildcards.</p> <p>This affects all the <code>loadTestsFrom*</code> methods.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="unittest.TestResult">
+<code>class unittest.TestResult</code> </dt> <dd>
+<p>This class is used to compile information about which tests have succeeded and which have failed.</p> <p>A <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> object stores the results of a set of tests. The <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> and <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> classes ensure that results are properly recorded; test authors do not need to worry about recording the outcome of tests.</p> <p>Testing frameworks built on top of <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> may want access to the <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> object generated by running a set of tests for reporting purposes; a <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> instance is returned by the <code>TestRunner.run()</code> method for this purpose.</p> <p><a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> instances have the following attributes that will be of interest when inspecting the results of running a set of tests:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.errors">
+<code>errors</code> </dt> <dd>
+<p>A list containing 2-tuples of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instances and strings holding formatted tracebacks. Each tuple represents a test which raised an unexpected exception.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.failures">
+<code>failures</code> </dt> <dd>
+<p>A list containing 2-tuples of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instances and strings holding formatted tracebacks. Each tuple represents a test where a failure was explicitly signalled using the <a class="reference internal" href="#assert-methods"><span class="std std-ref">assert* methods</span></a>.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.skipped">
+<code>skipped</code> </dt> <dd>
+<p>A list containing 2-tuples of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instances and strings holding the reason for skipping the test.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.expectedFailures">
+<code>expectedFailures</code> </dt> <dd>
+<p>A list containing 2-tuples of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instances and strings holding formatted tracebacks. Each tuple represents an expected failure or error of the test case.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.unexpectedSuccesses">
+<code>unexpectedSuccesses</code> </dt> <dd>
+<p>A list containing <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instances that were marked as expected failures, but succeeded.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.collectedDurations">
+<code>collectedDurations</code> </dt> <dd>
+<p>A list containing 2-tuples of test case names and floats representing the elapsed time of each test which was run.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.shouldStop">
+<code>shouldStop</code> </dt> <dd>
+<p>Set to <code>True</code> when the execution of tests should stop by <a class="reference internal" href="#unittest.TestResult.stop" title="unittest.TestResult.stop"><code>stop()</code></a>.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.testsRun">
+<code>testsRun</code> </dt> <dd>
+<p>The total number of tests run so far.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.buffer">
+<code>buffer</code> </dt> <dd>
+<p>If set to true, <code>sys.stdout</code> and <code>sys.stderr</code> will be buffered in between <a class="reference internal" href="#unittest.TestResult.startTest" title="unittest.TestResult.startTest"><code>startTest()</code></a> and <a class="reference internal" href="#unittest.TestResult.stopTest" title="unittest.TestResult.stopTest"><code>stopTest()</code></a> being called. Collected output will only be echoed onto the real <code>sys.stdout</code> and <code>sys.stderr</code> if the test fails or errors. Any output is also attached to the failure / error message.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.failfast">
+<code>failfast</code> </dt> <dd>
+<p>If set to true <a class="reference internal" href="#unittest.TestResult.stop" title="unittest.TestResult.stop"><code>stop()</code></a> will be called on the first failure or error, halting the test run.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="unittest.TestResult.tb_locals">
+<code>tb_locals</code> </dt> <dd>
+<p>If set to true then local variables will be shown in tracebacks.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.wasSuccessful">
+<code>wasSuccessful()</code> </dt> <dd>
+<p>Return <code>True</code> if all tests run so far have passed, otherwise returns <code>False</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Returns <code>False</code> if there were any <a class="reference internal" href="#unittest.TestResult.unexpectedSuccesses" title="unittest.TestResult.unexpectedSuccesses"><code>unexpectedSuccesses</code></a> from tests marked with the <a class="reference internal" href="#unittest.expectedFailure" title="unittest.expectedFailure"><code>expectedFailure()</code></a> decorator.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.stop">
+<code>stop()</code> </dt> <dd>
+<p>This method can be called to signal that the set of tests being run should be aborted by setting the <a class="reference internal" href="#unittest.TestResult.shouldStop" title="unittest.TestResult.shouldStop"><code>shouldStop</code></a> attribute to <code>True</code>. <code>TestRunner</code> objects should respect this flag and return without running any additional tests.</p> <p>For example, this feature is used by the <a class="reference internal" href="#unittest.TextTestRunner" title="unittest.TextTestRunner"><code>TextTestRunner</code></a> class to stop the test framework when the user signals an interrupt from the keyboard. Interactive tools which provide <code>TestRunner</code> implementations can use this in a similar manner.</p> </dd>
+</dl> <p>The following methods of the <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> class are used to maintain the internal data structures, and may be extended in subclasses to support additional reporting requirements. This is particularly useful in building tools which support interactive reporting while tests are being run.</p> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.startTest">
+<code>startTest(test)</code> </dt> <dd>
+<p>Called when the test case <em>test</em> is about to be run.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.stopTest">
+<code>stopTest(test)</code> </dt> <dd>
+<p>Called after the test case <em>test</em> has been executed, regardless of the outcome.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.startTestRun">
+<code>startTestRun()</code> </dt> <dd>
+<p>Called once before any tests are executed.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.stopTestRun">
+<code>stopTestRun()</code> </dt> <dd>
+<p>Called once after all tests are executed.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.addError">
+<code>addError(test, err)</code> </dt> <dd>
+<p>Called when the test case <em>test</em> raises an unexpected exception. <em>err</em> is a tuple of the form returned by <a class="reference internal" href="sys#sys.exc_info" title="sys.exc_info"><code>sys.exc_info()</code></a>: <code>(type, value,
+traceback)</code>.</p> <p>The default implementation appends a tuple <code>(test, formatted_err)</code> to the instance’s <a class="reference internal" href="#unittest.TestResult.errors" title="unittest.TestResult.errors"><code>errors</code></a> attribute, where <em>formatted_err</em> is a formatted traceback derived from <em>err</em>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.addFailure">
+<code>addFailure(test, err)</code> </dt> <dd>
+<p>Called when the test case <em>test</em> signals a failure. <em>err</em> is a tuple of the form returned by <a class="reference internal" href="sys#sys.exc_info" title="sys.exc_info"><code>sys.exc_info()</code></a>: <code>(type, value, traceback)</code>.</p> <p>The default implementation appends a tuple <code>(test, formatted_err)</code> to the instance’s <a class="reference internal" href="#unittest.TestResult.failures" title="unittest.TestResult.failures"><code>failures</code></a> attribute, where <em>formatted_err</em> is a formatted traceback derived from <em>err</em>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.addSuccess">
+<code>addSuccess(test)</code> </dt> <dd>
+<p>Called when the test case <em>test</em> succeeds.</p> <p>The default implementation does nothing.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.addSkip">
+<code>addSkip(test, reason)</code> </dt> <dd>
+<p>Called when the test case <em>test</em> is skipped. <em>reason</em> is the reason the test gave for skipping.</p> <p>The default implementation appends a tuple <code>(test, reason)</code> to the instance’s <a class="reference internal" href="#unittest.TestResult.skipped" title="unittest.TestResult.skipped"><code>skipped</code></a> attribute.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.addExpectedFailure">
+<code>addExpectedFailure(test, err)</code> </dt> <dd>
+<p>Called when the test case <em>test</em> fails or errors, but was marked with the <a class="reference internal" href="#unittest.expectedFailure" title="unittest.expectedFailure"><code>expectedFailure()</code></a> decorator.</p> <p>The default implementation appends a tuple <code>(test, formatted_err)</code> to the instance’s <a class="reference internal" href="#unittest.TestResult.expectedFailures" title="unittest.TestResult.expectedFailures"><code>expectedFailures</code></a> attribute, where <em>formatted_err</em> is a formatted traceback derived from <em>err</em>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.addUnexpectedSuccess">
+<code>addUnexpectedSuccess(test)</code> </dt> <dd>
+<p>Called when the test case <em>test</em> was marked with the <a class="reference internal" href="#unittest.expectedFailure" title="unittest.expectedFailure"><code>expectedFailure()</code></a> decorator, but succeeded.</p> <p>The default implementation appends the test to the instance’s <a class="reference internal" href="#unittest.TestResult.unexpectedSuccesses" title="unittest.TestResult.unexpectedSuccesses"><code>unexpectedSuccesses</code></a> attribute.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.addSubTest">
+<code>addSubTest(test, subtest, outcome)</code> </dt> <dd>
+<p>Called when a subtest finishes. <em>test</em> is the test case corresponding to the test method. <em>subtest</em> is a custom <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instance describing the subtest.</p> <p>If <em>outcome</em> is <a class="reference internal" href="constants#None" title="None"><code>None</code></a>, the subtest succeeded. Otherwise, it failed with an exception where <em>outcome</em> is a tuple of the form returned by <a class="reference internal" href="sys#sys.exc_info" title="sys.exc_info"><code>sys.exc_info()</code></a>: <code>(type, value, traceback)</code>.</p> <p>The default implementation does nothing when the outcome is a success, and records subtest failures as normal failures.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TestResult.addDuration">
+<code>addDuration(test, elapsed)</code> </dt> <dd>
+<p>Called when the test case finishes. <em>elapsed</em> is the time represented in seconds, and it includes the execution of cleanup functions.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
+</dl> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="unittest.TextTestResult">
+<code>class unittest.TextTestResult(stream, descriptions, verbosity, *, durations=None)</code> </dt> <dd>
+<p>A concrete implementation of <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> used by the <a class="reference internal" href="#unittest.TextTestRunner" title="unittest.TextTestRunner"><code>TextTestRunner</code></a>. Subclasses should accept <code>**kwargs</code> to ensure compatibility as the interface changes.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12: </span>Added <em>durations</em> keyword argument.</p> </div> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="unittest.defaultTestLoader">
+<code>unittest.defaultTestLoader</code> </dt> <dd>
+<p>Instance of the <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code>TestLoader</code></a> class intended to be shared. If no customization of the <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code>TestLoader</code></a> is needed, this instance can be used instead of repeatedly creating new instances.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="unittest.TextTestRunner">
+<code>class unittest.TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None, warnings=None, *, tb_locals=False, durations=None)</code> </dt> <dd>
+<p>A basic test runner implementation that outputs results to a stream. If <em>stream</em> is <code>None</code>, the default, <a class="reference internal" href="sys#sys.stderr" title="sys.stderr"><code>sys.stderr</code></a> is used as the output stream. This class has a few configurable parameters, but is essentially very simple. Graphical applications which run test suites should provide alternate implementations. Such implementations should accept <code>**kwargs</code> as the interface to construct runners changes when features are added to unittest.</p> <p>By default this runner shows <a class="reference internal" href="exceptions#DeprecationWarning" title="DeprecationWarning"><code>DeprecationWarning</code></a>, <a class="reference internal" href="exceptions#PendingDeprecationWarning" title="PendingDeprecationWarning"><code>PendingDeprecationWarning</code></a>, <a class="reference internal" href="exceptions#ResourceWarning" title="ResourceWarning"><code>ResourceWarning</code></a> and <a class="reference internal" href="exceptions#ImportWarning" title="ImportWarning"><code>ImportWarning</code></a> even if they are <a class="reference internal" href="warnings#warning-ignored"><span class="std std-ref">ignored by default</span></a>. This behavior can be overridden using Python’s <code>-Wd</code> or <code>-Wa</code> options (see <a class="reference internal" href="../using/cmdline#using-on-warnings"><span class="std std-ref">Warning control</span></a>) and leaving <em>warnings</em> to <code>None</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Added the <em>warnings</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The default stream is set to <a class="reference internal" href="sys#sys.stderr" title="sys.stderr"><code>sys.stderr</code></a> at instantiation time rather than import time.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Added the <em>tb_locals</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added the <em>durations</em> parameter.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TextTestRunner._makeResult">
+<code>_makeResult()</code> </dt> <dd>
+<p>This method returns the instance of <code>TestResult</code> used by <a class="reference internal" href="#unittest.TextTestRunner.run" title="unittest.TextTestRunner.run"><code>run()</code></a>. It is not intended to be called directly, but can be overridden in subclasses to provide a custom <code>TestResult</code>.</p> <p><code>_makeResult()</code> instantiates the class or callable passed in the <code>TextTestRunner</code> constructor as the <code>resultclass</code> argument. It defaults to <a class="reference internal" href="#unittest.TextTestResult" title="unittest.TextTestResult"><code>TextTestResult</code></a> if no <code>resultclass</code> is provided. The result class is instantiated with the following arguments:</p> <pre data-language="python">stream, descriptions, verbosity
+</pre> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.TextTestRunner.run">
+<code>run(test)</code> </dt> <dd>
+<p>This method is the main public interface to the <code>TextTestRunner</code>. This method takes a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> or <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> instance. A <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> is created by calling <a class="reference internal" href="#unittest.TextTestRunner._makeResult" title="unittest.TextTestRunner._makeResult"><code>_makeResult()</code></a> and the test(s) are run and the results printed to stdout.</p> </dd>
+</dl> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="unittest.main">
+<code>unittest.main(module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None, warnings=None)</code> </dt> <dd>
+<p>A command-line program that loads a set of tests from <em>module</em> 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 the end of a test script:</p> <pre data-language="python">if __name__ == '__main__':
+ unittest.main()
+</pre> <p>You can run tests with more detailed information by passing in the verbosity argument:</p> <pre data-language="python">if __name__ == '__main__':
+ unittest.main(verbosity=2)
+</pre> <p>The <em>defaultTest</em> argument is either the name of a single test or an iterable of test names to run if no test names are specified via <em>argv</em>. If not specified or <code>None</code> and no test names are provided via <em>argv</em>, all tests found in <em>module</em> are run.</p> <p>The <em>argv</em> argument can be a list of options passed to the program, with the first element being the program name. If not specified or <code>None</code>, the values of <a class="reference internal" href="sys#sys.argv" title="sys.argv"><code>sys.argv</code></a> are used.</p> <p>The <em>testRunner</em> argument can either be a test runner class or an already created instance of it. By default <code>main</code> calls <a class="reference internal" href="sys#sys.exit" title="sys.exit"><code>sys.exit()</code></a> with an exit code indicating success (0) or failure (1) of the tests run. An exit code of 5 indicates that no tests were run.</p> <p>The <em>testLoader</em> argument has to be a <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code>TestLoader</code></a> instance, and defaults to <a class="reference internal" href="#unittest.defaultTestLoader" title="unittest.defaultTestLoader"><code>defaultTestLoader</code></a>.</p> <p><code>main</code> supports being used from the interactive interpreter by passing in the argument <code>exit=False</code>. This displays the result on standard output without calling <a class="reference internal" href="sys#sys.exit" title="sys.exit"><code>sys.exit()</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; from unittest import main
+&gt;&gt;&gt; main(module='test_module', exit=False)
+</pre> <p>The <em>failfast</em>, <em>catchbreak</em> and <em>buffer</em> parameters have the same effect as the same-name <a class="reference internal" href="#command-line-options">command-line options</a>.</p> <p>The <em>warnings</em> argument specifies the <a class="reference internal" href="warnings#warning-filter"><span class="std std-ref">warning filter</span></a> that should be used while running the tests. If it’s not specified, it will remain <code>None</code> if a <code>-W</code> option is passed to <strong class="program">python</strong> (see <a class="reference internal" href="../using/cmdline#using-on-warnings"><span class="std std-ref">Warning control</span></a>), otherwise it will be set to <code>'default'</code>.</p> <p>Calling <code>main</code> actually returns an instance of the <code>TestProgram</code> class. This stores the result of the tests run as the <code>result</code> attribute.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span>The <em>exit</em> parameter was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The <em>verbosity</em>, <em>failfast</em>, <em>catchbreak</em>, <em>buffer</em> and <em>warnings</em> parameters were added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The <em>defaultTest</em> parameter was changed to also accept an iterable of test names.</p> </div> </dd>
+</dl> <section id="load-tests-protocol"> <span id="id1"></span><h4>load_tests Protocol</h4> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <p>Modules or packages can customize how tests are loaded from them during normal test runs or test discovery by implementing a function called <code>load_tests</code>.</p> <p>If a test module defines <code>load_tests</code> it will be called by <a class="reference internal" href="#unittest.TestLoader.loadTestsFromModule" title="unittest.TestLoader.loadTestsFromModule"><code>TestLoader.loadTestsFromModule()</code></a> with the following arguments:</p> <pre data-language="python">load_tests(loader, standard_tests, pattern)
+</pre> <p>where <em>pattern</em> is passed straight through from <code>loadTestsFromModule</code>. It defaults to <code>None</code>.</p> <p>It should return a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a>.</p> <p><em>loader</em> is the instance of <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code>TestLoader</code></a> doing the loading. <em>standard_tests</em> are the tests that would be loaded by default from the module. It is common for test modules to only want to add or remove tests from the standard set of tests. The third argument is used when loading packages as part of test discovery.</p> <p>A typical <code>load_tests</code> function that loads tests from a specific set of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> classes may look like:</p> <pre data-language="python">test_cases = (TestCase1, TestCase2, TestCase3)
+
+def load_tests(loader, tests, pattern):
+ suite = TestSuite()
+ for test_class in test_cases:
+ tests = loader.loadTestsFromTestCase(test_class)
+ suite.addTests(tests)
+ return suite
+</pre> <p>If discovery is started in a directory containing a package, either from the command line or by calling <a class="reference internal" href="#unittest.TestLoader.discover" title="unittest.TestLoader.discover"><code>TestLoader.discover()</code></a>, then the package <code>__init__.py</code> will be checked for <code>load_tests</code>. If that function does not exist, discovery will recurse into the package as though it were just another directory. Otherwise, discovery of the package’s tests will be left up to <code>load_tests</code> which is called with the following arguments:</p> <pre data-language="python">load_tests(loader, standard_tests, pattern)
+</pre> <p>This should return a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a> representing all the tests from the package. (<code>standard_tests</code> will only contain tests collected from <code>__init__.py</code>.)</p> <p>Because the pattern is passed into <code>load_tests</code> the package is free to continue (and potentially modify) test discovery. A ‘do nothing’ <code>load_tests</code> function for a test package would look like:</p> <pre data-language="python">def load_tests(loader, standard_tests, pattern):
+ # top level directory cached on loader instance
+ this_dir = os.path.dirname(__file__)
+ package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
+ standard_tests.addTests(package_tests)
+ return standard_tests
+</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Discovery no longer checks package names for matching <em>pattern</em> due to the impossibility of package names matching the default pattern.</p> </div> </section> </section> </section> <section id="class-and-module-fixtures"> <h2>Class and Module Fixtures</h2> <p>Class and module level fixtures are implemented in <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code>TestSuite</code></a>. When the test suite encounters a test from a new class then <code>tearDownClass()</code> from the previous class (if there is one) is called, followed by <code>setUpClass()</code> from the new class.</p> <p>Similarly if a test is from a different module from the previous test then <code>tearDownModule</code> from the previous module is run, followed by <code>setUpModule</code> from the new module.</p> <p>After all the tests have run the final <code>tearDownClass</code> and <code>tearDownModule</code> are run.</p> <p>Note that shared fixtures do not play well with [potential] features like test parallelization and they break test isolation. They should be used with care.</p> <p>The default ordering of tests created by the unittest test loaders is to group all tests from the same modules and classes together. This will lead to <code>setUpClass</code> / <code>setUpModule</code> (etc) being called exactly once per class and module. If you randomize the order, so that tests from different modules and classes are adjacent to each other, then these shared fixture functions may be called multiple times in a single test run.</p> <p>Shared fixtures are not intended to work with suites with non-standard ordering. A <code>BaseTestSuite</code> still exists for frameworks that don’t want to support shared fixtures.</p> <p>If there are any exceptions raised during one of the shared fixture functions the test is reported as an error. Because there is no corresponding test instance an <code>_ErrorHolder</code> object (that has the same interface as a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a>) is created to represent the error. If you are just using the standard unittest test runner then this detail doesn’t matter, but if you are a framework author it may be relevant.</p> <section id="setupclass-and-teardownclass"> <h3>setUpClass and tearDownClass</h3> <p>These must be implemented as class methods:</p> <pre data-language="python">import unittest
+
+class Test(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls._connection = createExpensiveConnectionObject()
+
+ @classmethod
+ def tearDownClass(cls):
+ cls._connection.destroy()
+</pre> <p>If you want the <code>setUpClass</code> and <code>tearDownClass</code> on base classes called then you must call up to them yourself. The implementations in <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code>TestCase</code></a> are empty.</p> <p>If an exception is raised during a <code>setUpClass</code> then the tests in the class are not run and the <code>tearDownClass</code> is not run. Skipped classes will not have <code>setUpClass</code> or <code>tearDownClass</code> run. If the exception is a <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code>SkipTest</code></a> exception then the class will be reported as having been skipped instead of as an error.</p> </section> <section id="setupmodule-and-teardownmodule"> <h3>setUpModule and tearDownModule</h3> <p>These should be implemented as functions:</p> <pre data-language="python">def setUpModule():
+ createConnection()
+
+def tearDownModule():
+ closeConnection()
+</pre> <p>If an exception is raised in a <code>setUpModule</code> then none of the tests in the module will be run and the <code>tearDownModule</code> will not be run. If the exception is a <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code>SkipTest</code></a> exception then the module will be reported as having been skipped instead of as an error.</p> <p>To add cleanup code that must be run even in the case of an exception, use <code>addModuleCleanup</code>:</p> <dl class="py function"> <dt class="sig sig-object py" id="unittest.addModuleCleanup">
+<code>unittest.addModuleCleanup(function, /, *args, **kwargs)</code> </dt> <dd>
+<p>Add a function to be called after <code>tearDownModule()</code> to cleanup resources used during the test class. Functions will be called in reverse order to the order they are added (<abbr title="last-in, first-out">LIFO</abbr>). They are called with any arguments and keyword arguments passed into <a class="reference internal" href="#unittest.addModuleCleanup" title="unittest.addModuleCleanup"><code>addModuleCleanup()</code></a> when they are added.</p> <p>If <code>setUpModule()</code> fails, meaning that <code>tearDownModule()</code> is not called, then any cleanup functions added will still be called.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="unittest.enterModuleContext">
+<code>classmethod unittest.enterModuleContext(cm)</code> </dt> <dd>
+<p>Enter the supplied <a class="reference internal" href="../glossary#term-context-manager"><span class="xref std std-term">context manager</span></a>. If successful, also add its <a class="reference internal" href="../reference/datamodel#object.__exit__" title="object.__exit__"><code>__exit__()</code></a> method as a cleanup function by <a class="reference internal" href="#unittest.addModuleCleanup" title="unittest.addModuleCleanup"><code>addModuleCleanup()</code></a> and return the result of the <a class="reference internal" href="../reference/datamodel#object.__enter__" title="object.__enter__"><code>__enter__()</code></a> method.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="unittest.doModuleCleanups">
+<code>unittest.doModuleCleanups()</code> </dt> <dd>
+<p>This function is called unconditionally after <code>tearDownModule()</code>, or after <code>setUpModule()</code> if <code>setUpModule()</code> raises an exception.</p> <p>It is responsible for calling all the cleanup functions added by <a class="reference internal" href="#unittest.addModuleCleanup" title="unittest.addModuleCleanup"><code>addModuleCleanup()</code></a>. If you need cleanup functions to be called <em>prior</em> to <code>tearDownModule()</code> then you can call <a class="reference internal" href="#unittest.doModuleCleanups" title="unittest.doModuleCleanups"><code>doModuleCleanups()</code></a> yourself.</p> <p><a class="reference internal" href="#unittest.doModuleCleanups" title="unittest.doModuleCleanups"><code>doModuleCleanups()</code></a> pops methods off the stack of cleanup functions one at a time, so it can be called at any time.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> </section> </section> <section id="signal-handling"> <h2>Signal Handling</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <p>The <a class="reference internal" href="#cmdoption-unittest-c"><code>-c/--catch</code></a> command-line option to unittest, along with the <code>catchbreak</code> parameter to <a class="reference internal" href="#unittest.main" title="unittest.main"><code>unittest.main()</code></a>, provide more friendly handling of control-C during a test run. With catch break behavior 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 second control-c will raise a <a class="reference internal" href="exceptions#KeyboardInterrupt" title="KeyboardInterrupt"><code>KeyboardInterrupt</code></a> in the usual way.</p> <p>The control-c handling signal handler attempts to remain compatible with code or tests that install their own <a class="reference internal" href="signal#signal.SIGINT" title="signal.SIGINT"><code>signal.SIGINT</code></a> handler. If the <code>unittest</code> handler is called but <em>isn’t</em> the installed <a class="reference internal" href="signal#signal.SIGINT" title="signal.SIGINT"><code>signal.SIGINT</code></a> handler, i.e. it has been replaced by the system under test and delegated to, then it calls the default handler. This will normally be the expected behavior by code that replaces an installed handler and delegates to it. For individual tests that need <code>unittest</code> control-c handling disabled the <a class="reference internal" href="#unittest.removeHandler" title="unittest.removeHandler"><code>removeHandler()</code></a> decorator can be used.</p> <p>There are a few utility functions for framework authors to enable control-c handling functionality within test frameworks.</p> <dl class="py function"> <dt class="sig sig-object py" id="unittest.installHandler">
+<code>unittest.installHandler()</code> </dt> <dd>
+<p>Install the control-c handler. When a <a class="reference internal" href="signal#signal.SIGINT" title="signal.SIGINT"><code>signal.SIGINT</code></a> is received (usually in response to the user pressing control-c) all registered results have <a class="reference internal" href="#unittest.TestResult.stop" title="unittest.TestResult.stop"><code>stop()</code></a> called.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="unittest.registerResult">
+<code>unittest.registerResult(result)</code> </dt> <dd>
+<p>Register a <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> object for control-c handling. Registering a result stores a weak reference to it, so it doesn’t prevent the result from being garbage collected.</p> <p>Registering a <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code>TestResult</code></a> object has no side-effects if control-c handling is not enabled, so test frameworks can unconditionally register all results they create independently of whether or not handling is enabled.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="unittest.removeResult">
+<code>unittest.removeResult(result)</code> </dt> <dd>
+<p>Remove a registered result. Once a result has been removed then <a class="reference internal" href="#unittest.TestResult.stop" title="unittest.TestResult.stop"><code>stop()</code></a> will no longer be called on that result object in response to a control-c.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="unittest.removeHandler">
+<code>unittest.removeHandler(function=None)</code> </dt> <dd>
+<p>When called without arguments this function removes the control-c handler if it has been installed. This function can also be used as a test decorator to temporarily remove the handler while the test is being executed:</p> <pre data-language="python">@unittest.removeHandler
+def test_signal_handling(self):
+ ...
+</pre> </dd>
+</dl> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/library/unittest.html" class="_attribution-link">https://docs.python.org/3.12/library/unittest.html</a>
+ </p>
+</div>