17db96d56Sopenharmony_ci:mod:`unittest` --- Unit testing framework 27db96d56Sopenharmony_ci========================================== 37db96d56Sopenharmony_ci 47db96d56Sopenharmony_ci.. module:: unittest 57db96d56Sopenharmony_ci :synopsis: Unit testing framework for Python. 67db96d56Sopenharmony_ci 77db96d56Sopenharmony_ci.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com> 87db96d56Sopenharmony_ci.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com> 97db96d56Sopenharmony_ci.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> 107db96d56Sopenharmony_ci.. sectionauthor:: Raymond Hettinger <python@rcn.com> 117db96d56Sopenharmony_ci 127db96d56Sopenharmony_ci**Source code:** :source:`Lib/unittest/__init__.py` 137db96d56Sopenharmony_ci 147db96d56Sopenharmony_ci-------------- 157db96d56Sopenharmony_ci 167db96d56Sopenharmony_ci(If you are already familiar with the basic concepts of testing, you might want 177db96d56Sopenharmony_cito skip to :ref:`the list of assert methods <assert-methods>`.) 187db96d56Sopenharmony_ci 197db96d56Sopenharmony_ciThe :mod:`unittest` unit testing framework was originally inspired by JUnit 207db96d56Sopenharmony_ciand has a similar flavor as major unit testing frameworks in other 217db96d56Sopenharmony_cilanguages. It supports test automation, sharing of setup and shutdown code 227db96d56Sopenharmony_cifor tests, aggregation of tests into collections, and independence of the 237db96d56Sopenharmony_citests from the reporting framework. 247db96d56Sopenharmony_ci 257db96d56Sopenharmony_ciTo achieve this, :mod:`unittest` supports some important concepts in an 267db96d56Sopenharmony_ciobject-oriented way: 277db96d56Sopenharmony_ci 287db96d56Sopenharmony_citest fixture 297db96d56Sopenharmony_ci A :dfn:`test fixture` represents the preparation needed to perform one or more 307db96d56Sopenharmony_ci tests, and any associated cleanup actions. This may involve, for example, 317db96d56Sopenharmony_ci creating temporary or proxy databases, directories, or starting a server 327db96d56Sopenharmony_ci process. 337db96d56Sopenharmony_ci 347db96d56Sopenharmony_citest case 357db96d56Sopenharmony_ci A :dfn:`test case` is the individual unit of testing. It checks for a specific 367db96d56Sopenharmony_ci response to a particular set of inputs. :mod:`unittest` provides a base class, 377db96d56Sopenharmony_ci :class:`TestCase`, which may be used to create new test cases. 387db96d56Sopenharmony_ci 397db96d56Sopenharmony_citest suite 407db96d56Sopenharmony_ci A :dfn:`test suite` is a collection of test cases, test suites, or both. It is 417db96d56Sopenharmony_ci used to aggregate tests that should be executed together. 427db96d56Sopenharmony_ci 437db96d56Sopenharmony_citest runner 447db96d56Sopenharmony_ci A :dfn:`test runner` is a component which orchestrates the execution of tests 457db96d56Sopenharmony_ci and provides the outcome to the user. The runner may use a graphical interface, 467db96d56Sopenharmony_ci a textual interface, or return a special value to indicate the results of 477db96d56Sopenharmony_ci executing the tests. 487db96d56Sopenharmony_ci 497db96d56Sopenharmony_ci 507db96d56Sopenharmony_ci.. seealso:: 517db96d56Sopenharmony_ci 527db96d56Sopenharmony_ci Module :mod:`doctest` 537db96d56Sopenharmony_ci Another test-support module with a very different flavor. 547db96d56Sopenharmony_ci 557db96d56Sopenharmony_ci `Simple Smalltalk Testing: With Patterns <https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm>`_ 567db96d56Sopenharmony_ci Kent Beck's original paper on testing frameworks using the pattern shared 577db96d56Sopenharmony_ci by :mod:`unittest`. 587db96d56Sopenharmony_ci 597db96d56Sopenharmony_ci `pytest <https://docs.pytest.org/>`_ 607db96d56Sopenharmony_ci Third-party unittest framework with a lighter-weight syntax for writing 617db96d56Sopenharmony_ci tests. For example, ``assert func(10) == 42``. 627db96d56Sopenharmony_ci 637db96d56Sopenharmony_ci `The Python Testing Tools Taxonomy <https://wiki.python.org/moin/PythonTestingToolsTaxonomy>`_ 647db96d56Sopenharmony_ci An extensive list of Python testing tools including functional testing 657db96d56Sopenharmony_ci frameworks and mock object libraries. 667db96d56Sopenharmony_ci 677db96d56Sopenharmony_ci `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_ 687db96d56Sopenharmony_ci A special-interest-group for discussion of testing, and testing tools, 697db96d56Sopenharmony_ci in Python. 707db96d56Sopenharmony_ci 717db96d56Sopenharmony_ci The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is 727db96d56Sopenharmony_ci a GUI tool for test discovery and execution. This is intended largely for ease of use 737db96d56Sopenharmony_ci for those new to unit testing. For production environments it is 747db96d56Sopenharmony_ci recommended that tests be driven by a continuous integration system such as 757db96d56Sopenharmony_ci `Buildbot <https://buildbot.net/>`_, `Jenkins <https://www.jenkins.io/>`_, 767db96d56Sopenharmony_ci `GitHub Actions <https://github.com/features/actions>`_, or 777db96d56Sopenharmony_ci `AppVeyor <https://www.appveyor.com/>`_. 787db96d56Sopenharmony_ci 797db96d56Sopenharmony_ci 807db96d56Sopenharmony_ci.. _unittest-minimal-example: 817db96d56Sopenharmony_ci 827db96d56Sopenharmony_ciBasic example 837db96d56Sopenharmony_ci------------- 847db96d56Sopenharmony_ci 857db96d56Sopenharmony_ciThe :mod:`unittest` module provides a rich set of tools for constructing and 867db96d56Sopenharmony_cirunning tests. This section demonstrates that a small subset of the tools 877db96d56Sopenharmony_cisuffice to meet the needs of most users. 887db96d56Sopenharmony_ci 897db96d56Sopenharmony_ciHere is a short script to test three string methods:: 907db96d56Sopenharmony_ci 917db96d56Sopenharmony_ci import unittest 927db96d56Sopenharmony_ci 937db96d56Sopenharmony_ci class TestStringMethods(unittest.TestCase): 947db96d56Sopenharmony_ci 957db96d56Sopenharmony_ci def test_upper(self): 967db96d56Sopenharmony_ci self.assertEqual('foo'.upper(), 'FOO') 977db96d56Sopenharmony_ci 987db96d56Sopenharmony_ci def test_isupper(self): 997db96d56Sopenharmony_ci self.assertTrue('FOO'.isupper()) 1007db96d56Sopenharmony_ci self.assertFalse('Foo'.isupper()) 1017db96d56Sopenharmony_ci 1027db96d56Sopenharmony_ci def test_split(self): 1037db96d56Sopenharmony_ci s = 'hello world' 1047db96d56Sopenharmony_ci self.assertEqual(s.split(), ['hello', 'world']) 1057db96d56Sopenharmony_ci # check that s.split fails when the separator is not a string 1067db96d56Sopenharmony_ci with self.assertRaises(TypeError): 1077db96d56Sopenharmony_ci s.split(2) 1087db96d56Sopenharmony_ci 1097db96d56Sopenharmony_ci if __name__ == '__main__': 1107db96d56Sopenharmony_ci unittest.main() 1117db96d56Sopenharmony_ci 1127db96d56Sopenharmony_ci 1137db96d56Sopenharmony_ciA testcase is created by subclassing :class:`unittest.TestCase`. The three 1147db96d56Sopenharmony_ciindividual tests are defined with methods whose names start with the letters 1157db96d56Sopenharmony_ci``test``. This naming convention informs the test runner about which methods 1167db96d56Sopenharmony_cirepresent tests. 1177db96d56Sopenharmony_ci 1187db96d56Sopenharmony_ciThe crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an 1197db96d56Sopenharmony_ciexpected result; :meth:`~TestCase.assertTrue` or :meth:`~TestCase.assertFalse` 1207db96d56Sopenharmony_cito verify a condition; or :meth:`~TestCase.assertRaises` to verify that a 1217db96d56Sopenharmony_cispecific exception gets raised. These methods are used instead of the 1227db96d56Sopenharmony_ci:keyword:`assert` statement so the test runner can accumulate all test results 1237db96d56Sopenharmony_ciand produce a report. 1247db96d56Sopenharmony_ci 1257db96d56Sopenharmony_ciThe :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you 1267db96d56Sopenharmony_cito define instructions that will be executed before and after each test method. 1277db96d56Sopenharmony_ciThey are covered in more detail in the section :ref:`organizing-tests`. 1287db96d56Sopenharmony_ci 1297db96d56Sopenharmony_ciThe final block shows a simple way to run the tests. :func:`unittest.main` 1307db96d56Sopenharmony_ciprovides a command-line interface to the test script. When run from the command 1317db96d56Sopenharmony_ciline, the above script produces an output that looks like this:: 1327db96d56Sopenharmony_ci 1337db96d56Sopenharmony_ci ... 1347db96d56Sopenharmony_ci ---------------------------------------------------------------------- 1357db96d56Sopenharmony_ci Ran 3 tests in 0.000s 1367db96d56Sopenharmony_ci 1377db96d56Sopenharmony_ci OK 1387db96d56Sopenharmony_ci 1397db96d56Sopenharmony_ciPassing the ``-v`` option to your test script will instruct :func:`unittest.main` 1407db96d56Sopenharmony_cito enable a higher level of verbosity, and produce the following output:: 1417db96d56Sopenharmony_ci 1427db96d56Sopenharmony_ci test_isupper (__main__.TestStringMethods.test_isupper) ... ok 1437db96d56Sopenharmony_ci test_split (__main__.TestStringMethods.test_split) ... ok 1447db96d56Sopenharmony_ci test_upper (__main__.TestStringMethods.test_upper) ... ok 1457db96d56Sopenharmony_ci 1467db96d56Sopenharmony_ci ---------------------------------------------------------------------- 1477db96d56Sopenharmony_ci Ran 3 tests in 0.001s 1487db96d56Sopenharmony_ci 1497db96d56Sopenharmony_ci OK 1507db96d56Sopenharmony_ci 1517db96d56Sopenharmony_ciThe above examples show the most commonly used :mod:`unittest` features which 1527db96d56Sopenharmony_ciare sufficient to meet many everyday testing needs. The remainder of the 1537db96d56Sopenharmony_cidocumentation explores the full feature set from first principles. 1547db96d56Sopenharmony_ci 1557db96d56Sopenharmony_ci.. versionchanged:: 3.11 1567db96d56Sopenharmony_ci The behavior of returning a value from a test method (other than the default 1577db96d56Sopenharmony_ci ``None`` value), is now deprecated. 1587db96d56Sopenharmony_ci 1597db96d56Sopenharmony_ci 1607db96d56Sopenharmony_ci.. _unittest-command-line-interface: 1617db96d56Sopenharmony_ci 1627db96d56Sopenharmony_ciCommand-Line Interface 1637db96d56Sopenharmony_ci---------------------- 1647db96d56Sopenharmony_ci 1657db96d56Sopenharmony_ciThe unittest module can be used from the command line to run tests from 1667db96d56Sopenharmony_cimodules, classes or even individual test methods:: 1677db96d56Sopenharmony_ci 1687db96d56Sopenharmony_ci python -m unittest test_module1 test_module2 1697db96d56Sopenharmony_ci python -m unittest test_module.TestClass 1707db96d56Sopenharmony_ci python -m unittest test_module.TestClass.test_method 1717db96d56Sopenharmony_ci 1727db96d56Sopenharmony_ciYou can pass in a list with any combination of module names, and fully 1737db96d56Sopenharmony_ciqualified class or method names. 1747db96d56Sopenharmony_ci 1757db96d56Sopenharmony_ciTest modules can be specified by file path as well:: 1767db96d56Sopenharmony_ci 1777db96d56Sopenharmony_ci python -m unittest tests/test_something.py 1787db96d56Sopenharmony_ci 1797db96d56Sopenharmony_ciThis allows you to use the shell filename completion to specify the test module. 1807db96d56Sopenharmony_ciThe file specified must still be importable as a module. The path is converted 1817db96d56Sopenharmony_cito a module name by removing the '.py' and converting path separators into '.'. 1827db96d56Sopenharmony_ciIf you want to execute a test file that isn't importable as a module you should 1837db96d56Sopenharmony_ciexecute the file directly instead. 1847db96d56Sopenharmony_ci 1857db96d56Sopenharmony_ciYou can run tests with more detail (higher verbosity) by passing in the -v flag:: 1867db96d56Sopenharmony_ci 1877db96d56Sopenharmony_ci python -m unittest -v test_module 1887db96d56Sopenharmony_ci 1897db96d56Sopenharmony_ciWhen executed without arguments :ref:`unittest-test-discovery` is started:: 1907db96d56Sopenharmony_ci 1917db96d56Sopenharmony_ci python -m unittest 1927db96d56Sopenharmony_ci 1937db96d56Sopenharmony_ciFor a list of all the command-line options:: 1947db96d56Sopenharmony_ci 1957db96d56Sopenharmony_ci python -m unittest -h 1967db96d56Sopenharmony_ci 1977db96d56Sopenharmony_ci.. versionchanged:: 3.2 1987db96d56Sopenharmony_ci In earlier versions it was only possible to run individual test methods and 1997db96d56Sopenharmony_ci not modules or classes. 2007db96d56Sopenharmony_ci 2017db96d56Sopenharmony_ci 2027db96d56Sopenharmony_ciCommand-line options 2037db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~ 2047db96d56Sopenharmony_ci 2057db96d56Sopenharmony_ci:program:`unittest` supports these command-line options: 2067db96d56Sopenharmony_ci 2077db96d56Sopenharmony_ci.. program:: unittest 2087db96d56Sopenharmony_ci 2097db96d56Sopenharmony_ci.. cmdoption:: -b, --buffer 2107db96d56Sopenharmony_ci 2117db96d56Sopenharmony_ci The standard output and standard error streams are buffered during the test 2127db96d56Sopenharmony_ci run. Output during a passing test is discarded. Output is echoed normally 2137db96d56Sopenharmony_ci on test fail or error and is added to the failure messages. 2147db96d56Sopenharmony_ci 2157db96d56Sopenharmony_ci.. cmdoption:: -c, --catch 2167db96d56Sopenharmony_ci 2177db96d56Sopenharmony_ci :kbd:`Control-C` during the test run waits for the current test to end and then 2187db96d56Sopenharmony_ci reports all the results so far. A second :kbd:`Control-C` raises the normal 2197db96d56Sopenharmony_ci :exc:`KeyboardInterrupt` exception. 2207db96d56Sopenharmony_ci 2217db96d56Sopenharmony_ci See `Signal Handling`_ for the functions that provide this functionality. 2227db96d56Sopenharmony_ci 2237db96d56Sopenharmony_ci.. cmdoption:: -f, --failfast 2247db96d56Sopenharmony_ci 2257db96d56Sopenharmony_ci Stop the test run on the first error or failure. 2267db96d56Sopenharmony_ci 2277db96d56Sopenharmony_ci.. cmdoption:: -k 2287db96d56Sopenharmony_ci 2297db96d56Sopenharmony_ci Only run test methods and classes that match the pattern or substring. 2307db96d56Sopenharmony_ci This option may be used multiple times, in which case all test cases that 2317db96d56Sopenharmony_ci match any of the given patterns are included. 2327db96d56Sopenharmony_ci 2337db96d56Sopenharmony_ci Patterns that contain a wildcard character (``*``) are matched against the 2347db96d56Sopenharmony_ci test name using :meth:`fnmatch.fnmatchcase`; otherwise simple case-sensitive 2357db96d56Sopenharmony_ci substring matching is used. 2367db96d56Sopenharmony_ci 2377db96d56Sopenharmony_ci Patterns are matched against the fully qualified test method name as 2387db96d56Sopenharmony_ci imported by the test loader. 2397db96d56Sopenharmony_ci 2407db96d56Sopenharmony_ci For example, ``-k foo`` matches ``foo_tests.SomeTest.test_something``, 2417db96d56Sopenharmony_ci ``bar_tests.SomeTest.test_foo``, but not ``bar_tests.FooTest.test_something``. 2427db96d56Sopenharmony_ci 2437db96d56Sopenharmony_ci.. cmdoption:: --locals 2447db96d56Sopenharmony_ci 2457db96d56Sopenharmony_ci Show local variables in tracebacks. 2467db96d56Sopenharmony_ci 2477db96d56Sopenharmony_ci.. versionadded:: 3.2 2487db96d56Sopenharmony_ci The command-line options ``-b``, ``-c`` and ``-f`` were added. 2497db96d56Sopenharmony_ci 2507db96d56Sopenharmony_ci.. versionadded:: 3.5 2517db96d56Sopenharmony_ci The command-line option ``--locals``. 2527db96d56Sopenharmony_ci 2537db96d56Sopenharmony_ci.. versionadded:: 3.7 2547db96d56Sopenharmony_ci The command-line option ``-k``. 2557db96d56Sopenharmony_ci 2567db96d56Sopenharmony_ciThe command line can also be used for test discovery, for running all of the 2577db96d56Sopenharmony_citests in a project or just a subset. 2587db96d56Sopenharmony_ci 2597db96d56Sopenharmony_ci 2607db96d56Sopenharmony_ci.. _unittest-test-discovery: 2617db96d56Sopenharmony_ci 2627db96d56Sopenharmony_ciTest Discovery 2637db96d56Sopenharmony_ci-------------- 2647db96d56Sopenharmony_ci 2657db96d56Sopenharmony_ci.. versionadded:: 3.2 2667db96d56Sopenharmony_ci 2677db96d56Sopenharmony_ciUnittest supports simple test discovery. In order to be compatible with test 2687db96d56Sopenharmony_cidiscovery, all of the test files must be :ref:`modules <tut-modules>` or 2697db96d56Sopenharmony_ci:ref:`packages <tut-packages>` importable from the top-level directory of 2707db96d56Sopenharmony_cithe project (this means that their filenames must be valid :ref:`identifiers 2717db96d56Sopenharmony_ci<identifiers>`). 2727db96d56Sopenharmony_ci 2737db96d56Sopenharmony_ciTest discovery is implemented in :meth:`TestLoader.discover`, but can also be 2747db96d56Sopenharmony_ciused from the command line. The basic command-line usage is:: 2757db96d56Sopenharmony_ci 2767db96d56Sopenharmony_ci cd project_directory 2777db96d56Sopenharmony_ci python -m unittest discover 2787db96d56Sopenharmony_ci 2797db96d56Sopenharmony_ci.. note:: 2807db96d56Sopenharmony_ci 2817db96d56Sopenharmony_ci As a shortcut, ``python -m unittest`` is the equivalent of 2827db96d56Sopenharmony_ci ``python -m unittest discover``. If you want to pass arguments to test 2837db96d56Sopenharmony_ci discovery the ``discover`` sub-command must be used explicitly. 2847db96d56Sopenharmony_ci 2857db96d56Sopenharmony_ciThe ``discover`` sub-command has the following options: 2867db96d56Sopenharmony_ci 2877db96d56Sopenharmony_ci.. program:: unittest discover 2887db96d56Sopenharmony_ci 2897db96d56Sopenharmony_ci.. cmdoption:: -v, --verbose 2907db96d56Sopenharmony_ci 2917db96d56Sopenharmony_ci Verbose output 2927db96d56Sopenharmony_ci 2937db96d56Sopenharmony_ci.. cmdoption:: -s, --start-directory directory 2947db96d56Sopenharmony_ci 2957db96d56Sopenharmony_ci Directory to start discovery (``.`` default) 2967db96d56Sopenharmony_ci 2977db96d56Sopenharmony_ci.. cmdoption:: -p, --pattern pattern 2987db96d56Sopenharmony_ci 2997db96d56Sopenharmony_ci Pattern to match test files (``test*.py`` default) 3007db96d56Sopenharmony_ci 3017db96d56Sopenharmony_ci.. cmdoption:: -t, --top-level-directory directory 3027db96d56Sopenharmony_ci 3037db96d56Sopenharmony_ci Top level directory of project (defaults to start directory) 3047db96d56Sopenharmony_ci 3057db96d56Sopenharmony_ciThe :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in 3067db96d56Sopenharmony_cias positional arguments in that order. The following two command lines 3077db96d56Sopenharmony_ciare equivalent:: 3087db96d56Sopenharmony_ci 3097db96d56Sopenharmony_ci python -m unittest discover -s project_directory -p "*_test.py" 3107db96d56Sopenharmony_ci python -m unittest discover project_directory "*_test.py" 3117db96d56Sopenharmony_ci 3127db96d56Sopenharmony_ciAs well as being a path it is possible to pass a package name, for example 3137db96d56Sopenharmony_ci``myproject.subpackage.test``, as the start directory. The package name you 3147db96d56Sopenharmony_cisupply will then be imported and its location on the filesystem will be used 3157db96d56Sopenharmony_cias the start directory. 3167db96d56Sopenharmony_ci 3177db96d56Sopenharmony_ci.. caution:: 3187db96d56Sopenharmony_ci 3197db96d56Sopenharmony_ci Test discovery loads tests by importing them. Once test discovery has found 3207db96d56Sopenharmony_ci all the test files from the start directory you specify it turns the paths 3217db96d56Sopenharmony_ci into package names to import. For example :file:`foo/bar/baz.py` will be 3227db96d56Sopenharmony_ci imported as ``foo.bar.baz``. 3237db96d56Sopenharmony_ci 3247db96d56Sopenharmony_ci If you have a package installed globally and attempt test discovery on 3257db96d56Sopenharmony_ci a different copy of the package then the import *could* happen from the 3267db96d56Sopenharmony_ci wrong place. If this happens test discovery will warn you and exit. 3277db96d56Sopenharmony_ci 3287db96d56Sopenharmony_ci If you supply the start directory as a package name rather than a 3297db96d56Sopenharmony_ci path to a directory then discover assumes that whichever location it 3307db96d56Sopenharmony_ci imports from is the location you intended, so you will not get the 3317db96d56Sopenharmony_ci warning. 3327db96d56Sopenharmony_ci 3337db96d56Sopenharmony_ciTest modules and packages can customize test loading and discovery by through 3347db96d56Sopenharmony_cithe `load_tests protocol`_. 3357db96d56Sopenharmony_ci 3367db96d56Sopenharmony_ci.. versionchanged:: 3.4 3377db96d56Sopenharmony_ci Test discovery supports :term:`namespace packages <namespace package>` 3387db96d56Sopenharmony_ci for the start directory. Note that you need to specify the top level 3397db96d56Sopenharmony_ci directory too (e.g. 3407db96d56Sopenharmony_ci ``python -m unittest discover -s root/namespace -t root``). 3417db96d56Sopenharmony_ci 3427db96d56Sopenharmony_ci.. versionchanged:: 3.11 3437db96d56Sopenharmony_ci Python 3.11 dropped the :term:`namespace packages <namespace package>` 3447db96d56Sopenharmony_ci support. It has been broken since Python 3.7. Start directory and 3457db96d56Sopenharmony_ci subdirectories containing tests must be regular package that have 3467db96d56Sopenharmony_ci ``__init__.py`` file. 3477db96d56Sopenharmony_ci 3487db96d56Sopenharmony_ci Directories containing start directory still can be a namespace package. 3497db96d56Sopenharmony_ci In this case, you need to specify start directory as dotted package name, 3507db96d56Sopenharmony_ci and target directory explicitly. For example:: 3517db96d56Sopenharmony_ci 3527db96d56Sopenharmony_ci # proj/ <-- current directory 3537db96d56Sopenharmony_ci # namespace/ 3547db96d56Sopenharmony_ci # mypkg/ 3557db96d56Sopenharmony_ci # __init__.py 3567db96d56Sopenharmony_ci # test_mypkg.py 3577db96d56Sopenharmony_ci 3587db96d56Sopenharmony_ci python -m unittest discover -s namespace.mypkg -t . 3597db96d56Sopenharmony_ci 3607db96d56Sopenharmony_ci 3617db96d56Sopenharmony_ci.. _organizing-tests: 3627db96d56Sopenharmony_ci 3637db96d56Sopenharmony_ciOrganizing test code 3647db96d56Sopenharmony_ci-------------------- 3657db96d56Sopenharmony_ci 3667db96d56Sopenharmony_ciThe basic building blocks of unit testing are :dfn:`test cases` --- single 3677db96d56Sopenharmony_ciscenarios that must be set up and checked for correctness. In :mod:`unittest`, 3687db96d56Sopenharmony_citest cases are represented by :class:`unittest.TestCase` instances. 3697db96d56Sopenharmony_ciTo make your own test cases you must write subclasses of 3707db96d56Sopenharmony_ci:class:`TestCase` or use :class:`FunctionTestCase`. 3717db96d56Sopenharmony_ci 3727db96d56Sopenharmony_ciThe testing code of a :class:`TestCase` instance should be entirely self 3737db96d56Sopenharmony_cicontained, such that it can be run either in isolation or in arbitrary 3747db96d56Sopenharmony_cicombination with any number of other test cases. 3757db96d56Sopenharmony_ci 3767db96d56Sopenharmony_ciThe simplest :class:`TestCase` subclass will simply implement a test method 3777db96d56Sopenharmony_ci(i.e. a method whose name starts with ``test``) in order to perform specific 3787db96d56Sopenharmony_citesting code:: 3797db96d56Sopenharmony_ci 3807db96d56Sopenharmony_ci import unittest 3817db96d56Sopenharmony_ci 3827db96d56Sopenharmony_ci class DefaultWidgetSizeTestCase(unittest.TestCase): 3837db96d56Sopenharmony_ci def test_default_widget_size(self): 3847db96d56Sopenharmony_ci widget = Widget('The widget') 3857db96d56Sopenharmony_ci self.assertEqual(widget.size(), (50, 50)) 3867db96d56Sopenharmony_ci 3877db96d56Sopenharmony_ciNote that in order to test something, we use one of the :meth:`assert\*` 3887db96d56Sopenharmony_cimethods provided by the :class:`TestCase` base class. If the test fails, an 3897db96d56Sopenharmony_ciexception will be raised with an explanatory message, and :mod:`unittest` 3907db96d56Sopenharmony_ciwill identify the test case as a :dfn:`failure`. Any other exceptions will be 3917db96d56Sopenharmony_citreated as :dfn:`errors`. 3927db96d56Sopenharmony_ci 3937db96d56Sopenharmony_ciTests can be numerous, and their set-up can be repetitive. Luckily, we 3947db96d56Sopenharmony_cican factor out set-up code by implementing a method called 3957db96d56Sopenharmony_ci:meth:`~TestCase.setUp`, which the testing framework will automatically 3967db96d56Sopenharmony_cicall for every single test we run:: 3977db96d56Sopenharmony_ci 3987db96d56Sopenharmony_ci import unittest 3997db96d56Sopenharmony_ci 4007db96d56Sopenharmony_ci class WidgetTestCase(unittest.TestCase): 4017db96d56Sopenharmony_ci def setUp(self): 4027db96d56Sopenharmony_ci self.widget = Widget('The widget') 4037db96d56Sopenharmony_ci 4047db96d56Sopenharmony_ci def test_default_widget_size(self): 4057db96d56Sopenharmony_ci self.assertEqual(self.widget.size(), (50,50), 4067db96d56Sopenharmony_ci 'incorrect default size') 4077db96d56Sopenharmony_ci 4087db96d56Sopenharmony_ci def test_widget_resize(self): 4097db96d56Sopenharmony_ci self.widget.resize(100,150) 4107db96d56Sopenharmony_ci self.assertEqual(self.widget.size(), (100,150), 4117db96d56Sopenharmony_ci 'wrong size after resize') 4127db96d56Sopenharmony_ci 4137db96d56Sopenharmony_ci.. note:: 4147db96d56Sopenharmony_ci The order in which the various tests will be run is determined 4157db96d56Sopenharmony_ci by sorting the test method names with respect to the built-in 4167db96d56Sopenharmony_ci ordering for strings. 4177db96d56Sopenharmony_ci 4187db96d56Sopenharmony_ciIf the :meth:`~TestCase.setUp` method raises an exception while the test is 4197db96d56Sopenharmony_cirunning, the framework will consider the test to have suffered an error, and 4207db96d56Sopenharmony_cithe test method will not be executed. 4217db96d56Sopenharmony_ci 4227db96d56Sopenharmony_ciSimilarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up 4237db96d56Sopenharmony_ciafter the test method has been run:: 4247db96d56Sopenharmony_ci 4257db96d56Sopenharmony_ci import unittest 4267db96d56Sopenharmony_ci 4277db96d56Sopenharmony_ci class WidgetTestCase(unittest.TestCase): 4287db96d56Sopenharmony_ci def setUp(self): 4297db96d56Sopenharmony_ci self.widget = Widget('The widget') 4307db96d56Sopenharmony_ci 4317db96d56Sopenharmony_ci def tearDown(self): 4327db96d56Sopenharmony_ci self.widget.dispose() 4337db96d56Sopenharmony_ci 4347db96d56Sopenharmony_ciIf :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be 4357db96d56Sopenharmony_cirun whether the test method succeeded or not. 4367db96d56Sopenharmony_ci 4377db96d56Sopenharmony_ciSuch a working environment for the testing code is called a 4387db96d56Sopenharmony_ci:dfn:`test fixture`. A new TestCase instance is created as a unique 4397db96d56Sopenharmony_citest fixture used to execute each individual test method. Thus 4407db96d56Sopenharmony_ci:meth:`~TestCase.setUp`, :meth:`~TestCase.tearDown`, and :meth:`~TestCase.__init__` 4417db96d56Sopenharmony_ciwill be called once per test. 4427db96d56Sopenharmony_ci 4437db96d56Sopenharmony_ciIt is recommended that you use TestCase implementations to group tests together 4447db96d56Sopenharmony_ciaccording to the features they test. :mod:`unittest` provides a mechanism for 4457db96d56Sopenharmony_cithis: the :dfn:`test suite`, represented by :mod:`unittest`'s 4467db96d56Sopenharmony_ci:class:`TestSuite` class. In most cases, calling :func:`unittest.main` will do 4477db96d56Sopenharmony_cithe right thing and collect all the module's test cases for you and execute 4487db96d56Sopenharmony_cithem. 4497db96d56Sopenharmony_ci 4507db96d56Sopenharmony_ciHowever, should you want to customize the building of your test suite, 4517db96d56Sopenharmony_ciyou can do it yourself:: 4527db96d56Sopenharmony_ci 4537db96d56Sopenharmony_ci def suite(): 4547db96d56Sopenharmony_ci suite = unittest.TestSuite() 4557db96d56Sopenharmony_ci suite.addTest(WidgetTestCase('test_default_widget_size')) 4567db96d56Sopenharmony_ci suite.addTest(WidgetTestCase('test_widget_resize')) 4577db96d56Sopenharmony_ci return suite 4587db96d56Sopenharmony_ci 4597db96d56Sopenharmony_ci if __name__ == '__main__': 4607db96d56Sopenharmony_ci runner = unittest.TextTestRunner() 4617db96d56Sopenharmony_ci runner.run(suite()) 4627db96d56Sopenharmony_ci 4637db96d56Sopenharmony_ciYou can place the definitions of test cases and test suites in the same modules 4647db96d56Sopenharmony_cias the code they are to test (such as :file:`widget.py`), but there are several 4657db96d56Sopenharmony_ciadvantages to placing the test code in a separate module, such as 4667db96d56Sopenharmony_ci:file:`test_widget.py`: 4677db96d56Sopenharmony_ci 4687db96d56Sopenharmony_ci* The test module can be run standalone from the command line. 4697db96d56Sopenharmony_ci 4707db96d56Sopenharmony_ci* The test code can more easily be separated from shipped code. 4717db96d56Sopenharmony_ci 4727db96d56Sopenharmony_ci* There is less temptation to change test code to fit the code it tests without 4737db96d56Sopenharmony_ci a good reason. 4747db96d56Sopenharmony_ci 4757db96d56Sopenharmony_ci* Test code should be modified much less frequently than the code it tests. 4767db96d56Sopenharmony_ci 4777db96d56Sopenharmony_ci* Tested code can be refactored more easily. 4787db96d56Sopenharmony_ci 4797db96d56Sopenharmony_ci* Tests for modules written in C must be in separate modules anyway, so why not 4807db96d56Sopenharmony_ci be consistent? 4817db96d56Sopenharmony_ci 4827db96d56Sopenharmony_ci* If the testing strategy changes, there is no need to change the source code. 4837db96d56Sopenharmony_ci 4847db96d56Sopenharmony_ci 4857db96d56Sopenharmony_ci.. _legacy-unit-tests: 4867db96d56Sopenharmony_ci 4877db96d56Sopenharmony_ciRe-using old test code 4887db96d56Sopenharmony_ci---------------------- 4897db96d56Sopenharmony_ci 4907db96d56Sopenharmony_ciSome users will find that they have existing test code that they would like to 4917db96d56Sopenharmony_cirun from :mod:`unittest`, without converting every old test function to a 4927db96d56Sopenharmony_ci:class:`TestCase` subclass. 4937db96d56Sopenharmony_ci 4947db96d56Sopenharmony_ciFor this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class. 4957db96d56Sopenharmony_ciThis subclass of :class:`TestCase` can be used to wrap an existing test 4967db96d56Sopenharmony_cifunction. Set-up and tear-down functions can also be provided. 4977db96d56Sopenharmony_ci 4987db96d56Sopenharmony_ciGiven the following test function:: 4997db96d56Sopenharmony_ci 5007db96d56Sopenharmony_ci def testSomething(): 5017db96d56Sopenharmony_ci something = makeSomething() 5027db96d56Sopenharmony_ci assert something.name is not None 5037db96d56Sopenharmony_ci # ... 5047db96d56Sopenharmony_ci 5057db96d56Sopenharmony_cione can create an equivalent test case instance as follows, with optional 5067db96d56Sopenharmony_ciset-up and tear-down methods:: 5077db96d56Sopenharmony_ci 5087db96d56Sopenharmony_ci testcase = unittest.FunctionTestCase(testSomething, 5097db96d56Sopenharmony_ci setUp=makeSomethingDB, 5107db96d56Sopenharmony_ci tearDown=deleteSomethingDB) 5117db96d56Sopenharmony_ci 5127db96d56Sopenharmony_ci.. note:: 5137db96d56Sopenharmony_ci 5147db96d56Sopenharmony_ci Even though :class:`FunctionTestCase` can be used to quickly convert an 5157db96d56Sopenharmony_ci existing test base over to a :mod:`unittest`\ -based system, this approach is 5167db96d56Sopenharmony_ci not recommended. Taking the time to set up proper :class:`TestCase` 5177db96d56Sopenharmony_ci subclasses will make future test refactorings infinitely easier. 5187db96d56Sopenharmony_ci 5197db96d56Sopenharmony_ciIn some cases, the existing tests may have been written using the :mod:`doctest` 5207db96d56Sopenharmony_cimodule. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can 5217db96d56Sopenharmony_ciautomatically build :class:`unittest.TestSuite` instances from the existing 5227db96d56Sopenharmony_ci:mod:`doctest`\ -based tests. 5237db96d56Sopenharmony_ci 5247db96d56Sopenharmony_ci 5257db96d56Sopenharmony_ci.. _unittest-skipping: 5267db96d56Sopenharmony_ci 5277db96d56Sopenharmony_ciSkipping tests and expected failures 5287db96d56Sopenharmony_ci------------------------------------ 5297db96d56Sopenharmony_ci 5307db96d56Sopenharmony_ci.. versionadded:: 3.1 5317db96d56Sopenharmony_ci 5327db96d56Sopenharmony_ciUnittest supports skipping individual test methods and even whole classes of 5337db96d56Sopenharmony_citests. In addition, it supports marking a test as an "expected failure," a test 5347db96d56Sopenharmony_cithat is broken and will fail, but shouldn't be counted as a failure on a 5357db96d56Sopenharmony_ci:class:`TestResult`. 5367db96d56Sopenharmony_ci 5377db96d56Sopenharmony_ciSkipping a test is simply a matter of using the :func:`skip` :term:`decorator` 5387db96d56Sopenharmony_cior one of its conditional variants, calling :meth:`TestCase.skipTest` within a 5397db96d56Sopenharmony_ci:meth:`~TestCase.setUp` or test method, or raising :exc:`SkipTest` directly. 5407db96d56Sopenharmony_ci 5417db96d56Sopenharmony_ciBasic skipping looks like this:: 5427db96d56Sopenharmony_ci 5437db96d56Sopenharmony_ci class MyTestCase(unittest.TestCase): 5447db96d56Sopenharmony_ci 5457db96d56Sopenharmony_ci @unittest.skip("demonstrating skipping") 5467db96d56Sopenharmony_ci def test_nothing(self): 5477db96d56Sopenharmony_ci self.fail("shouldn't happen") 5487db96d56Sopenharmony_ci 5497db96d56Sopenharmony_ci @unittest.skipIf(mylib.__version__ < (1, 3), 5507db96d56Sopenharmony_ci "not supported in this library version") 5517db96d56Sopenharmony_ci def test_format(self): 5527db96d56Sopenharmony_ci # Tests that work for only a certain version of the library. 5537db96d56Sopenharmony_ci pass 5547db96d56Sopenharmony_ci 5557db96d56Sopenharmony_ci @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") 5567db96d56Sopenharmony_ci def test_windows_support(self): 5577db96d56Sopenharmony_ci # windows specific testing code 5587db96d56Sopenharmony_ci pass 5597db96d56Sopenharmony_ci 5607db96d56Sopenharmony_ci def test_maybe_skipped(self): 5617db96d56Sopenharmony_ci if not external_resource_available(): 5627db96d56Sopenharmony_ci self.skipTest("external resource not available") 5637db96d56Sopenharmony_ci # test code that depends on the external resource 5647db96d56Sopenharmony_ci pass 5657db96d56Sopenharmony_ci 5667db96d56Sopenharmony_ciThis is the output of running the example above in verbose mode:: 5677db96d56Sopenharmony_ci 5687db96d56Sopenharmony_ci test_format (__main__.MyTestCase.test_format) ... skipped 'not supported in this library version' 5697db96d56Sopenharmony_ci test_nothing (__main__.MyTestCase.test_nothing) ... skipped 'demonstrating skipping' 5707db96d56Sopenharmony_ci test_maybe_skipped (__main__.MyTestCase.test_maybe_skipped) ... skipped 'external resource not available' 5717db96d56Sopenharmony_ci test_windows_support (__main__.MyTestCase.test_windows_support) ... skipped 'requires Windows' 5727db96d56Sopenharmony_ci 5737db96d56Sopenharmony_ci ---------------------------------------------------------------------- 5747db96d56Sopenharmony_ci Ran 4 tests in 0.005s 5757db96d56Sopenharmony_ci 5767db96d56Sopenharmony_ci OK (skipped=4) 5777db96d56Sopenharmony_ci 5787db96d56Sopenharmony_ciClasses can be skipped just like methods:: 5797db96d56Sopenharmony_ci 5807db96d56Sopenharmony_ci @unittest.skip("showing class skipping") 5817db96d56Sopenharmony_ci class MySkippedTestCase(unittest.TestCase): 5827db96d56Sopenharmony_ci def test_not_run(self): 5837db96d56Sopenharmony_ci pass 5847db96d56Sopenharmony_ci 5857db96d56Sopenharmony_ci:meth:`TestCase.setUp` can also skip the test. This is useful when a resource 5867db96d56Sopenharmony_cithat needs to be set up is not available. 5877db96d56Sopenharmony_ci 5887db96d56Sopenharmony_ciExpected failures use the :func:`expectedFailure` decorator. :: 5897db96d56Sopenharmony_ci 5907db96d56Sopenharmony_ci class ExpectedFailureTestCase(unittest.TestCase): 5917db96d56Sopenharmony_ci @unittest.expectedFailure 5927db96d56Sopenharmony_ci def test_fail(self): 5937db96d56Sopenharmony_ci self.assertEqual(1, 0, "broken") 5947db96d56Sopenharmony_ci 5957db96d56Sopenharmony_ciIt's easy to roll your own skipping decorators by making a decorator that calls 5967db96d56Sopenharmony_ci:func:`skip` on the test when it wants it to be skipped. This decorator skips 5977db96d56Sopenharmony_cithe test unless the passed object has a certain attribute:: 5987db96d56Sopenharmony_ci 5997db96d56Sopenharmony_ci def skipUnlessHasattr(obj, attr): 6007db96d56Sopenharmony_ci if hasattr(obj, attr): 6017db96d56Sopenharmony_ci return lambda func: func 6027db96d56Sopenharmony_ci return unittest.skip("{!r} doesn't have {!r}".format(obj, attr)) 6037db96d56Sopenharmony_ci 6047db96d56Sopenharmony_ciThe following decorators and exception implement test skipping and expected failures: 6057db96d56Sopenharmony_ci 6067db96d56Sopenharmony_ci.. decorator:: skip(reason) 6077db96d56Sopenharmony_ci 6087db96d56Sopenharmony_ci Unconditionally skip the decorated test. *reason* should describe why the 6097db96d56Sopenharmony_ci test is being skipped. 6107db96d56Sopenharmony_ci 6117db96d56Sopenharmony_ci.. decorator:: skipIf(condition, reason) 6127db96d56Sopenharmony_ci 6137db96d56Sopenharmony_ci Skip the decorated test if *condition* is true. 6147db96d56Sopenharmony_ci 6157db96d56Sopenharmony_ci.. decorator:: skipUnless(condition, reason) 6167db96d56Sopenharmony_ci 6177db96d56Sopenharmony_ci Skip the decorated test unless *condition* is true. 6187db96d56Sopenharmony_ci 6197db96d56Sopenharmony_ci.. decorator:: expectedFailure 6207db96d56Sopenharmony_ci 6217db96d56Sopenharmony_ci Mark the test as an expected failure or error. If the test fails or errors 6227db96d56Sopenharmony_ci in the test function itself (rather than in one of the :dfn:`test fixture` 6237db96d56Sopenharmony_ci methods) then it will be considered a success. If the test passes, it will 6247db96d56Sopenharmony_ci be considered a failure. 6257db96d56Sopenharmony_ci 6267db96d56Sopenharmony_ci.. exception:: SkipTest(reason) 6277db96d56Sopenharmony_ci 6287db96d56Sopenharmony_ci This exception is raised to skip a test. 6297db96d56Sopenharmony_ci 6307db96d56Sopenharmony_ci Usually you can use :meth:`TestCase.skipTest` or one of the skipping 6317db96d56Sopenharmony_ci decorators instead of raising this directly. 6327db96d56Sopenharmony_ci 6337db96d56Sopenharmony_ciSkipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them. 6347db96d56Sopenharmony_ciSkipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run. 6357db96d56Sopenharmony_ciSkipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run. 6367db96d56Sopenharmony_ci 6377db96d56Sopenharmony_ci 6387db96d56Sopenharmony_ci.. _subtests: 6397db96d56Sopenharmony_ci 6407db96d56Sopenharmony_ciDistinguishing test iterations using subtests 6417db96d56Sopenharmony_ci--------------------------------------------- 6427db96d56Sopenharmony_ci 6437db96d56Sopenharmony_ci.. versionadded:: 3.4 6447db96d56Sopenharmony_ci 6457db96d56Sopenharmony_ciWhen there are very small differences among your tests, for 6467db96d56Sopenharmony_ciinstance some parameters, unittest allows you to distinguish them inside 6477db96d56Sopenharmony_cithe body of a test method using the :meth:`~TestCase.subTest` context manager. 6487db96d56Sopenharmony_ci 6497db96d56Sopenharmony_ciFor example, the following test:: 6507db96d56Sopenharmony_ci 6517db96d56Sopenharmony_ci class NumbersTest(unittest.TestCase): 6527db96d56Sopenharmony_ci 6537db96d56Sopenharmony_ci def test_even(self): 6547db96d56Sopenharmony_ci """ 6557db96d56Sopenharmony_ci Test that numbers between 0 and 5 are all even. 6567db96d56Sopenharmony_ci """ 6577db96d56Sopenharmony_ci for i in range(0, 6): 6587db96d56Sopenharmony_ci with self.subTest(i=i): 6597db96d56Sopenharmony_ci self.assertEqual(i % 2, 0) 6607db96d56Sopenharmony_ci 6617db96d56Sopenharmony_ciwill produce the following output:: 6627db96d56Sopenharmony_ci 6637db96d56Sopenharmony_ci ====================================================================== 6647db96d56Sopenharmony_ci FAIL: test_even (__main__.NumbersTest.test_even) (i=1) 6657db96d56Sopenharmony_ci Test that numbers between 0 and 5 are all even. 6667db96d56Sopenharmony_ci ---------------------------------------------------------------------- 6677db96d56Sopenharmony_ci Traceback (most recent call last): 6687db96d56Sopenharmony_ci File "subtests.py", line 11, in test_even 6697db96d56Sopenharmony_ci self.assertEqual(i % 2, 0) 6707db96d56Sopenharmony_ci ^^^^^^^^^^^^^^^^^^^^^^^^^^ 6717db96d56Sopenharmony_ci AssertionError: 1 != 0 6727db96d56Sopenharmony_ci 6737db96d56Sopenharmony_ci ====================================================================== 6747db96d56Sopenharmony_ci FAIL: test_even (__main__.NumbersTest.test_even) (i=3) 6757db96d56Sopenharmony_ci Test that numbers between 0 and 5 are all even. 6767db96d56Sopenharmony_ci ---------------------------------------------------------------------- 6777db96d56Sopenharmony_ci Traceback (most recent call last): 6787db96d56Sopenharmony_ci File "subtests.py", line 11, in test_even 6797db96d56Sopenharmony_ci self.assertEqual(i % 2, 0) 6807db96d56Sopenharmony_ci ^^^^^^^^^^^^^^^^^^^^^^^^^^ 6817db96d56Sopenharmony_ci AssertionError: 1 != 0 6827db96d56Sopenharmony_ci 6837db96d56Sopenharmony_ci ====================================================================== 6847db96d56Sopenharmony_ci FAIL: test_even (__main__.NumbersTest.test_even) (i=5) 6857db96d56Sopenharmony_ci Test that numbers between 0 and 5 are all even. 6867db96d56Sopenharmony_ci ---------------------------------------------------------------------- 6877db96d56Sopenharmony_ci Traceback (most recent call last): 6887db96d56Sopenharmony_ci File "subtests.py", line 11, in test_even 6897db96d56Sopenharmony_ci self.assertEqual(i % 2, 0) 6907db96d56Sopenharmony_ci ^^^^^^^^^^^^^^^^^^^^^^^^^^ 6917db96d56Sopenharmony_ci AssertionError: 1 != 0 6927db96d56Sopenharmony_ci 6937db96d56Sopenharmony_ciWithout using a subtest, execution would stop after the first failure, 6947db96d56Sopenharmony_ciand the error would be less easy to diagnose because the value of ``i`` 6957db96d56Sopenharmony_ciwouldn't be displayed:: 6967db96d56Sopenharmony_ci 6977db96d56Sopenharmony_ci ====================================================================== 6987db96d56Sopenharmony_ci FAIL: test_even (__main__.NumbersTest.test_even) 6997db96d56Sopenharmony_ci ---------------------------------------------------------------------- 7007db96d56Sopenharmony_ci Traceback (most recent call last): 7017db96d56Sopenharmony_ci File "subtests.py", line 32, in test_even 7027db96d56Sopenharmony_ci self.assertEqual(i % 2, 0) 7037db96d56Sopenharmony_ci AssertionError: 1 != 0 7047db96d56Sopenharmony_ci 7057db96d56Sopenharmony_ci 7067db96d56Sopenharmony_ci.. _unittest-contents: 7077db96d56Sopenharmony_ci 7087db96d56Sopenharmony_ciClasses and functions 7097db96d56Sopenharmony_ci--------------------- 7107db96d56Sopenharmony_ci 7117db96d56Sopenharmony_ciThis section describes in depth the API of :mod:`unittest`. 7127db96d56Sopenharmony_ci 7137db96d56Sopenharmony_ci 7147db96d56Sopenharmony_ci.. _testcase-objects: 7157db96d56Sopenharmony_ci 7167db96d56Sopenharmony_ciTest cases 7177db96d56Sopenharmony_ci~~~~~~~~~~ 7187db96d56Sopenharmony_ci 7197db96d56Sopenharmony_ci.. class:: TestCase(methodName='runTest') 7207db96d56Sopenharmony_ci 7217db96d56Sopenharmony_ci Instances of the :class:`TestCase` class represent the logical test units 7227db96d56Sopenharmony_ci in the :mod:`unittest` universe. This class is intended to be used as a base 7237db96d56Sopenharmony_ci class, with specific tests being implemented by concrete subclasses. This class 7247db96d56Sopenharmony_ci implements the interface needed by the test runner to allow it to drive the 7257db96d56Sopenharmony_ci tests, and methods that the test code can use to check for and report various 7267db96d56Sopenharmony_ci kinds of failure. 7277db96d56Sopenharmony_ci 7287db96d56Sopenharmony_ci Each instance of :class:`TestCase` will run a single base method: the method 7297db96d56Sopenharmony_ci named *methodName*. 7307db96d56Sopenharmony_ci In most uses of :class:`TestCase`, you will neither change 7317db96d56Sopenharmony_ci the *methodName* nor reimplement the default ``runTest()`` method. 7327db96d56Sopenharmony_ci 7337db96d56Sopenharmony_ci .. versionchanged:: 3.2 7347db96d56Sopenharmony_ci :class:`TestCase` can be instantiated successfully without providing a 7357db96d56Sopenharmony_ci *methodName*. This makes it easier to experiment with :class:`TestCase` 7367db96d56Sopenharmony_ci from the interactive interpreter. 7377db96d56Sopenharmony_ci 7387db96d56Sopenharmony_ci :class:`TestCase` instances provide three groups of methods: one group used 7397db96d56Sopenharmony_ci to run the test, another used by the test implementation to check conditions 7407db96d56Sopenharmony_ci and report failures, and some inquiry methods allowing information about the 7417db96d56Sopenharmony_ci test itself to be gathered. 7427db96d56Sopenharmony_ci 7437db96d56Sopenharmony_ci Methods in the first group (running the test) are: 7447db96d56Sopenharmony_ci 7457db96d56Sopenharmony_ci .. method:: setUp() 7467db96d56Sopenharmony_ci 7477db96d56Sopenharmony_ci Method called to prepare the test fixture. This is called immediately 7487db96d56Sopenharmony_ci before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`, 7497db96d56Sopenharmony_ci any exception raised by this method will be considered an error rather than 7507db96d56Sopenharmony_ci a test failure. The default implementation does nothing. 7517db96d56Sopenharmony_ci 7527db96d56Sopenharmony_ci 7537db96d56Sopenharmony_ci .. method:: tearDown() 7547db96d56Sopenharmony_ci 7557db96d56Sopenharmony_ci Method called immediately after the test method has been called and the 7567db96d56Sopenharmony_ci result recorded. This is called even if the test method raised an 7577db96d56Sopenharmony_ci exception, so the implementation in subclasses may need to be particularly 7587db96d56Sopenharmony_ci careful about checking internal state. Any exception, other than 7597db96d56Sopenharmony_ci :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be 7607db96d56Sopenharmony_ci considered an additional error rather than a test failure (thus increasing 7617db96d56Sopenharmony_ci the total number of reported errors). This method will only be called if 7627db96d56Sopenharmony_ci the :meth:`setUp` succeeds, regardless of the outcome of the test method. 7637db96d56Sopenharmony_ci The default implementation does nothing. 7647db96d56Sopenharmony_ci 7657db96d56Sopenharmony_ci 7667db96d56Sopenharmony_ci .. method:: setUpClass() 7677db96d56Sopenharmony_ci 7687db96d56Sopenharmony_ci A class method called before tests in an individual class are run. 7697db96d56Sopenharmony_ci ``setUpClass`` is called with the class as the only argument 7707db96d56Sopenharmony_ci and must be decorated as a :func:`classmethod`:: 7717db96d56Sopenharmony_ci 7727db96d56Sopenharmony_ci @classmethod 7737db96d56Sopenharmony_ci def setUpClass(cls): 7747db96d56Sopenharmony_ci ... 7757db96d56Sopenharmony_ci 7767db96d56Sopenharmony_ci See `Class and Module Fixtures`_ for more details. 7777db96d56Sopenharmony_ci 7787db96d56Sopenharmony_ci .. versionadded:: 3.2 7797db96d56Sopenharmony_ci 7807db96d56Sopenharmony_ci 7817db96d56Sopenharmony_ci .. method:: tearDownClass() 7827db96d56Sopenharmony_ci 7837db96d56Sopenharmony_ci A class method called after tests in an individual class have run. 7847db96d56Sopenharmony_ci ``tearDownClass`` is called with the class as the only argument 7857db96d56Sopenharmony_ci and must be decorated as a :meth:`classmethod`:: 7867db96d56Sopenharmony_ci 7877db96d56Sopenharmony_ci @classmethod 7887db96d56Sopenharmony_ci def tearDownClass(cls): 7897db96d56Sopenharmony_ci ... 7907db96d56Sopenharmony_ci 7917db96d56Sopenharmony_ci See `Class and Module Fixtures`_ for more details. 7927db96d56Sopenharmony_ci 7937db96d56Sopenharmony_ci .. versionadded:: 3.2 7947db96d56Sopenharmony_ci 7957db96d56Sopenharmony_ci 7967db96d56Sopenharmony_ci .. method:: run(result=None) 7977db96d56Sopenharmony_ci 7987db96d56Sopenharmony_ci Run the test, collecting the result into the :class:`TestResult` object 7997db96d56Sopenharmony_ci passed as *result*. If *result* is omitted or ``None``, a temporary 8007db96d56Sopenharmony_ci result object is created (by calling the :meth:`defaultTestResult` 8017db96d56Sopenharmony_ci method) and used. The result object is returned to :meth:`run`'s 8027db96d56Sopenharmony_ci caller. 8037db96d56Sopenharmony_ci 8047db96d56Sopenharmony_ci The same effect may be had by simply calling the :class:`TestCase` 8057db96d56Sopenharmony_ci instance. 8067db96d56Sopenharmony_ci 8077db96d56Sopenharmony_ci .. versionchanged:: 3.3 8087db96d56Sopenharmony_ci Previous versions of ``run`` did not return the result. Neither did 8097db96d56Sopenharmony_ci calling an instance. 8107db96d56Sopenharmony_ci 8117db96d56Sopenharmony_ci .. method:: skipTest(reason) 8127db96d56Sopenharmony_ci 8137db96d56Sopenharmony_ci Calling this during a test method or :meth:`setUp` skips the current 8147db96d56Sopenharmony_ci test. See :ref:`unittest-skipping` for more information. 8157db96d56Sopenharmony_ci 8167db96d56Sopenharmony_ci .. versionadded:: 3.1 8177db96d56Sopenharmony_ci 8187db96d56Sopenharmony_ci 8197db96d56Sopenharmony_ci .. method:: subTest(msg=None, **params) 8207db96d56Sopenharmony_ci 8217db96d56Sopenharmony_ci Return a context manager which executes the enclosed code block as a 8227db96d56Sopenharmony_ci subtest. *msg* and *params* are optional, arbitrary values which are 8237db96d56Sopenharmony_ci displayed whenever a subtest fails, allowing you to identify them 8247db96d56Sopenharmony_ci clearly. 8257db96d56Sopenharmony_ci 8267db96d56Sopenharmony_ci A test case can contain any number of subtest declarations, and 8277db96d56Sopenharmony_ci they can be arbitrarily nested. 8287db96d56Sopenharmony_ci 8297db96d56Sopenharmony_ci See :ref:`subtests` for more information. 8307db96d56Sopenharmony_ci 8317db96d56Sopenharmony_ci .. versionadded:: 3.4 8327db96d56Sopenharmony_ci 8337db96d56Sopenharmony_ci 8347db96d56Sopenharmony_ci .. method:: debug() 8357db96d56Sopenharmony_ci 8367db96d56Sopenharmony_ci Run the test without collecting the result. This allows exceptions raised 8377db96d56Sopenharmony_ci by the test to be propagated to the caller, and can be used to support 8387db96d56Sopenharmony_ci running tests under a debugger. 8397db96d56Sopenharmony_ci 8407db96d56Sopenharmony_ci .. _assert-methods: 8417db96d56Sopenharmony_ci 8427db96d56Sopenharmony_ci The :class:`TestCase` class provides several assert methods to check for and 8437db96d56Sopenharmony_ci report failures. The following table lists the most commonly used methods 8447db96d56Sopenharmony_ci (see the tables below for more assert methods): 8457db96d56Sopenharmony_ci 8467db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8477db96d56Sopenharmony_ci | Method | Checks that | New in | 8487db96d56Sopenharmony_ci +=========================================+=============================+===============+ 8497db96d56Sopenharmony_ci | :meth:`assertEqual(a, b) | ``a == b`` | | 8507db96d56Sopenharmony_ci | <TestCase.assertEqual>` | | | 8517db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8527db96d56Sopenharmony_ci | :meth:`assertNotEqual(a, b) | ``a != b`` | | 8537db96d56Sopenharmony_ci | <TestCase.assertNotEqual>` | | | 8547db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8557db96d56Sopenharmony_ci | :meth:`assertTrue(x) | ``bool(x) is True`` | | 8567db96d56Sopenharmony_ci | <TestCase.assertTrue>` | | | 8577db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8587db96d56Sopenharmony_ci | :meth:`assertFalse(x) | ``bool(x) is False`` | | 8597db96d56Sopenharmony_ci | <TestCase.assertFalse>` | | | 8607db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8617db96d56Sopenharmony_ci | :meth:`assertIs(a, b) | ``a is b`` | 3.1 | 8627db96d56Sopenharmony_ci | <TestCase.assertIs>` | | | 8637db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8647db96d56Sopenharmony_ci | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 | 8657db96d56Sopenharmony_ci | <TestCase.assertIsNot>` | | | 8667db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8677db96d56Sopenharmony_ci | :meth:`assertIsNone(x) | ``x is None`` | 3.1 | 8687db96d56Sopenharmony_ci | <TestCase.assertIsNone>` | | | 8697db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8707db96d56Sopenharmony_ci | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 | 8717db96d56Sopenharmony_ci | <TestCase.assertIsNotNone>` | | | 8727db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8737db96d56Sopenharmony_ci | :meth:`assertIn(a, b) | ``a in b`` | 3.1 | 8747db96d56Sopenharmony_ci | <TestCase.assertIn>` | | | 8757db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8767db96d56Sopenharmony_ci | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 | 8777db96d56Sopenharmony_ci | <TestCase.assertNotIn>` | | | 8787db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8797db96d56Sopenharmony_ci | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 | 8807db96d56Sopenharmony_ci | <TestCase.assertIsInstance>` | | | 8817db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8827db96d56Sopenharmony_ci | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 | 8837db96d56Sopenharmony_ci | <TestCase.assertNotIsInstance>` | | | 8847db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+---------------+ 8857db96d56Sopenharmony_ci 8867db96d56Sopenharmony_ci All the assert methods accept a *msg* argument that, if specified, is used 8877db96d56Sopenharmony_ci as the error message on failure (see also :data:`longMessage`). 8887db96d56Sopenharmony_ci Note that the *msg* keyword argument can be passed to :meth:`assertRaises`, 8897db96d56Sopenharmony_ci :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex` 8907db96d56Sopenharmony_ci only when they are used as a context manager. 8917db96d56Sopenharmony_ci 8927db96d56Sopenharmony_ci .. method:: assertEqual(first, second, msg=None) 8937db96d56Sopenharmony_ci 8947db96d56Sopenharmony_ci Test that *first* and *second* are equal. If the values do not 8957db96d56Sopenharmony_ci compare equal, the test will fail. 8967db96d56Sopenharmony_ci 8977db96d56Sopenharmony_ci In addition, if *first* and *second* are the exact same type and one of 8987db96d56Sopenharmony_ci list, tuple, dict, set, frozenset or str or any type that a subclass 8997db96d56Sopenharmony_ci registers with :meth:`addTypeEqualityFunc` the type-specific equality 9007db96d56Sopenharmony_ci function will be called in order to generate a more useful default 9017db96d56Sopenharmony_ci error message (see also the :ref:`list of type-specific methods 9027db96d56Sopenharmony_ci <type-specific-methods>`). 9037db96d56Sopenharmony_ci 9047db96d56Sopenharmony_ci .. versionchanged:: 3.1 9057db96d56Sopenharmony_ci Added the automatic calling of type-specific equality function. 9067db96d56Sopenharmony_ci 9077db96d56Sopenharmony_ci .. versionchanged:: 3.2 9087db96d56Sopenharmony_ci :meth:`assertMultiLineEqual` added as the default type equality 9097db96d56Sopenharmony_ci function for comparing strings. 9107db96d56Sopenharmony_ci 9117db96d56Sopenharmony_ci 9127db96d56Sopenharmony_ci .. method:: assertNotEqual(first, second, msg=None) 9137db96d56Sopenharmony_ci 9147db96d56Sopenharmony_ci Test that *first* and *second* are not equal. If the values do 9157db96d56Sopenharmony_ci compare equal, the test will fail. 9167db96d56Sopenharmony_ci 9177db96d56Sopenharmony_ci .. method:: assertTrue(expr, msg=None) 9187db96d56Sopenharmony_ci assertFalse(expr, msg=None) 9197db96d56Sopenharmony_ci 9207db96d56Sopenharmony_ci Test that *expr* is true (or false). 9217db96d56Sopenharmony_ci 9227db96d56Sopenharmony_ci Note that this is equivalent to ``bool(expr) is True`` and not to ``expr 9237db96d56Sopenharmony_ci is True`` (use ``assertIs(expr, True)`` for the latter). This method 9247db96d56Sopenharmony_ci should also be avoided when more specific methods are available (e.g. 9257db96d56Sopenharmony_ci ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they 9267db96d56Sopenharmony_ci provide a better error message in case of failure. 9277db96d56Sopenharmony_ci 9287db96d56Sopenharmony_ci 9297db96d56Sopenharmony_ci .. method:: assertIs(first, second, msg=None) 9307db96d56Sopenharmony_ci assertIsNot(first, second, msg=None) 9317db96d56Sopenharmony_ci 9327db96d56Sopenharmony_ci Test that *first* and *second* are (or are not) the same object. 9337db96d56Sopenharmony_ci 9347db96d56Sopenharmony_ci .. versionadded:: 3.1 9357db96d56Sopenharmony_ci 9367db96d56Sopenharmony_ci 9377db96d56Sopenharmony_ci .. method:: assertIsNone(expr, msg=None) 9387db96d56Sopenharmony_ci assertIsNotNone(expr, msg=None) 9397db96d56Sopenharmony_ci 9407db96d56Sopenharmony_ci Test that *expr* is (or is not) ``None``. 9417db96d56Sopenharmony_ci 9427db96d56Sopenharmony_ci .. versionadded:: 3.1 9437db96d56Sopenharmony_ci 9447db96d56Sopenharmony_ci 9457db96d56Sopenharmony_ci .. method:: assertIn(member, container, msg=None) 9467db96d56Sopenharmony_ci assertNotIn(member, container, msg=None) 9477db96d56Sopenharmony_ci 9487db96d56Sopenharmony_ci Test that *member* is (or is not) in *container*. 9497db96d56Sopenharmony_ci 9507db96d56Sopenharmony_ci .. versionadded:: 3.1 9517db96d56Sopenharmony_ci 9527db96d56Sopenharmony_ci 9537db96d56Sopenharmony_ci .. method:: assertIsInstance(obj, cls, msg=None) 9547db96d56Sopenharmony_ci assertNotIsInstance(obj, cls, msg=None) 9557db96d56Sopenharmony_ci 9567db96d56Sopenharmony_ci Test that *obj* is (or is not) an instance of *cls* (which can be a 9577db96d56Sopenharmony_ci class or a tuple of classes, as supported by :func:`isinstance`). 9587db96d56Sopenharmony_ci To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`. 9597db96d56Sopenharmony_ci 9607db96d56Sopenharmony_ci .. versionadded:: 3.2 9617db96d56Sopenharmony_ci 9627db96d56Sopenharmony_ci 9637db96d56Sopenharmony_ci 9647db96d56Sopenharmony_ci It is also possible to check the production of exceptions, warnings, and 9657db96d56Sopenharmony_ci log messages using the following methods: 9667db96d56Sopenharmony_ci 9677db96d56Sopenharmony_ci +---------------------------------------------------------+--------------------------------------+------------+ 9687db96d56Sopenharmony_ci | Method | Checks that | New in | 9697db96d56Sopenharmony_ci +=========================================================+======================================+============+ 9707db96d56Sopenharmony_ci | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | | 9717db96d56Sopenharmony_ci | <TestCase.assertRaises>` | | | 9727db96d56Sopenharmony_ci +---------------------------------------------------------+--------------------------------------+------------+ 9737db96d56Sopenharmony_ci | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 | 9747db96d56Sopenharmony_ci | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | | 9757db96d56Sopenharmony_ci +---------------------------------------------------------+--------------------------------------+------------+ 9767db96d56Sopenharmony_ci | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 | 9777db96d56Sopenharmony_ci | <TestCase.assertWarns>` | | | 9787db96d56Sopenharmony_ci +---------------------------------------------------------+--------------------------------------+------------+ 9797db96d56Sopenharmony_ci | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 | 9807db96d56Sopenharmony_ci | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | | 9817db96d56Sopenharmony_ci +---------------------------------------------------------+--------------------------------------+------------+ 9827db96d56Sopenharmony_ci | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 | 9837db96d56Sopenharmony_ci | <TestCase.assertLogs>` | with minimum *level* | | 9847db96d56Sopenharmony_ci +---------------------------------------------------------+--------------------------------------+------------+ 9857db96d56Sopenharmony_ci | :meth:`assertNoLogs(logger, level) | The ``with`` block does not log on | 3.10 | 9867db96d56Sopenharmony_ci | <TestCase.assertNoLogs>` | *logger* with minimum *level* | | 9877db96d56Sopenharmony_ci +---------------------------------------------------------+--------------------------------------+------------+ 9887db96d56Sopenharmony_ci 9897db96d56Sopenharmony_ci .. method:: assertRaises(exception, callable, *args, **kwds) 9907db96d56Sopenharmony_ci assertRaises(exception, *, msg=None) 9917db96d56Sopenharmony_ci 9927db96d56Sopenharmony_ci Test that an exception is raised when *callable* is called with any 9937db96d56Sopenharmony_ci positional or keyword arguments that are also passed to 9947db96d56Sopenharmony_ci :meth:`assertRaises`. The test passes if *exception* is raised, is an 9957db96d56Sopenharmony_ci error if another exception is raised, or fails if no exception is raised. 9967db96d56Sopenharmony_ci To catch any of a group of exceptions, a tuple containing the exception 9977db96d56Sopenharmony_ci classes may be passed as *exception*. 9987db96d56Sopenharmony_ci 9997db96d56Sopenharmony_ci If only the *exception* and possibly the *msg* arguments are given, 10007db96d56Sopenharmony_ci return a context manager so that the code under test can be written 10017db96d56Sopenharmony_ci inline rather than as a function:: 10027db96d56Sopenharmony_ci 10037db96d56Sopenharmony_ci with self.assertRaises(SomeException): 10047db96d56Sopenharmony_ci do_something() 10057db96d56Sopenharmony_ci 10067db96d56Sopenharmony_ci When used as a context manager, :meth:`assertRaises` accepts the 10077db96d56Sopenharmony_ci additional keyword argument *msg*. 10087db96d56Sopenharmony_ci 10097db96d56Sopenharmony_ci The context manager will store the caught exception object in its 10107db96d56Sopenharmony_ci :attr:`exception` attribute. This can be useful if the intention 10117db96d56Sopenharmony_ci is to perform additional checks on the exception raised:: 10127db96d56Sopenharmony_ci 10137db96d56Sopenharmony_ci with self.assertRaises(SomeException) as cm: 10147db96d56Sopenharmony_ci do_something() 10157db96d56Sopenharmony_ci 10167db96d56Sopenharmony_ci the_exception = cm.exception 10177db96d56Sopenharmony_ci self.assertEqual(the_exception.error_code, 3) 10187db96d56Sopenharmony_ci 10197db96d56Sopenharmony_ci .. versionchanged:: 3.1 10207db96d56Sopenharmony_ci Added the ability to use :meth:`assertRaises` as a context manager. 10217db96d56Sopenharmony_ci 10227db96d56Sopenharmony_ci .. versionchanged:: 3.2 10237db96d56Sopenharmony_ci Added the :attr:`exception` attribute. 10247db96d56Sopenharmony_ci 10257db96d56Sopenharmony_ci .. versionchanged:: 3.3 10267db96d56Sopenharmony_ci Added the *msg* keyword argument when used as a context manager. 10277db96d56Sopenharmony_ci 10287db96d56Sopenharmony_ci 10297db96d56Sopenharmony_ci .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds) 10307db96d56Sopenharmony_ci assertRaisesRegex(exception, regex, *, msg=None) 10317db96d56Sopenharmony_ci 10327db96d56Sopenharmony_ci Like :meth:`assertRaises` but also tests that *regex* matches 10337db96d56Sopenharmony_ci on the string representation of the raised exception. *regex* may be 10347db96d56Sopenharmony_ci a regular expression object or a string containing a regular expression 10357db96d56Sopenharmony_ci suitable for use by :func:`re.search`. Examples:: 10367db96d56Sopenharmony_ci 10377db96d56Sopenharmony_ci self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$", 10387db96d56Sopenharmony_ci int, 'XYZ') 10397db96d56Sopenharmony_ci 10407db96d56Sopenharmony_ci or:: 10417db96d56Sopenharmony_ci 10427db96d56Sopenharmony_ci with self.assertRaisesRegex(ValueError, 'literal'): 10437db96d56Sopenharmony_ci int('XYZ') 10447db96d56Sopenharmony_ci 10457db96d56Sopenharmony_ci .. versionadded:: 3.1 10467db96d56Sopenharmony_ci Added under the name ``assertRaisesRegexp``. 10477db96d56Sopenharmony_ci 10487db96d56Sopenharmony_ci .. versionchanged:: 3.2 10497db96d56Sopenharmony_ci Renamed to :meth:`assertRaisesRegex`. 10507db96d56Sopenharmony_ci 10517db96d56Sopenharmony_ci .. versionchanged:: 3.3 10527db96d56Sopenharmony_ci Added the *msg* keyword argument when used as a context manager. 10537db96d56Sopenharmony_ci 10547db96d56Sopenharmony_ci 10557db96d56Sopenharmony_ci .. method:: assertWarns(warning, callable, *args, **kwds) 10567db96d56Sopenharmony_ci assertWarns(warning, *, msg=None) 10577db96d56Sopenharmony_ci 10587db96d56Sopenharmony_ci Test that a warning is triggered when *callable* is called with any 10597db96d56Sopenharmony_ci positional or keyword arguments that are also passed to 10607db96d56Sopenharmony_ci :meth:`assertWarns`. The test passes if *warning* is triggered and 10617db96d56Sopenharmony_ci fails if it isn't. Any exception is an error. 10627db96d56Sopenharmony_ci To catch any of a group of warnings, a tuple containing the warning 10637db96d56Sopenharmony_ci classes may be passed as *warnings*. 10647db96d56Sopenharmony_ci 10657db96d56Sopenharmony_ci If only the *warning* and possibly the *msg* arguments are given, 10667db96d56Sopenharmony_ci return a context manager so that the code under test can be written 10677db96d56Sopenharmony_ci inline rather than as a function:: 10687db96d56Sopenharmony_ci 10697db96d56Sopenharmony_ci with self.assertWarns(SomeWarning): 10707db96d56Sopenharmony_ci do_something() 10717db96d56Sopenharmony_ci 10727db96d56Sopenharmony_ci When used as a context manager, :meth:`assertWarns` accepts the 10737db96d56Sopenharmony_ci additional keyword argument *msg*. 10747db96d56Sopenharmony_ci 10757db96d56Sopenharmony_ci The context manager will store the caught warning object in its 10767db96d56Sopenharmony_ci :attr:`warning` attribute, and the source line which triggered the 10777db96d56Sopenharmony_ci warnings in the :attr:`filename` and :attr:`lineno` attributes. 10787db96d56Sopenharmony_ci This can be useful if the intention is to perform additional checks 10797db96d56Sopenharmony_ci on the warning caught:: 10807db96d56Sopenharmony_ci 10817db96d56Sopenharmony_ci with self.assertWarns(SomeWarning) as cm: 10827db96d56Sopenharmony_ci do_something() 10837db96d56Sopenharmony_ci 10847db96d56Sopenharmony_ci self.assertIn('myfile.py', cm.filename) 10857db96d56Sopenharmony_ci self.assertEqual(320, cm.lineno) 10867db96d56Sopenharmony_ci 10877db96d56Sopenharmony_ci This method works regardless of the warning filters in place when it 10887db96d56Sopenharmony_ci is called. 10897db96d56Sopenharmony_ci 10907db96d56Sopenharmony_ci .. versionadded:: 3.2 10917db96d56Sopenharmony_ci 10927db96d56Sopenharmony_ci .. versionchanged:: 3.3 10937db96d56Sopenharmony_ci Added the *msg* keyword argument when used as a context manager. 10947db96d56Sopenharmony_ci 10957db96d56Sopenharmony_ci 10967db96d56Sopenharmony_ci .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds) 10977db96d56Sopenharmony_ci assertWarnsRegex(warning, regex, *, msg=None) 10987db96d56Sopenharmony_ci 10997db96d56Sopenharmony_ci Like :meth:`assertWarns` but also tests that *regex* matches on the 11007db96d56Sopenharmony_ci message of the triggered warning. *regex* may be a regular expression 11017db96d56Sopenharmony_ci object or a string containing a regular expression suitable for use 11027db96d56Sopenharmony_ci by :func:`re.search`. Example:: 11037db96d56Sopenharmony_ci 11047db96d56Sopenharmony_ci self.assertWarnsRegex(DeprecationWarning, 11057db96d56Sopenharmony_ci r'legacy_function\(\) is deprecated', 11067db96d56Sopenharmony_ci legacy_function, 'XYZ') 11077db96d56Sopenharmony_ci 11087db96d56Sopenharmony_ci or:: 11097db96d56Sopenharmony_ci 11107db96d56Sopenharmony_ci with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'): 11117db96d56Sopenharmony_ci frobnicate('/etc/passwd') 11127db96d56Sopenharmony_ci 11137db96d56Sopenharmony_ci .. versionadded:: 3.2 11147db96d56Sopenharmony_ci 11157db96d56Sopenharmony_ci .. versionchanged:: 3.3 11167db96d56Sopenharmony_ci Added the *msg* keyword argument when used as a context manager. 11177db96d56Sopenharmony_ci 11187db96d56Sopenharmony_ci .. method:: assertLogs(logger=None, level=None) 11197db96d56Sopenharmony_ci 11207db96d56Sopenharmony_ci A context manager to test that at least one message is logged on 11217db96d56Sopenharmony_ci the *logger* or one of its children, with at least the given 11227db96d56Sopenharmony_ci *level*. 11237db96d56Sopenharmony_ci 11247db96d56Sopenharmony_ci If given, *logger* should be a :class:`logging.Logger` object or a 11257db96d56Sopenharmony_ci :class:`str` giving the name of a logger. The default is the root 11267db96d56Sopenharmony_ci logger, which will catch all messages that were not blocked by a 11277db96d56Sopenharmony_ci non-propagating descendent logger. 11287db96d56Sopenharmony_ci 11297db96d56Sopenharmony_ci If given, *level* should be either a numeric logging level or 11307db96d56Sopenharmony_ci its string equivalent (for example either ``"ERROR"`` or 11317db96d56Sopenharmony_ci :attr:`logging.ERROR`). The default is :attr:`logging.INFO`. 11327db96d56Sopenharmony_ci 11337db96d56Sopenharmony_ci The test passes if at least one message emitted inside the ``with`` 11347db96d56Sopenharmony_ci block matches the *logger* and *level* conditions, otherwise it fails. 11357db96d56Sopenharmony_ci 11367db96d56Sopenharmony_ci The object returned by the context manager is a recording helper 11377db96d56Sopenharmony_ci which keeps tracks of the matching log messages. It has two 11387db96d56Sopenharmony_ci attributes: 11397db96d56Sopenharmony_ci 11407db96d56Sopenharmony_ci .. attribute:: records 11417db96d56Sopenharmony_ci 11427db96d56Sopenharmony_ci A list of :class:`logging.LogRecord` objects of the matching 11437db96d56Sopenharmony_ci log messages. 11447db96d56Sopenharmony_ci 11457db96d56Sopenharmony_ci .. attribute:: output 11467db96d56Sopenharmony_ci 11477db96d56Sopenharmony_ci A list of :class:`str` objects with the formatted output of 11487db96d56Sopenharmony_ci matching messages. 11497db96d56Sopenharmony_ci 11507db96d56Sopenharmony_ci Example:: 11517db96d56Sopenharmony_ci 11527db96d56Sopenharmony_ci with self.assertLogs('foo', level='INFO') as cm: 11537db96d56Sopenharmony_ci logging.getLogger('foo').info('first message') 11547db96d56Sopenharmony_ci logging.getLogger('foo.bar').error('second message') 11557db96d56Sopenharmony_ci self.assertEqual(cm.output, ['INFO:foo:first message', 11567db96d56Sopenharmony_ci 'ERROR:foo.bar:second message']) 11577db96d56Sopenharmony_ci 11587db96d56Sopenharmony_ci .. versionadded:: 3.4 11597db96d56Sopenharmony_ci 11607db96d56Sopenharmony_ci .. method:: assertNoLogs(logger=None, level=None) 11617db96d56Sopenharmony_ci 11627db96d56Sopenharmony_ci A context manager to test that no messages are logged on 11637db96d56Sopenharmony_ci the *logger* or one of its children, with at least the given 11647db96d56Sopenharmony_ci *level*. 11657db96d56Sopenharmony_ci 11667db96d56Sopenharmony_ci If given, *logger* should be a :class:`logging.Logger` object or a 11677db96d56Sopenharmony_ci :class:`str` giving the name of a logger. The default is the root 11687db96d56Sopenharmony_ci logger, which will catch all messages. 11697db96d56Sopenharmony_ci 11707db96d56Sopenharmony_ci If given, *level* should be either a numeric logging level or 11717db96d56Sopenharmony_ci its string equivalent (for example either ``"ERROR"`` or 11727db96d56Sopenharmony_ci :attr:`logging.ERROR`). The default is :attr:`logging.INFO`. 11737db96d56Sopenharmony_ci 11747db96d56Sopenharmony_ci Unlike :meth:`assertLogs`, nothing will be returned by the context 11757db96d56Sopenharmony_ci manager. 11767db96d56Sopenharmony_ci 11777db96d56Sopenharmony_ci .. versionadded:: 3.10 11787db96d56Sopenharmony_ci 11797db96d56Sopenharmony_ci There are also other methods used to perform more specific checks, such as: 11807db96d56Sopenharmony_ci 11817db96d56Sopenharmony_ci +---------------------------------------+--------------------------------+--------------+ 11827db96d56Sopenharmony_ci | Method | Checks that | New in | 11837db96d56Sopenharmony_ci +=======================================+================================+==============+ 11847db96d56Sopenharmony_ci | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | | 11857db96d56Sopenharmony_ci | <TestCase.assertAlmostEqual>` | | | 11867db96d56Sopenharmony_ci +---------------------------------------+--------------------------------+--------------+ 11877db96d56Sopenharmony_ci | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | | 11887db96d56Sopenharmony_ci | <TestCase.assertNotAlmostEqual>` | | | 11897db96d56Sopenharmony_ci +---------------------------------------+--------------------------------+--------------+ 11907db96d56Sopenharmony_ci | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 | 11917db96d56Sopenharmony_ci | <TestCase.assertGreater>` | | | 11927db96d56Sopenharmony_ci +---------------------------------------+--------------------------------+--------------+ 11937db96d56Sopenharmony_ci | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 | 11947db96d56Sopenharmony_ci | <TestCase.assertGreaterEqual>` | | | 11957db96d56Sopenharmony_ci +---------------------------------------+--------------------------------+--------------+ 11967db96d56Sopenharmony_ci | :meth:`assertLess(a, b) | ``a < b`` | 3.1 | 11977db96d56Sopenharmony_ci | <TestCase.assertLess>` | | | 11987db96d56Sopenharmony_ci +---------------------------------------+--------------------------------+--------------+ 11997db96d56Sopenharmony_ci | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 | 12007db96d56Sopenharmony_ci | <TestCase.assertLessEqual>` | | | 12017db96d56Sopenharmony_ci +---------------------------------------+--------------------------------+--------------+ 12027db96d56Sopenharmony_ci | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 | 12037db96d56Sopenharmony_ci | <TestCase.assertRegex>` | | | 12047db96d56Sopenharmony_ci +---------------------------------------+--------------------------------+--------------+ 12057db96d56Sopenharmony_ci | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 | 12067db96d56Sopenharmony_ci | <TestCase.assertNotRegex>` | | | 12077db96d56Sopenharmony_ci +---------------------------------------+--------------------------------+--------------+ 12087db96d56Sopenharmony_ci | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 | 12097db96d56Sopenharmony_ci | <TestCase.assertCountEqual>` | elements in the same number, | | 12107db96d56Sopenharmony_ci | | regardless of their order. | | 12117db96d56Sopenharmony_ci +---------------------------------------+--------------------------------+--------------+ 12127db96d56Sopenharmony_ci 12137db96d56Sopenharmony_ci 12147db96d56Sopenharmony_ci .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None) 12157db96d56Sopenharmony_ci assertNotAlmostEqual(first, second, places=7, msg=None, delta=None) 12167db96d56Sopenharmony_ci 12177db96d56Sopenharmony_ci Test that *first* and *second* are approximately (or not approximately) 12187db96d56Sopenharmony_ci equal by computing the difference, rounding to the given number of 12197db96d56Sopenharmony_ci decimal *places* (default 7), and comparing to zero. Note that these 12207db96d56Sopenharmony_ci methods round the values to the given number of *decimal places* (i.e. 12217db96d56Sopenharmony_ci like the :func:`round` function) and not *significant digits*. 12227db96d56Sopenharmony_ci 12237db96d56Sopenharmony_ci If *delta* is supplied instead of *places* then the difference 12247db96d56Sopenharmony_ci between *first* and *second* must be less or equal to (or greater than) *delta*. 12257db96d56Sopenharmony_ci 12267db96d56Sopenharmony_ci Supplying both *delta* and *places* raises a :exc:`TypeError`. 12277db96d56Sopenharmony_ci 12287db96d56Sopenharmony_ci .. versionchanged:: 3.2 12297db96d56Sopenharmony_ci :meth:`assertAlmostEqual` automatically considers almost equal objects 12307db96d56Sopenharmony_ci that compare equal. :meth:`assertNotAlmostEqual` automatically fails 12317db96d56Sopenharmony_ci if the objects compare equal. Added the *delta* keyword argument. 12327db96d56Sopenharmony_ci 12337db96d56Sopenharmony_ci 12347db96d56Sopenharmony_ci .. method:: assertGreater(first, second, msg=None) 12357db96d56Sopenharmony_ci assertGreaterEqual(first, second, msg=None) 12367db96d56Sopenharmony_ci assertLess(first, second, msg=None) 12377db96d56Sopenharmony_ci assertLessEqual(first, second, msg=None) 12387db96d56Sopenharmony_ci 12397db96d56Sopenharmony_ci Test that *first* is respectively >, >=, < or <= than *second* depending 12407db96d56Sopenharmony_ci on the method name. If not, the test will fail:: 12417db96d56Sopenharmony_ci 12427db96d56Sopenharmony_ci >>> self.assertGreaterEqual(3, 4) 12437db96d56Sopenharmony_ci AssertionError: "3" unexpectedly not greater than or equal to "4" 12447db96d56Sopenharmony_ci 12457db96d56Sopenharmony_ci .. versionadded:: 3.1 12467db96d56Sopenharmony_ci 12477db96d56Sopenharmony_ci 12487db96d56Sopenharmony_ci .. method:: assertRegex(text, regex, msg=None) 12497db96d56Sopenharmony_ci assertNotRegex(text, regex, msg=None) 12507db96d56Sopenharmony_ci 12517db96d56Sopenharmony_ci Test that a *regex* search matches (or does not match) *text*. In case 12527db96d56Sopenharmony_ci of failure, the error message will include the pattern and the *text* (or 12537db96d56Sopenharmony_ci the pattern and the part of *text* that unexpectedly matched). *regex* 12547db96d56Sopenharmony_ci may be a regular expression object or a string containing a regular 12557db96d56Sopenharmony_ci expression suitable for use by :func:`re.search`. 12567db96d56Sopenharmony_ci 12577db96d56Sopenharmony_ci .. versionadded:: 3.1 12587db96d56Sopenharmony_ci Added under the name ``assertRegexpMatches``. 12597db96d56Sopenharmony_ci .. versionchanged:: 3.2 12607db96d56Sopenharmony_ci The method ``assertRegexpMatches()`` has been renamed to 12617db96d56Sopenharmony_ci :meth:`.assertRegex`. 12627db96d56Sopenharmony_ci .. versionadded:: 3.2 12637db96d56Sopenharmony_ci :meth:`.assertNotRegex`. 12647db96d56Sopenharmony_ci .. versionadded:: 3.5 12657db96d56Sopenharmony_ci The name ``assertNotRegexpMatches`` is a deprecated alias 12667db96d56Sopenharmony_ci for :meth:`.assertNotRegex`. 12677db96d56Sopenharmony_ci 12687db96d56Sopenharmony_ci 12697db96d56Sopenharmony_ci .. method:: assertCountEqual(first, second, msg=None) 12707db96d56Sopenharmony_ci 12717db96d56Sopenharmony_ci Test that sequence *first* contains the same elements as *second*, 12727db96d56Sopenharmony_ci regardless of their order. When they don't, an error message listing the 12737db96d56Sopenharmony_ci differences between the sequences will be generated. 12747db96d56Sopenharmony_ci 12757db96d56Sopenharmony_ci Duplicate elements are *not* ignored when comparing *first* and 12767db96d56Sopenharmony_ci *second*. It verifies whether each element has the same count in both 12777db96d56Sopenharmony_ci sequences. Equivalent to: 12787db96d56Sopenharmony_ci ``assertEqual(Counter(list(first)), Counter(list(second)))`` 12797db96d56Sopenharmony_ci but works with sequences of unhashable objects as well. 12807db96d56Sopenharmony_ci 12817db96d56Sopenharmony_ci .. versionadded:: 3.2 12827db96d56Sopenharmony_ci 12837db96d56Sopenharmony_ci 12847db96d56Sopenharmony_ci .. _type-specific-methods: 12857db96d56Sopenharmony_ci 12867db96d56Sopenharmony_ci The :meth:`assertEqual` method dispatches the equality check for objects of 12877db96d56Sopenharmony_ci the same type to different type-specific methods. These methods are already 12887db96d56Sopenharmony_ci implemented for most of the built-in types, but it's also possible to 12897db96d56Sopenharmony_ci register new methods using :meth:`addTypeEqualityFunc`: 12907db96d56Sopenharmony_ci 12917db96d56Sopenharmony_ci .. method:: addTypeEqualityFunc(typeobj, function) 12927db96d56Sopenharmony_ci 12937db96d56Sopenharmony_ci Registers a type-specific method called by :meth:`assertEqual` to check 12947db96d56Sopenharmony_ci if two objects of exactly the same *typeobj* (not subclasses) compare 12957db96d56Sopenharmony_ci equal. *function* must take two positional arguments and a third msg=None 12967db96d56Sopenharmony_ci keyword argument just as :meth:`assertEqual` does. It must raise 12977db96d56Sopenharmony_ci :data:`self.failureException(msg) <failureException>` when inequality 12987db96d56Sopenharmony_ci between the first two parameters is detected -- possibly providing useful 12997db96d56Sopenharmony_ci information and explaining the inequalities in details in the error 13007db96d56Sopenharmony_ci message. 13017db96d56Sopenharmony_ci 13027db96d56Sopenharmony_ci .. versionadded:: 3.1 13037db96d56Sopenharmony_ci 13047db96d56Sopenharmony_ci The list of type-specific methods automatically used by 13057db96d56Sopenharmony_ci :meth:`~TestCase.assertEqual` are summarized in the following table. Note 13067db96d56Sopenharmony_ci that it's usually not necessary to invoke these methods directly. 13077db96d56Sopenharmony_ci 13087db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+--------------+ 13097db96d56Sopenharmony_ci | Method | Used to compare | New in | 13107db96d56Sopenharmony_ci +=========================================+=============================+==============+ 13117db96d56Sopenharmony_ci | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 | 13127db96d56Sopenharmony_ci | <TestCase.assertMultiLineEqual>` | | | 13137db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+--------------+ 13147db96d56Sopenharmony_ci | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 | 13157db96d56Sopenharmony_ci | <TestCase.assertSequenceEqual>` | | | 13167db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+--------------+ 13177db96d56Sopenharmony_ci | :meth:`assertListEqual(a, b) | lists | 3.1 | 13187db96d56Sopenharmony_ci | <TestCase.assertListEqual>` | | | 13197db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+--------------+ 13207db96d56Sopenharmony_ci | :meth:`assertTupleEqual(a, b) | tuples | 3.1 | 13217db96d56Sopenharmony_ci | <TestCase.assertTupleEqual>` | | | 13227db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+--------------+ 13237db96d56Sopenharmony_ci | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 | 13247db96d56Sopenharmony_ci | <TestCase.assertSetEqual>` | | | 13257db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+--------------+ 13267db96d56Sopenharmony_ci | :meth:`assertDictEqual(a, b) | dicts | 3.1 | 13277db96d56Sopenharmony_ci | <TestCase.assertDictEqual>` | | | 13287db96d56Sopenharmony_ci +-----------------------------------------+-----------------------------+--------------+ 13297db96d56Sopenharmony_ci 13307db96d56Sopenharmony_ci 13317db96d56Sopenharmony_ci 13327db96d56Sopenharmony_ci .. method:: assertMultiLineEqual(first, second, msg=None) 13337db96d56Sopenharmony_ci 13347db96d56Sopenharmony_ci Test that the multiline string *first* is equal to the string *second*. 13357db96d56Sopenharmony_ci When not equal a diff of the two strings highlighting the differences 13367db96d56Sopenharmony_ci will be included in the error message. This method is used by default 13377db96d56Sopenharmony_ci when comparing strings with :meth:`assertEqual`. 13387db96d56Sopenharmony_ci 13397db96d56Sopenharmony_ci .. versionadded:: 3.1 13407db96d56Sopenharmony_ci 13417db96d56Sopenharmony_ci 13427db96d56Sopenharmony_ci .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None) 13437db96d56Sopenharmony_ci 13447db96d56Sopenharmony_ci Tests that two sequences are equal. If a *seq_type* is supplied, both 13457db96d56Sopenharmony_ci *first* and *second* must be instances of *seq_type* or a failure will 13467db96d56Sopenharmony_ci be raised. If the sequences are different an error message is 13477db96d56Sopenharmony_ci constructed that shows the difference between the two. 13487db96d56Sopenharmony_ci 13497db96d56Sopenharmony_ci This method is not called directly by :meth:`assertEqual`, but 13507db96d56Sopenharmony_ci it's used to implement :meth:`assertListEqual` and 13517db96d56Sopenharmony_ci :meth:`assertTupleEqual`. 13527db96d56Sopenharmony_ci 13537db96d56Sopenharmony_ci .. versionadded:: 3.1 13547db96d56Sopenharmony_ci 13557db96d56Sopenharmony_ci 13567db96d56Sopenharmony_ci .. method:: assertListEqual(first, second, msg=None) 13577db96d56Sopenharmony_ci assertTupleEqual(first, second, msg=None) 13587db96d56Sopenharmony_ci 13597db96d56Sopenharmony_ci Tests that two lists or tuples are equal. If not, an error message is 13607db96d56Sopenharmony_ci constructed that shows only the differences between the two. An error 13617db96d56Sopenharmony_ci is also raised if either of the parameters are of the wrong type. 13627db96d56Sopenharmony_ci These methods are used by default when comparing lists or tuples with 13637db96d56Sopenharmony_ci :meth:`assertEqual`. 13647db96d56Sopenharmony_ci 13657db96d56Sopenharmony_ci .. versionadded:: 3.1 13667db96d56Sopenharmony_ci 13677db96d56Sopenharmony_ci 13687db96d56Sopenharmony_ci .. method:: assertSetEqual(first, second, msg=None) 13697db96d56Sopenharmony_ci 13707db96d56Sopenharmony_ci Tests that two sets are equal. If not, an error message is constructed 13717db96d56Sopenharmony_ci that lists the differences between the sets. This method is used by 13727db96d56Sopenharmony_ci default when comparing sets or frozensets with :meth:`assertEqual`. 13737db96d56Sopenharmony_ci 13747db96d56Sopenharmony_ci Fails if either of *first* or *second* does not have a :meth:`set.difference` 13757db96d56Sopenharmony_ci method. 13767db96d56Sopenharmony_ci 13777db96d56Sopenharmony_ci .. versionadded:: 3.1 13787db96d56Sopenharmony_ci 13797db96d56Sopenharmony_ci 13807db96d56Sopenharmony_ci .. method:: assertDictEqual(first, second, msg=None) 13817db96d56Sopenharmony_ci 13827db96d56Sopenharmony_ci Test that two dictionaries are equal. If not, an error message is 13837db96d56Sopenharmony_ci constructed that shows the differences in the dictionaries. This 13847db96d56Sopenharmony_ci method will be used by default to compare dictionaries in 13857db96d56Sopenharmony_ci calls to :meth:`assertEqual`. 13867db96d56Sopenharmony_ci 13877db96d56Sopenharmony_ci .. versionadded:: 3.1 13887db96d56Sopenharmony_ci 13897db96d56Sopenharmony_ci 13907db96d56Sopenharmony_ci 13917db96d56Sopenharmony_ci .. _other-methods-and-attrs: 13927db96d56Sopenharmony_ci 13937db96d56Sopenharmony_ci Finally the :class:`TestCase` provides the following methods and attributes: 13947db96d56Sopenharmony_ci 13957db96d56Sopenharmony_ci 13967db96d56Sopenharmony_ci .. method:: fail(msg=None) 13977db96d56Sopenharmony_ci 13987db96d56Sopenharmony_ci Signals a test failure unconditionally, with *msg* or ``None`` for 13997db96d56Sopenharmony_ci the error message. 14007db96d56Sopenharmony_ci 14017db96d56Sopenharmony_ci 14027db96d56Sopenharmony_ci .. attribute:: failureException 14037db96d56Sopenharmony_ci 14047db96d56Sopenharmony_ci This class attribute gives the exception raised by the test method. If a 14057db96d56Sopenharmony_ci test framework needs to use a specialized exception, possibly to carry 14067db96d56Sopenharmony_ci additional information, it must subclass this exception in order to "play 14077db96d56Sopenharmony_ci fair" with the framework. The initial value of this attribute is 14087db96d56Sopenharmony_ci :exc:`AssertionError`. 14097db96d56Sopenharmony_ci 14107db96d56Sopenharmony_ci 14117db96d56Sopenharmony_ci .. attribute:: longMessage 14127db96d56Sopenharmony_ci 14137db96d56Sopenharmony_ci This class attribute determines what happens when a custom failure message 14147db96d56Sopenharmony_ci is passed as the msg argument to an assertXYY call that fails. 14157db96d56Sopenharmony_ci ``True`` is the default value. In this case, the custom message is appended 14167db96d56Sopenharmony_ci to the end of the standard failure message. 14177db96d56Sopenharmony_ci When set to ``False``, the custom message replaces the standard message. 14187db96d56Sopenharmony_ci 14197db96d56Sopenharmony_ci The class setting can be overridden in individual test methods by assigning 14207db96d56Sopenharmony_ci an instance attribute, self.longMessage, to ``True`` or ``False`` before 14217db96d56Sopenharmony_ci calling the assert methods. 14227db96d56Sopenharmony_ci 14237db96d56Sopenharmony_ci The class setting gets reset before each test call. 14247db96d56Sopenharmony_ci 14257db96d56Sopenharmony_ci .. versionadded:: 3.1 14267db96d56Sopenharmony_ci 14277db96d56Sopenharmony_ci 14287db96d56Sopenharmony_ci .. attribute:: maxDiff 14297db96d56Sopenharmony_ci 14307db96d56Sopenharmony_ci This attribute controls the maximum length of diffs output by assert 14317db96d56Sopenharmony_ci methods that report diffs on failure. It defaults to 80*8 characters. 14327db96d56Sopenharmony_ci Assert methods affected by this attribute are 14337db96d56Sopenharmony_ci :meth:`assertSequenceEqual` (including all the sequence comparison 14347db96d56Sopenharmony_ci methods that delegate to it), :meth:`assertDictEqual` and 14357db96d56Sopenharmony_ci :meth:`assertMultiLineEqual`. 14367db96d56Sopenharmony_ci 14377db96d56Sopenharmony_ci Setting ``maxDiff`` to ``None`` means that there is no maximum length of 14387db96d56Sopenharmony_ci diffs. 14397db96d56Sopenharmony_ci 14407db96d56Sopenharmony_ci .. versionadded:: 3.2 14417db96d56Sopenharmony_ci 14427db96d56Sopenharmony_ci 14437db96d56Sopenharmony_ci Testing frameworks can use the following methods to collect information on 14447db96d56Sopenharmony_ci the test: 14457db96d56Sopenharmony_ci 14467db96d56Sopenharmony_ci 14477db96d56Sopenharmony_ci .. method:: countTestCases() 14487db96d56Sopenharmony_ci 14497db96d56Sopenharmony_ci Return the number of tests represented by this test object. For 14507db96d56Sopenharmony_ci :class:`TestCase` instances, this will always be ``1``. 14517db96d56Sopenharmony_ci 14527db96d56Sopenharmony_ci 14537db96d56Sopenharmony_ci .. method:: defaultTestResult() 14547db96d56Sopenharmony_ci 14557db96d56Sopenharmony_ci Return an instance of the test result class that should be used for this 14567db96d56Sopenharmony_ci test case class (if no other result instance is provided to the 14577db96d56Sopenharmony_ci :meth:`run` method). 14587db96d56Sopenharmony_ci 14597db96d56Sopenharmony_ci For :class:`TestCase` instances, this will always be an instance of 14607db96d56Sopenharmony_ci :class:`TestResult`; subclasses of :class:`TestCase` should override this 14617db96d56Sopenharmony_ci as necessary. 14627db96d56Sopenharmony_ci 14637db96d56Sopenharmony_ci 14647db96d56Sopenharmony_ci .. method:: id() 14657db96d56Sopenharmony_ci 14667db96d56Sopenharmony_ci Return a string identifying the specific test case. This is usually the 14677db96d56Sopenharmony_ci full name of the test method, including the module and class name. 14687db96d56Sopenharmony_ci 14697db96d56Sopenharmony_ci 14707db96d56Sopenharmony_ci .. method:: shortDescription() 14717db96d56Sopenharmony_ci 14727db96d56Sopenharmony_ci Returns a description of the test, or ``None`` if no description 14737db96d56Sopenharmony_ci has been provided. The default implementation of this method 14747db96d56Sopenharmony_ci returns the first line of the test method's docstring, if available, 14757db96d56Sopenharmony_ci or ``None``. 14767db96d56Sopenharmony_ci 14777db96d56Sopenharmony_ci .. versionchanged:: 3.1 14787db96d56Sopenharmony_ci In 3.1 this was changed to add the test name to the short description 14797db96d56Sopenharmony_ci even in the presence of a docstring. This caused compatibility issues 14807db96d56Sopenharmony_ci with unittest extensions and adding the test name was moved to the 14817db96d56Sopenharmony_ci :class:`TextTestResult` in Python 3.2. 14827db96d56Sopenharmony_ci 14837db96d56Sopenharmony_ci 14847db96d56Sopenharmony_ci .. method:: addCleanup(function, /, *args, **kwargs) 14857db96d56Sopenharmony_ci 14867db96d56Sopenharmony_ci Add a function to be called after :meth:`tearDown` to cleanup resources 14877db96d56Sopenharmony_ci used during the test. Functions will be called in reverse order to the 14887db96d56Sopenharmony_ci order they are added (:abbr:`LIFO (last-in, first-out)`). They 14897db96d56Sopenharmony_ci are called with any arguments and keyword arguments passed into 14907db96d56Sopenharmony_ci :meth:`addCleanup` when they are added. 14917db96d56Sopenharmony_ci 14927db96d56Sopenharmony_ci If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called, 14937db96d56Sopenharmony_ci then any cleanup functions added will still be called. 14947db96d56Sopenharmony_ci 14957db96d56Sopenharmony_ci .. versionadded:: 3.1 14967db96d56Sopenharmony_ci 14977db96d56Sopenharmony_ci 14987db96d56Sopenharmony_ci .. method:: enterContext(cm) 14997db96d56Sopenharmony_ci 15007db96d56Sopenharmony_ci Enter the supplied :term:`context manager`. If successful, also 15017db96d56Sopenharmony_ci add its :meth:`~object.__exit__` method as a cleanup function by 15027db96d56Sopenharmony_ci :meth:`addCleanup` and return the result of the 15037db96d56Sopenharmony_ci :meth:`~object.__enter__` method. 15047db96d56Sopenharmony_ci 15057db96d56Sopenharmony_ci .. versionadded:: 3.11 15067db96d56Sopenharmony_ci 15077db96d56Sopenharmony_ci 15087db96d56Sopenharmony_ci .. method:: doCleanups() 15097db96d56Sopenharmony_ci 15107db96d56Sopenharmony_ci This method is called unconditionally after :meth:`tearDown`, or 15117db96d56Sopenharmony_ci after :meth:`setUp` if :meth:`setUp` raises an exception. 15127db96d56Sopenharmony_ci 15137db96d56Sopenharmony_ci It is responsible for calling all the cleanup functions added by 15147db96d56Sopenharmony_ci :meth:`addCleanup`. If you need cleanup functions to be called 15157db96d56Sopenharmony_ci *prior* to :meth:`tearDown` then you can call :meth:`doCleanups` 15167db96d56Sopenharmony_ci yourself. 15177db96d56Sopenharmony_ci 15187db96d56Sopenharmony_ci :meth:`doCleanups` pops methods off the stack of cleanup 15197db96d56Sopenharmony_ci functions one at a time, so it can be called at any time. 15207db96d56Sopenharmony_ci 15217db96d56Sopenharmony_ci .. versionadded:: 3.1 15227db96d56Sopenharmony_ci 15237db96d56Sopenharmony_ci 15247db96d56Sopenharmony_ci .. classmethod:: addClassCleanup(function, /, *args, **kwargs) 15257db96d56Sopenharmony_ci 15267db96d56Sopenharmony_ci Add a function to be called after :meth:`tearDownClass` to cleanup 15277db96d56Sopenharmony_ci resources used during the test class. Functions will be called in reverse 15287db96d56Sopenharmony_ci order to the order they are added (:abbr:`LIFO (last-in, first-out)`). 15297db96d56Sopenharmony_ci They are called with any arguments and keyword arguments passed into 15307db96d56Sopenharmony_ci :meth:`addClassCleanup` when they are added. 15317db96d56Sopenharmony_ci 15327db96d56Sopenharmony_ci If :meth:`setUpClass` fails, meaning that :meth:`tearDownClass` is not 15337db96d56Sopenharmony_ci called, then any cleanup functions added will still be called. 15347db96d56Sopenharmony_ci 15357db96d56Sopenharmony_ci .. versionadded:: 3.8 15367db96d56Sopenharmony_ci 15377db96d56Sopenharmony_ci 15387db96d56Sopenharmony_ci .. classmethod:: enterClassContext(cm) 15397db96d56Sopenharmony_ci 15407db96d56Sopenharmony_ci Enter the supplied :term:`context manager`. If successful, also 15417db96d56Sopenharmony_ci add its :meth:`~object.__exit__` method as a cleanup function by 15427db96d56Sopenharmony_ci :meth:`addClassCleanup` and return the result of the 15437db96d56Sopenharmony_ci :meth:`~object.__enter__` method. 15447db96d56Sopenharmony_ci 15457db96d56Sopenharmony_ci .. versionadded:: 3.11 15467db96d56Sopenharmony_ci 15477db96d56Sopenharmony_ci 15487db96d56Sopenharmony_ci .. classmethod:: doClassCleanups() 15497db96d56Sopenharmony_ci 15507db96d56Sopenharmony_ci This method is called unconditionally after :meth:`tearDownClass`, or 15517db96d56Sopenharmony_ci after :meth:`setUpClass` if :meth:`setUpClass` raises an exception. 15527db96d56Sopenharmony_ci 15537db96d56Sopenharmony_ci It is responsible for calling all the cleanup functions added by 15547db96d56Sopenharmony_ci :meth:`addClassCleanup`. If you need cleanup functions to be called 15557db96d56Sopenharmony_ci *prior* to :meth:`tearDownClass` then you can call 15567db96d56Sopenharmony_ci :meth:`doClassCleanups` yourself. 15577db96d56Sopenharmony_ci 15587db96d56Sopenharmony_ci :meth:`doClassCleanups` pops methods off the stack of cleanup 15597db96d56Sopenharmony_ci functions one at a time, so it can be called at any time. 15607db96d56Sopenharmony_ci 15617db96d56Sopenharmony_ci .. versionadded:: 3.8 15627db96d56Sopenharmony_ci 15637db96d56Sopenharmony_ci 15647db96d56Sopenharmony_ci.. class:: IsolatedAsyncioTestCase(methodName='runTest') 15657db96d56Sopenharmony_ci 15667db96d56Sopenharmony_ci This class provides an API similar to :class:`TestCase` and also accepts 15677db96d56Sopenharmony_ci coroutines as test functions. 15687db96d56Sopenharmony_ci 15697db96d56Sopenharmony_ci .. versionadded:: 3.8 15707db96d56Sopenharmony_ci 15717db96d56Sopenharmony_ci .. coroutinemethod:: asyncSetUp() 15727db96d56Sopenharmony_ci 15737db96d56Sopenharmony_ci Method called to prepare the test fixture. This is called after :meth:`setUp`. 15747db96d56Sopenharmony_ci This is called immediately before calling the test method; other than 15757db96d56Sopenharmony_ci :exc:`AssertionError` or :exc:`SkipTest`, any exception raised by this method 15767db96d56Sopenharmony_ci will be considered an error rather than a test failure. The default implementation 15777db96d56Sopenharmony_ci does nothing. 15787db96d56Sopenharmony_ci 15797db96d56Sopenharmony_ci .. coroutinemethod:: asyncTearDown() 15807db96d56Sopenharmony_ci 15817db96d56Sopenharmony_ci Method called immediately after the test method has been called and the 15827db96d56Sopenharmony_ci result recorded. This is called before :meth:`tearDown`. This is called even if 15837db96d56Sopenharmony_ci the test method raised an exception, so the implementation in subclasses may need 15847db96d56Sopenharmony_ci to be particularly careful about checking internal state. Any exception, other than 15857db96d56Sopenharmony_ci :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be 15867db96d56Sopenharmony_ci considered an additional error rather than a test failure (thus increasing 15877db96d56Sopenharmony_ci the total number of reported errors). This method will only be called if 15887db96d56Sopenharmony_ci the :meth:`asyncSetUp` succeeds, regardless of the outcome of the test method. 15897db96d56Sopenharmony_ci The default implementation does nothing. 15907db96d56Sopenharmony_ci 15917db96d56Sopenharmony_ci .. method:: addAsyncCleanup(function, /, *args, **kwargs) 15927db96d56Sopenharmony_ci 15937db96d56Sopenharmony_ci This method accepts a coroutine that can be used as a cleanup function. 15947db96d56Sopenharmony_ci 15957db96d56Sopenharmony_ci .. coroutinemethod:: enterAsyncContext(cm) 15967db96d56Sopenharmony_ci 15977db96d56Sopenharmony_ci Enter the supplied :term:`asynchronous context manager`. If successful, 15987db96d56Sopenharmony_ci also add its :meth:`~object.__aexit__` method as a cleanup function by 15997db96d56Sopenharmony_ci :meth:`addAsyncCleanup` and return the result of the 16007db96d56Sopenharmony_ci :meth:`~object.__aenter__` method. 16017db96d56Sopenharmony_ci 16027db96d56Sopenharmony_ci .. versionadded:: 3.11 16037db96d56Sopenharmony_ci 16047db96d56Sopenharmony_ci 16057db96d56Sopenharmony_ci .. method:: run(result=None) 16067db96d56Sopenharmony_ci 16077db96d56Sopenharmony_ci Sets up a new event loop to run the test, collecting the result into 16087db96d56Sopenharmony_ci the :class:`TestResult` object passed as *result*. If *result* is 16097db96d56Sopenharmony_ci omitted or ``None``, a temporary result object is created (by calling 16107db96d56Sopenharmony_ci the :meth:`defaultTestResult` method) and used. The result object is 16117db96d56Sopenharmony_ci returned to :meth:`run`'s caller. At the end of the test all the tasks 16127db96d56Sopenharmony_ci in the event loop are cancelled. 16137db96d56Sopenharmony_ci 16147db96d56Sopenharmony_ci 16157db96d56Sopenharmony_ci An example illustrating the order:: 16167db96d56Sopenharmony_ci 16177db96d56Sopenharmony_ci from unittest import IsolatedAsyncioTestCase 16187db96d56Sopenharmony_ci 16197db96d56Sopenharmony_ci events = [] 16207db96d56Sopenharmony_ci 16217db96d56Sopenharmony_ci 16227db96d56Sopenharmony_ci class Test(IsolatedAsyncioTestCase): 16237db96d56Sopenharmony_ci 16247db96d56Sopenharmony_ci 16257db96d56Sopenharmony_ci def setUp(self): 16267db96d56Sopenharmony_ci events.append("setUp") 16277db96d56Sopenharmony_ci 16287db96d56Sopenharmony_ci async def asyncSetUp(self): 16297db96d56Sopenharmony_ci self._async_connection = await AsyncConnection() 16307db96d56Sopenharmony_ci events.append("asyncSetUp") 16317db96d56Sopenharmony_ci 16327db96d56Sopenharmony_ci async def test_response(self): 16337db96d56Sopenharmony_ci events.append("test_response") 16347db96d56Sopenharmony_ci response = await self._async_connection.get("https://example.com") 16357db96d56Sopenharmony_ci self.assertEqual(response.status_code, 200) 16367db96d56Sopenharmony_ci self.addAsyncCleanup(self.on_cleanup) 16377db96d56Sopenharmony_ci 16387db96d56Sopenharmony_ci def tearDown(self): 16397db96d56Sopenharmony_ci events.append("tearDown") 16407db96d56Sopenharmony_ci 16417db96d56Sopenharmony_ci async def asyncTearDown(self): 16427db96d56Sopenharmony_ci await self._async_connection.close() 16437db96d56Sopenharmony_ci events.append("asyncTearDown") 16447db96d56Sopenharmony_ci 16457db96d56Sopenharmony_ci async def on_cleanup(self): 16467db96d56Sopenharmony_ci events.append("cleanup") 16477db96d56Sopenharmony_ci 16487db96d56Sopenharmony_ci if __name__ == "__main__": 16497db96d56Sopenharmony_ci unittest.main() 16507db96d56Sopenharmony_ci 16517db96d56Sopenharmony_ci After running the test, ``events`` would contain ``["setUp", "asyncSetUp", "test_response", "asyncTearDown", "tearDown", "cleanup"]``. 16527db96d56Sopenharmony_ci 16537db96d56Sopenharmony_ci 16547db96d56Sopenharmony_ci.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None) 16557db96d56Sopenharmony_ci 16567db96d56Sopenharmony_ci This class implements the portion of the :class:`TestCase` interface which 16577db96d56Sopenharmony_ci allows the test runner to drive the test, but does not provide the methods 16587db96d56Sopenharmony_ci which test code can use to check and report errors. This is used to create 16597db96d56Sopenharmony_ci test cases using legacy test code, allowing it to be integrated into a 16607db96d56Sopenharmony_ci :mod:`unittest`-based test framework. 16617db96d56Sopenharmony_ci 16627db96d56Sopenharmony_ci 16637db96d56Sopenharmony_ci.. _deprecated-aliases: 16647db96d56Sopenharmony_ci 16657db96d56Sopenharmony_ciDeprecated aliases 16667db96d56Sopenharmony_ci################## 16677db96d56Sopenharmony_ci 16687db96d56Sopenharmony_ciFor historical reasons, some of the :class:`TestCase` methods had one or more 16697db96d56Sopenharmony_cialiases that are now deprecated. The following table lists the correct names 16707db96d56Sopenharmony_cialong with their deprecated aliases: 16717db96d56Sopenharmony_ci 16727db96d56Sopenharmony_ci ============================== ====================== ======================= 16737db96d56Sopenharmony_ci Method Name Deprecated alias Deprecated alias 16747db96d56Sopenharmony_ci ============================== ====================== ======================= 16757db96d56Sopenharmony_ci :meth:`.assertEqual` failUnlessEqual assertEquals 16767db96d56Sopenharmony_ci :meth:`.assertNotEqual` failIfEqual assertNotEquals 16777db96d56Sopenharmony_ci :meth:`.assertTrue` failUnless assert\_ 16787db96d56Sopenharmony_ci :meth:`.assertFalse` failIf 16797db96d56Sopenharmony_ci :meth:`.assertRaises` failUnlessRaises 16807db96d56Sopenharmony_ci :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals 16817db96d56Sopenharmony_ci :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals 16827db96d56Sopenharmony_ci :meth:`.assertRegex` assertRegexpMatches 16837db96d56Sopenharmony_ci :meth:`.assertNotRegex` assertNotRegexpMatches 16847db96d56Sopenharmony_ci :meth:`.assertRaisesRegex` assertRaisesRegexp 16857db96d56Sopenharmony_ci ============================== ====================== ======================= 16867db96d56Sopenharmony_ci 16877db96d56Sopenharmony_ci .. deprecated:: 3.1 16887db96d56Sopenharmony_ci The fail* aliases listed in the second column have been deprecated. 16897db96d56Sopenharmony_ci .. deprecated:: 3.2 16907db96d56Sopenharmony_ci The assert* aliases listed in the third column have been deprecated. 16917db96d56Sopenharmony_ci .. deprecated:: 3.2 16927db96d56Sopenharmony_ci ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to 16937db96d56Sopenharmony_ci :meth:`.assertRegex` and :meth:`.assertRaisesRegex`. 16947db96d56Sopenharmony_ci .. deprecated:: 3.5 16957db96d56Sopenharmony_ci The ``assertNotRegexpMatches`` name is deprecated in favor of :meth:`.assertNotRegex`. 16967db96d56Sopenharmony_ci 16977db96d56Sopenharmony_ci.. _testsuite-objects: 16987db96d56Sopenharmony_ci 16997db96d56Sopenharmony_ciGrouping tests 17007db96d56Sopenharmony_ci~~~~~~~~~~~~~~ 17017db96d56Sopenharmony_ci 17027db96d56Sopenharmony_ci.. class:: TestSuite(tests=()) 17037db96d56Sopenharmony_ci 17047db96d56Sopenharmony_ci This class represents an aggregation of individual test cases and test suites. 17057db96d56Sopenharmony_ci The class presents the interface needed by the test runner to allow it to be run 17067db96d56Sopenharmony_ci as any other test case. Running a :class:`TestSuite` instance is the same as 17077db96d56Sopenharmony_ci iterating over the suite, running each test individually. 17087db96d56Sopenharmony_ci 17097db96d56Sopenharmony_ci If *tests* is given, it must be an iterable of individual test cases or other 17107db96d56Sopenharmony_ci test suites that will be used to build the suite initially. Additional methods 17117db96d56Sopenharmony_ci are provided to add test cases and suites to the collection later on. 17127db96d56Sopenharmony_ci 17137db96d56Sopenharmony_ci :class:`TestSuite` objects behave much like :class:`TestCase` objects, except 17147db96d56Sopenharmony_ci they do not actually implement a test. Instead, they are used to aggregate 17157db96d56Sopenharmony_ci tests into groups of tests that should be run together. Some additional 17167db96d56Sopenharmony_ci methods are available to add tests to :class:`TestSuite` instances: 17177db96d56Sopenharmony_ci 17187db96d56Sopenharmony_ci 17197db96d56Sopenharmony_ci .. method:: TestSuite.addTest(test) 17207db96d56Sopenharmony_ci 17217db96d56Sopenharmony_ci Add a :class:`TestCase` or :class:`TestSuite` to the suite. 17227db96d56Sopenharmony_ci 17237db96d56Sopenharmony_ci 17247db96d56Sopenharmony_ci .. method:: TestSuite.addTests(tests) 17257db96d56Sopenharmony_ci 17267db96d56Sopenharmony_ci Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite` 17277db96d56Sopenharmony_ci instances to this test suite. 17287db96d56Sopenharmony_ci 17297db96d56Sopenharmony_ci This is equivalent to iterating over *tests*, calling :meth:`addTest` for 17307db96d56Sopenharmony_ci each element. 17317db96d56Sopenharmony_ci 17327db96d56Sopenharmony_ci :class:`TestSuite` shares the following methods with :class:`TestCase`: 17337db96d56Sopenharmony_ci 17347db96d56Sopenharmony_ci 17357db96d56Sopenharmony_ci .. method:: run(result) 17367db96d56Sopenharmony_ci 17377db96d56Sopenharmony_ci Run the tests associated with this suite, collecting the result into the 17387db96d56Sopenharmony_ci test result object passed as *result*. Note that unlike 17397db96d56Sopenharmony_ci :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to 17407db96d56Sopenharmony_ci be passed in. 17417db96d56Sopenharmony_ci 17427db96d56Sopenharmony_ci 17437db96d56Sopenharmony_ci .. method:: debug() 17447db96d56Sopenharmony_ci 17457db96d56Sopenharmony_ci Run the tests associated with this suite without collecting the 17467db96d56Sopenharmony_ci result. This allows exceptions raised by the test to be propagated to the 17477db96d56Sopenharmony_ci caller and can be used to support running tests under a debugger. 17487db96d56Sopenharmony_ci 17497db96d56Sopenharmony_ci 17507db96d56Sopenharmony_ci .. method:: countTestCases() 17517db96d56Sopenharmony_ci 17527db96d56Sopenharmony_ci Return the number of tests represented by this test object, including all 17537db96d56Sopenharmony_ci individual tests and sub-suites. 17547db96d56Sopenharmony_ci 17557db96d56Sopenharmony_ci 17567db96d56Sopenharmony_ci .. method:: __iter__() 17577db96d56Sopenharmony_ci 17587db96d56Sopenharmony_ci Tests grouped by a :class:`TestSuite` are always accessed by iteration. 17597db96d56Sopenharmony_ci Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note 17607db96d56Sopenharmony_ci that this method may be called several times on a single suite (for 17617db96d56Sopenharmony_ci example when counting tests or comparing for equality) so the tests 17627db96d56Sopenharmony_ci returned by repeated iterations before :meth:`TestSuite.run` must be the 17637db96d56Sopenharmony_ci same for each call iteration. After :meth:`TestSuite.run`, callers should 17647db96d56Sopenharmony_ci not rely on the tests returned by this method unless the caller uses a 17657db96d56Sopenharmony_ci subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve 17667db96d56Sopenharmony_ci test references. 17677db96d56Sopenharmony_ci 17687db96d56Sopenharmony_ci .. versionchanged:: 3.2 17697db96d56Sopenharmony_ci In earlier versions the :class:`TestSuite` accessed tests directly rather 17707db96d56Sopenharmony_ci than through iteration, so overriding :meth:`__iter__` wasn't sufficient 17717db96d56Sopenharmony_ci for providing tests. 17727db96d56Sopenharmony_ci 17737db96d56Sopenharmony_ci .. versionchanged:: 3.4 17747db96d56Sopenharmony_ci In earlier versions the :class:`TestSuite` held references to each 17757db96d56Sopenharmony_ci :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore 17767db96d56Sopenharmony_ci that behavior by overriding :meth:`TestSuite._removeTestAtIndex`. 17777db96d56Sopenharmony_ci 17787db96d56Sopenharmony_ci In the typical usage of a :class:`TestSuite` object, the :meth:`run` method 17797db96d56Sopenharmony_ci is invoked by a :class:`TestRunner` rather than by the end-user test harness. 17807db96d56Sopenharmony_ci 17817db96d56Sopenharmony_ci 17827db96d56Sopenharmony_ciLoading and running tests 17837db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~ 17847db96d56Sopenharmony_ci 17857db96d56Sopenharmony_ci.. class:: TestLoader() 17867db96d56Sopenharmony_ci 17877db96d56Sopenharmony_ci The :class:`TestLoader` class is used to create test suites from classes and 17887db96d56Sopenharmony_ci modules. Normally, there is no need to create an instance of this class; the 17897db96d56Sopenharmony_ci :mod:`unittest` module provides an instance that can be shared as 17907db96d56Sopenharmony_ci :data:`unittest.defaultTestLoader`. Using a subclass or instance, however, 17917db96d56Sopenharmony_ci allows customization of some configurable properties. 17927db96d56Sopenharmony_ci 17937db96d56Sopenharmony_ci :class:`TestLoader` objects have the following attributes: 17947db96d56Sopenharmony_ci 17957db96d56Sopenharmony_ci 17967db96d56Sopenharmony_ci .. attribute:: errors 17977db96d56Sopenharmony_ci 17987db96d56Sopenharmony_ci A list of the non-fatal errors encountered while loading tests. Not reset 17997db96d56Sopenharmony_ci by the loader at any point. Fatal errors are signalled by the relevant 18007db96d56Sopenharmony_ci method raising an exception to the caller. Non-fatal errors are also 18017db96d56Sopenharmony_ci indicated by a synthetic test that will raise the original error when 18027db96d56Sopenharmony_ci run. 18037db96d56Sopenharmony_ci 18047db96d56Sopenharmony_ci .. versionadded:: 3.5 18057db96d56Sopenharmony_ci 18067db96d56Sopenharmony_ci 18077db96d56Sopenharmony_ci :class:`TestLoader` objects have the following methods: 18087db96d56Sopenharmony_ci 18097db96d56Sopenharmony_ci 18107db96d56Sopenharmony_ci .. method:: loadTestsFromTestCase(testCaseClass) 18117db96d56Sopenharmony_ci 18127db96d56Sopenharmony_ci Return a suite of all test cases contained in the :class:`TestCase`\ -derived 18137db96d56Sopenharmony_ci :class:`testCaseClass`. 18147db96d56Sopenharmony_ci 18157db96d56Sopenharmony_ci A test case instance is created for each method named by 18167db96d56Sopenharmony_ci :meth:`getTestCaseNames`. By default these are the method names 18177db96d56Sopenharmony_ci beginning with ``test``. If :meth:`getTestCaseNames` returns no 18187db96d56Sopenharmony_ci methods, but the :meth:`runTest` method is implemented, a single test 18197db96d56Sopenharmony_ci case is created for that method instead. 18207db96d56Sopenharmony_ci 18217db96d56Sopenharmony_ci 18227db96d56Sopenharmony_ci .. method:: loadTestsFromModule(module, pattern=None) 18237db96d56Sopenharmony_ci 18247db96d56Sopenharmony_ci Return a suite of all test cases contained in the given module. This 18257db96d56Sopenharmony_ci method searches *module* for classes derived from :class:`TestCase` and 18267db96d56Sopenharmony_ci creates an instance of the class for each test method defined for the 18277db96d56Sopenharmony_ci class. 18287db96d56Sopenharmony_ci 18297db96d56Sopenharmony_ci .. note:: 18307db96d56Sopenharmony_ci 18317db96d56Sopenharmony_ci While using a hierarchy of :class:`TestCase`\ -derived classes can be 18327db96d56Sopenharmony_ci convenient in sharing fixtures and helper functions, defining test 18337db96d56Sopenharmony_ci methods on base classes that are not intended to be instantiated 18347db96d56Sopenharmony_ci directly does not play well with this method. Doing so, however, can 18357db96d56Sopenharmony_ci be useful when the fixtures are different and defined in subclasses. 18367db96d56Sopenharmony_ci 18377db96d56Sopenharmony_ci If a module provides a ``load_tests`` function it will be called to 18387db96d56Sopenharmony_ci load the tests. This allows modules to customize test loading. 18397db96d56Sopenharmony_ci This is the `load_tests protocol`_. The *pattern* argument is passed as 18407db96d56Sopenharmony_ci the third argument to ``load_tests``. 18417db96d56Sopenharmony_ci 18427db96d56Sopenharmony_ci .. versionchanged:: 3.2 18437db96d56Sopenharmony_ci Support for ``load_tests`` added. 18447db96d56Sopenharmony_ci 18457db96d56Sopenharmony_ci .. versionchanged:: 3.5 18467db96d56Sopenharmony_ci The undocumented and unofficial *use_load_tests* default argument is 18477db96d56Sopenharmony_ci deprecated and ignored, although it is still accepted for backward 18487db96d56Sopenharmony_ci compatibility. The method also now accepts a keyword-only argument 18497db96d56Sopenharmony_ci *pattern* which is passed to ``load_tests`` as the third argument. 18507db96d56Sopenharmony_ci 18517db96d56Sopenharmony_ci 18527db96d56Sopenharmony_ci .. method:: loadTestsFromName(name, module=None) 18537db96d56Sopenharmony_ci 18547db96d56Sopenharmony_ci Return a suite of all test cases given a string specifier. 18557db96d56Sopenharmony_ci 18567db96d56Sopenharmony_ci The specifier *name* is a "dotted name" that may resolve either to a 18577db96d56Sopenharmony_ci module, a test case class, a test method within a test case class, a 18587db96d56Sopenharmony_ci :class:`TestSuite` instance, or a callable object which returns a 18597db96d56Sopenharmony_ci :class:`TestCase` or :class:`TestSuite` instance. These checks are 18607db96d56Sopenharmony_ci applied in the order listed here; that is, a method on a possible test 18617db96d56Sopenharmony_ci case class will be picked up as "a test method within a test case class", 18627db96d56Sopenharmony_ci rather than "a callable object". 18637db96d56Sopenharmony_ci 18647db96d56Sopenharmony_ci For example, if you have a module :mod:`SampleTests` containing a 18657db96d56Sopenharmony_ci :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test 18667db96d56Sopenharmony_ci methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the 18677db96d56Sopenharmony_ci specifier ``'SampleTests.SampleTestCase'`` would cause this method to 18687db96d56Sopenharmony_ci return a suite which will run all three test methods. Using the specifier 18697db96d56Sopenharmony_ci ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test 18707db96d56Sopenharmony_ci suite which will run only the :meth:`test_two` test method. The specifier 18717db96d56Sopenharmony_ci can refer to modules and packages which have not been imported; they will 18727db96d56Sopenharmony_ci be imported as a side-effect. 18737db96d56Sopenharmony_ci 18747db96d56Sopenharmony_ci The method optionally resolves *name* relative to the given *module*. 18757db96d56Sopenharmony_ci 18767db96d56Sopenharmony_ci .. versionchanged:: 3.5 18777db96d56Sopenharmony_ci If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing 18787db96d56Sopenharmony_ci *name* then a synthetic test that raises that error when run will be 18797db96d56Sopenharmony_ci returned. These errors are included in the errors accumulated by 18807db96d56Sopenharmony_ci self.errors. 18817db96d56Sopenharmony_ci 18827db96d56Sopenharmony_ci 18837db96d56Sopenharmony_ci .. method:: loadTestsFromNames(names, module=None) 18847db96d56Sopenharmony_ci 18857db96d56Sopenharmony_ci Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather 18867db96d56Sopenharmony_ci than a single name. The return value is a test suite which supports all 18877db96d56Sopenharmony_ci the tests defined for each name. 18887db96d56Sopenharmony_ci 18897db96d56Sopenharmony_ci 18907db96d56Sopenharmony_ci .. method:: getTestCaseNames(testCaseClass) 18917db96d56Sopenharmony_ci 18927db96d56Sopenharmony_ci Return a sorted sequence of method names found within *testCaseClass*; 18937db96d56Sopenharmony_ci this should be a subclass of :class:`TestCase`. 18947db96d56Sopenharmony_ci 18957db96d56Sopenharmony_ci 18967db96d56Sopenharmony_ci .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None) 18977db96d56Sopenharmony_ci 18987db96d56Sopenharmony_ci Find all the test modules by recursing into subdirectories from the 18997db96d56Sopenharmony_ci specified start directory, and return a TestSuite object containing them. 19007db96d56Sopenharmony_ci Only test files that match *pattern* will be loaded. (Using shell style 19017db96d56Sopenharmony_ci pattern matching.) Only module names that are importable (i.e. are valid 19027db96d56Sopenharmony_ci Python identifiers) will be loaded. 19037db96d56Sopenharmony_ci 19047db96d56Sopenharmony_ci All test modules must be importable from the top level of the project. If 19057db96d56Sopenharmony_ci the start directory is not the top level directory then the top level 19067db96d56Sopenharmony_ci directory must be specified separately. 19077db96d56Sopenharmony_ci 19087db96d56Sopenharmony_ci If importing a module fails, for example due to a syntax error, then 19097db96d56Sopenharmony_ci this will be recorded as a single error and discovery will continue. If 19107db96d56Sopenharmony_ci the import failure is due to :exc:`SkipTest` being raised, it will be 19117db96d56Sopenharmony_ci recorded as a skip instead of an error. 19127db96d56Sopenharmony_ci 19137db96d56Sopenharmony_ci If a package (a directory containing a file named :file:`__init__.py`) is 19147db96d56Sopenharmony_ci found, the package will be checked for a ``load_tests`` function. If this 19157db96d56Sopenharmony_ci exists then it will be called 19167db96d56Sopenharmony_ci ``package.load_tests(loader, tests, pattern)``. Test discovery takes care 19177db96d56Sopenharmony_ci to ensure that a package is only checked for tests once during an 19187db96d56Sopenharmony_ci invocation, even if the load_tests function itself calls 19197db96d56Sopenharmony_ci ``loader.discover``. 19207db96d56Sopenharmony_ci 19217db96d56Sopenharmony_ci If ``load_tests`` exists then discovery does *not* recurse into the 19227db96d56Sopenharmony_ci package, ``load_tests`` is responsible for loading all tests in the 19237db96d56Sopenharmony_ci package. 19247db96d56Sopenharmony_ci 19257db96d56Sopenharmony_ci The pattern is deliberately not stored as a loader attribute so that 19267db96d56Sopenharmony_ci packages can continue discovery themselves. *top_level_dir* is stored so 19277db96d56Sopenharmony_ci ``load_tests`` does not need to pass this argument in to 19287db96d56Sopenharmony_ci ``loader.discover()``. 19297db96d56Sopenharmony_ci 19307db96d56Sopenharmony_ci *start_dir* can be a dotted module name as well as a directory. 19317db96d56Sopenharmony_ci 19327db96d56Sopenharmony_ci .. versionadded:: 3.2 19337db96d56Sopenharmony_ci 19347db96d56Sopenharmony_ci .. versionchanged:: 3.4 19357db96d56Sopenharmony_ci Modules that raise :exc:`SkipTest` on import are recorded as skips, 19367db96d56Sopenharmony_ci not errors. 19377db96d56Sopenharmony_ci 19387db96d56Sopenharmony_ci .. versionchanged:: 3.4 19397db96d56Sopenharmony_ci *start_dir* can be a :term:`namespace packages <namespace package>`. 19407db96d56Sopenharmony_ci 19417db96d56Sopenharmony_ci .. versionchanged:: 3.4 19427db96d56Sopenharmony_ci Paths are sorted before being imported so that execution order is the 19437db96d56Sopenharmony_ci same even if the underlying file system's ordering is not dependent 19447db96d56Sopenharmony_ci on file name. 19457db96d56Sopenharmony_ci 19467db96d56Sopenharmony_ci .. versionchanged:: 3.5 19477db96d56Sopenharmony_ci Found packages are now checked for ``load_tests`` regardless of 19487db96d56Sopenharmony_ci whether their path matches *pattern*, because it is impossible for 19497db96d56Sopenharmony_ci a package name to match the default pattern. 19507db96d56Sopenharmony_ci 19517db96d56Sopenharmony_ci .. versionchanged:: 3.11 19527db96d56Sopenharmony_ci *start_dir* can not be a :term:`namespace packages <namespace package>`. 19537db96d56Sopenharmony_ci It has been broken since Python 3.7 and Python 3.11 officially remove it. 19547db96d56Sopenharmony_ci 19557db96d56Sopenharmony_ci 19567db96d56Sopenharmony_ci The following attributes of a :class:`TestLoader` can be configured either by 19577db96d56Sopenharmony_ci subclassing or assignment on an instance: 19587db96d56Sopenharmony_ci 19597db96d56Sopenharmony_ci 19607db96d56Sopenharmony_ci .. attribute:: testMethodPrefix 19617db96d56Sopenharmony_ci 19627db96d56Sopenharmony_ci String giving the prefix of method names which will be interpreted as test 19637db96d56Sopenharmony_ci methods. The default value is ``'test'``. 19647db96d56Sopenharmony_ci 19657db96d56Sopenharmony_ci This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` 19667db96d56Sopenharmony_ci methods. 19677db96d56Sopenharmony_ci 19687db96d56Sopenharmony_ci 19697db96d56Sopenharmony_ci .. attribute:: sortTestMethodsUsing 19707db96d56Sopenharmony_ci 19717db96d56Sopenharmony_ci Function to be used to compare method names when sorting them in 19727db96d56Sopenharmony_ci :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. 19737db96d56Sopenharmony_ci 19747db96d56Sopenharmony_ci 19757db96d56Sopenharmony_ci .. attribute:: suiteClass 19767db96d56Sopenharmony_ci 19777db96d56Sopenharmony_ci Callable object that constructs a test suite from a list of tests. No 19787db96d56Sopenharmony_ci methods on the resulting object are needed. The default value is the 19797db96d56Sopenharmony_ci :class:`TestSuite` class. 19807db96d56Sopenharmony_ci 19817db96d56Sopenharmony_ci This affects all the :meth:`loadTestsFrom\*` methods. 19827db96d56Sopenharmony_ci 19837db96d56Sopenharmony_ci .. attribute:: testNamePatterns 19847db96d56Sopenharmony_ci 19857db96d56Sopenharmony_ci List of Unix shell-style wildcard test name patterns that test methods 19867db96d56Sopenharmony_ci have to match to be included in test suites (see ``-k`` option). 19877db96d56Sopenharmony_ci 19887db96d56Sopenharmony_ci If this attribute is not ``None`` (the default), all test methods to be 19897db96d56Sopenharmony_ci included in test suites must match one of the patterns in this list. 19907db96d56Sopenharmony_ci Note that matches are always performed using :meth:`fnmatch.fnmatchcase`, 19917db96d56Sopenharmony_ci so unlike patterns passed to the ``-k`` option, simple substring patterns 19927db96d56Sopenharmony_ci will have to be converted using ``*`` wildcards. 19937db96d56Sopenharmony_ci 19947db96d56Sopenharmony_ci This affects all the :meth:`loadTestsFrom\*` methods. 19957db96d56Sopenharmony_ci 19967db96d56Sopenharmony_ci .. versionadded:: 3.7 19977db96d56Sopenharmony_ci 19987db96d56Sopenharmony_ci 19997db96d56Sopenharmony_ci.. class:: TestResult 20007db96d56Sopenharmony_ci 20017db96d56Sopenharmony_ci This class is used to compile information about which tests have succeeded 20027db96d56Sopenharmony_ci and which have failed. 20037db96d56Sopenharmony_ci 20047db96d56Sopenharmony_ci A :class:`TestResult` object stores the results of a set of tests. The 20057db96d56Sopenharmony_ci :class:`TestCase` and :class:`TestSuite` classes ensure that results are 20067db96d56Sopenharmony_ci properly recorded; test authors do not need to worry about recording the 20077db96d56Sopenharmony_ci outcome of tests. 20087db96d56Sopenharmony_ci 20097db96d56Sopenharmony_ci Testing frameworks built on top of :mod:`unittest` may want access to the 20107db96d56Sopenharmony_ci :class:`TestResult` object generated by running a set of tests for reporting 20117db96d56Sopenharmony_ci purposes; a :class:`TestResult` instance is returned by the 20127db96d56Sopenharmony_ci :meth:`TestRunner.run` method for this purpose. 20137db96d56Sopenharmony_ci 20147db96d56Sopenharmony_ci :class:`TestResult` instances have the following attributes that will be of 20157db96d56Sopenharmony_ci interest when inspecting the results of running a set of tests: 20167db96d56Sopenharmony_ci 20177db96d56Sopenharmony_ci 20187db96d56Sopenharmony_ci .. attribute:: errors 20197db96d56Sopenharmony_ci 20207db96d56Sopenharmony_ci A list containing 2-tuples of :class:`TestCase` instances and strings 20217db96d56Sopenharmony_ci holding formatted tracebacks. Each tuple represents a test which raised an 20227db96d56Sopenharmony_ci unexpected exception. 20237db96d56Sopenharmony_ci 20247db96d56Sopenharmony_ci .. attribute:: failures 20257db96d56Sopenharmony_ci 20267db96d56Sopenharmony_ci A list containing 2-tuples of :class:`TestCase` instances and strings 20277db96d56Sopenharmony_ci holding formatted tracebacks. Each tuple represents a test where a failure 20287db96d56Sopenharmony_ci was explicitly signalled using the :meth:`TestCase.assert\*` methods. 20297db96d56Sopenharmony_ci 20307db96d56Sopenharmony_ci .. attribute:: skipped 20317db96d56Sopenharmony_ci 20327db96d56Sopenharmony_ci A list containing 2-tuples of :class:`TestCase` instances and strings 20337db96d56Sopenharmony_ci holding the reason for skipping the test. 20347db96d56Sopenharmony_ci 20357db96d56Sopenharmony_ci .. versionadded:: 3.1 20367db96d56Sopenharmony_ci 20377db96d56Sopenharmony_ci .. attribute:: expectedFailures 20387db96d56Sopenharmony_ci 20397db96d56Sopenharmony_ci A list containing 2-tuples of :class:`TestCase` instances and strings 20407db96d56Sopenharmony_ci holding formatted tracebacks. Each tuple represents an expected failure 20417db96d56Sopenharmony_ci or error of the test case. 20427db96d56Sopenharmony_ci 20437db96d56Sopenharmony_ci .. attribute:: unexpectedSuccesses 20447db96d56Sopenharmony_ci 20457db96d56Sopenharmony_ci A list containing :class:`TestCase` instances that were marked as expected 20467db96d56Sopenharmony_ci failures, but succeeded. 20477db96d56Sopenharmony_ci 20487db96d56Sopenharmony_ci .. attribute:: shouldStop 20497db96d56Sopenharmony_ci 20507db96d56Sopenharmony_ci Set to ``True`` when the execution of tests should stop by :meth:`stop`. 20517db96d56Sopenharmony_ci 20527db96d56Sopenharmony_ci .. attribute:: testsRun 20537db96d56Sopenharmony_ci 20547db96d56Sopenharmony_ci The total number of tests run so far. 20557db96d56Sopenharmony_ci 20567db96d56Sopenharmony_ci .. attribute:: buffer 20577db96d56Sopenharmony_ci 20587db96d56Sopenharmony_ci If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between 20597db96d56Sopenharmony_ci :meth:`startTest` and :meth:`stopTest` being called. Collected output will 20607db96d56Sopenharmony_ci only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test 20617db96d56Sopenharmony_ci fails or errors. Any output is also attached to the failure / error message. 20627db96d56Sopenharmony_ci 20637db96d56Sopenharmony_ci .. versionadded:: 3.2 20647db96d56Sopenharmony_ci 20657db96d56Sopenharmony_ci .. attribute:: failfast 20667db96d56Sopenharmony_ci 20677db96d56Sopenharmony_ci If set to true :meth:`stop` will be called on the first failure or error, 20687db96d56Sopenharmony_ci halting the test run. 20697db96d56Sopenharmony_ci 20707db96d56Sopenharmony_ci .. versionadded:: 3.2 20717db96d56Sopenharmony_ci 20727db96d56Sopenharmony_ci .. attribute:: tb_locals 20737db96d56Sopenharmony_ci 20747db96d56Sopenharmony_ci If set to true then local variables will be shown in tracebacks. 20757db96d56Sopenharmony_ci 20767db96d56Sopenharmony_ci .. versionadded:: 3.5 20777db96d56Sopenharmony_ci 20787db96d56Sopenharmony_ci .. method:: wasSuccessful() 20797db96d56Sopenharmony_ci 20807db96d56Sopenharmony_ci Return ``True`` if all tests run so far have passed, otherwise returns 20817db96d56Sopenharmony_ci ``False``. 20827db96d56Sopenharmony_ci 20837db96d56Sopenharmony_ci .. versionchanged:: 3.4 20847db96d56Sopenharmony_ci Returns ``False`` if there were any :attr:`unexpectedSuccesses` 20857db96d56Sopenharmony_ci from tests marked with the :func:`expectedFailure` decorator. 20867db96d56Sopenharmony_ci 20877db96d56Sopenharmony_ci .. method:: stop() 20887db96d56Sopenharmony_ci 20897db96d56Sopenharmony_ci This method can be called to signal that the set of tests being run should 20907db96d56Sopenharmony_ci be aborted by setting the :attr:`shouldStop` attribute to ``True``. 20917db96d56Sopenharmony_ci :class:`TestRunner` objects should respect this flag and return without 20927db96d56Sopenharmony_ci running any additional tests. 20937db96d56Sopenharmony_ci 20947db96d56Sopenharmony_ci For example, this feature is used by the :class:`TextTestRunner` class to 20957db96d56Sopenharmony_ci stop the test framework when the user signals an interrupt from the 20967db96d56Sopenharmony_ci keyboard. Interactive tools which provide :class:`TestRunner` 20977db96d56Sopenharmony_ci implementations can use this in a similar manner. 20987db96d56Sopenharmony_ci 20997db96d56Sopenharmony_ci The following methods of the :class:`TestResult` class are used to maintain 21007db96d56Sopenharmony_ci the internal data structures, and may be extended in subclasses to support 21017db96d56Sopenharmony_ci additional reporting requirements. This is particularly useful in building 21027db96d56Sopenharmony_ci tools which support interactive reporting while tests are being run. 21037db96d56Sopenharmony_ci 21047db96d56Sopenharmony_ci 21057db96d56Sopenharmony_ci .. method:: startTest(test) 21067db96d56Sopenharmony_ci 21077db96d56Sopenharmony_ci Called when the test case *test* is about to be run. 21087db96d56Sopenharmony_ci 21097db96d56Sopenharmony_ci .. method:: stopTest(test) 21107db96d56Sopenharmony_ci 21117db96d56Sopenharmony_ci Called after the test case *test* has been executed, regardless of the 21127db96d56Sopenharmony_ci outcome. 21137db96d56Sopenharmony_ci 21147db96d56Sopenharmony_ci .. method:: startTestRun() 21157db96d56Sopenharmony_ci 21167db96d56Sopenharmony_ci Called once before any tests are executed. 21177db96d56Sopenharmony_ci 21187db96d56Sopenharmony_ci .. versionadded:: 3.1 21197db96d56Sopenharmony_ci 21207db96d56Sopenharmony_ci 21217db96d56Sopenharmony_ci .. method:: stopTestRun() 21227db96d56Sopenharmony_ci 21237db96d56Sopenharmony_ci Called once after all tests are executed. 21247db96d56Sopenharmony_ci 21257db96d56Sopenharmony_ci .. versionadded:: 3.1 21267db96d56Sopenharmony_ci 21277db96d56Sopenharmony_ci 21287db96d56Sopenharmony_ci .. method:: addError(test, err) 21297db96d56Sopenharmony_ci 21307db96d56Sopenharmony_ci Called when the test case *test* raises an unexpected exception. *err* is a 21317db96d56Sopenharmony_ci tuple of the form returned by :func:`sys.exc_info`: ``(type, value, 21327db96d56Sopenharmony_ci traceback)``. 21337db96d56Sopenharmony_ci 21347db96d56Sopenharmony_ci The default implementation appends a tuple ``(test, formatted_err)`` to 21357db96d56Sopenharmony_ci the instance's :attr:`errors` attribute, where *formatted_err* is a 21367db96d56Sopenharmony_ci formatted traceback derived from *err*. 21377db96d56Sopenharmony_ci 21387db96d56Sopenharmony_ci 21397db96d56Sopenharmony_ci .. method:: addFailure(test, err) 21407db96d56Sopenharmony_ci 21417db96d56Sopenharmony_ci Called when the test case *test* signals a failure. *err* is a tuple of 21427db96d56Sopenharmony_ci the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``. 21437db96d56Sopenharmony_ci 21447db96d56Sopenharmony_ci The default implementation appends a tuple ``(test, formatted_err)`` to 21457db96d56Sopenharmony_ci the instance's :attr:`failures` attribute, where *formatted_err* is a 21467db96d56Sopenharmony_ci formatted traceback derived from *err*. 21477db96d56Sopenharmony_ci 21487db96d56Sopenharmony_ci 21497db96d56Sopenharmony_ci .. method:: addSuccess(test) 21507db96d56Sopenharmony_ci 21517db96d56Sopenharmony_ci Called when the test case *test* succeeds. 21527db96d56Sopenharmony_ci 21537db96d56Sopenharmony_ci The default implementation does nothing. 21547db96d56Sopenharmony_ci 21557db96d56Sopenharmony_ci 21567db96d56Sopenharmony_ci .. method:: addSkip(test, reason) 21577db96d56Sopenharmony_ci 21587db96d56Sopenharmony_ci Called when the test case *test* is skipped. *reason* is the reason the 21597db96d56Sopenharmony_ci test gave for skipping. 21607db96d56Sopenharmony_ci 21617db96d56Sopenharmony_ci The default implementation appends a tuple ``(test, reason)`` to the 21627db96d56Sopenharmony_ci instance's :attr:`skipped` attribute. 21637db96d56Sopenharmony_ci 21647db96d56Sopenharmony_ci 21657db96d56Sopenharmony_ci .. method:: addExpectedFailure(test, err) 21667db96d56Sopenharmony_ci 21677db96d56Sopenharmony_ci Called when the test case *test* fails or errors, but was marked with 21687db96d56Sopenharmony_ci the :func:`expectedFailure` decorator. 21697db96d56Sopenharmony_ci 21707db96d56Sopenharmony_ci The default implementation appends a tuple ``(test, formatted_err)`` to 21717db96d56Sopenharmony_ci the instance's :attr:`expectedFailures` attribute, where *formatted_err* 21727db96d56Sopenharmony_ci is a formatted traceback derived from *err*. 21737db96d56Sopenharmony_ci 21747db96d56Sopenharmony_ci 21757db96d56Sopenharmony_ci .. method:: addUnexpectedSuccess(test) 21767db96d56Sopenharmony_ci 21777db96d56Sopenharmony_ci Called when the test case *test* was marked with the 21787db96d56Sopenharmony_ci :func:`expectedFailure` decorator, but succeeded. 21797db96d56Sopenharmony_ci 21807db96d56Sopenharmony_ci The default implementation appends the test to the instance's 21817db96d56Sopenharmony_ci :attr:`unexpectedSuccesses` attribute. 21827db96d56Sopenharmony_ci 21837db96d56Sopenharmony_ci 21847db96d56Sopenharmony_ci .. method:: addSubTest(test, subtest, outcome) 21857db96d56Sopenharmony_ci 21867db96d56Sopenharmony_ci Called when a subtest finishes. *test* is the test case 21877db96d56Sopenharmony_ci corresponding to the test method. *subtest* is a custom 21887db96d56Sopenharmony_ci :class:`TestCase` instance describing the subtest. 21897db96d56Sopenharmony_ci 21907db96d56Sopenharmony_ci If *outcome* is :const:`None`, the subtest succeeded. Otherwise, 21917db96d56Sopenharmony_ci it failed with an exception where *outcome* is a tuple of the form 21927db96d56Sopenharmony_ci returned by :func:`sys.exc_info`: ``(type, value, traceback)``. 21937db96d56Sopenharmony_ci 21947db96d56Sopenharmony_ci The default implementation does nothing when the outcome is a 21957db96d56Sopenharmony_ci success, and records subtest failures as normal failures. 21967db96d56Sopenharmony_ci 21977db96d56Sopenharmony_ci .. versionadded:: 3.4 21987db96d56Sopenharmony_ci 21997db96d56Sopenharmony_ci 22007db96d56Sopenharmony_ci.. class:: TextTestResult(stream, descriptions, verbosity) 22017db96d56Sopenharmony_ci 22027db96d56Sopenharmony_ci A concrete implementation of :class:`TestResult` used by the 22037db96d56Sopenharmony_ci :class:`TextTestRunner`. 22047db96d56Sopenharmony_ci 22057db96d56Sopenharmony_ci .. versionadded:: 3.2 22067db96d56Sopenharmony_ci This class was previously named ``_TextTestResult``. The old name still 22077db96d56Sopenharmony_ci exists as an alias but is deprecated. 22087db96d56Sopenharmony_ci 22097db96d56Sopenharmony_ci 22107db96d56Sopenharmony_ci.. data:: defaultTestLoader 22117db96d56Sopenharmony_ci 22127db96d56Sopenharmony_ci Instance of the :class:`TestLoader` class intended to be shared. If no 22137db96d56Sopenharmony_ci customization of the :class:`TestLoader` is needed, this instance can be used 22147db96d56Sopenharmony_ci instead of repeatedly creating new instances. 22157db96d56Sopenharmony_ci 22167db96d56Sopenharmony_ci 22177db96d56Sopenharmony_ci.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \ 22187db96d56Sopenharmony_ci buffer=False, resultclass=None, warnings=None, *, tb_locals=False) 22197db96d56Sopenharmony_ci 22207db96d56Sopenharmony_ci A basic test runner implementation that outputs results to a stream. If *stream* 22217db96d56Sopenharmony_ci is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class 22227db96d56Sopenharmony_ci has a few configurable parameters, but is essentially very simple. Graphical 22237db96d56Sopenharmony_ci applications which run test suites should provide alternate implementations. Such 22247db96d56Sopenharmony_ci implementations should accept ``**kwargs`` as the interface to construct runners 22257db96d56Sopenharmony_ci changes when features are added to unittest. 22267db96d56Sopenharmony_ci 22277db96d56Sopenharmony_ci By default this runner shows :exc:`DeprecationWarning`, 22287db96d56Sopenharmony_ci :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and 22297db96d56Sopenharmony_ci :exc:`ImportWarning` even if they are :ref:`ignored by default 22307db96d56Sopenharmony_ci <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest 22317db96d56Sopenharmony_ci methods <deprecated-aliases>` are also special-cased and, when the warning 22327db96d56Sopenharmony_ci filters are ``'default'`` or ``'always'``, they will appear only once 22337db96d56Sopenharmony_ci per-module, in order to avoid too many warning messages. This behavior can 22347db96d56Sopenharmony_ci be overridden using Python's :option:`!-Wd` or :option:`!-Wa` options 22357db96d56Sopenharmony_ci (see :ref:`Warning control <using-on-warnings>`) and leaving 22367db96d56Sopenharmony_ci *warnings* to ``None``. 22377db96d56Sopenharmony_ci 22387db96d56Sopenharmony_ci .. versionchanged:: 3.2 22397db96d56Sopenharmony_ci Added the ``warnings`` argument. 22407db96d56Sopenharmony_ci 22417db96d56Sopenharmony_ci .. versionchanged:: 3.2 22427db96d56Sopenharmony_ci The default stream is set to :data:`sys.stderr` at instantiation time rather 22437db96d56Sopenharmony_ci than import time. 22447db96d56Sopenharmony_ci 22457db96d56Sopenharmony_ci .. versionchanged:: 3.5 22467db96d56Sopenharmony_ci Added the tb_locals parameter. 22477db96d56Sopenharmony_ci 22487db96d56Sopenharmony_ci .. method:: _makeResult() 22497db96d56Sopenharmony_ci 22507db96d56Sopenharmony_ci This method returns the instance of ``TestResult`` used by :meth:`run`. 22517db96d56Sopenharmony_ci It is not intended to be called directly, but can be overridden in 22527db96d56Sopenharmony_ci subclasses to provide a custom ``TestResult``. 22537db96d56Sopenharmony_ci 22547db96d56Sopenharmony_ci ``_makeResult()`` instantiates the class or callable passed in the 22557db96d56Sopenharmony_ci ``TextTestRunner`` constructor as the ``resultclass`` argument. It 22567db96d56Sopenharmony_ci defaults to :class:`TextTestResult` if no ``resultclass`` is provided. 22577db96d56Sopenharmony_ci The result class is instantiated with the following arguments:: 22587db96d56Sopenharmony_ci 22597db96d56Sopenharmony_ci stream, descriptions, verbosity 22607db96d56Sopenharmony_ci 22617db96d56Sopenharmony_ci .. method:: run(test) 22627db96d56Sopenharmony_ci 22637db96d56Sopenharmony_ci This method is the main public interface to the ``TextTestRunner``. This 22647db96d56Sopenharmony_ci method takes a :class:`TestSuite` or :class:`TestCase` instance. A 22657db96d56Sopenharmony_ci :class:`TestResult` is created by calling 22667db96d56Sopenharmony_ci :func:`_makeResult` and the test(s) are run and the 22677db96d56Sopenharmony_ci results printed to stdout. 22687db96d56Sopenharmony_ci 22697db96d56Sopenharmony_ci 22707db96d56Sopenharmony_ci.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \ 22717db96d56Sopenharmony_ci testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \ 22727db96d56Sopenharmony_ci failfast=None, catchbreak=None, buffer=None, warnings=None) 22737db96d56Sopenharmony_ci 22747db96d56Sopenharmony_ci A command-line program that loads a set of tests from *module* and runs them; 22757db96d56Sopenharmony_ci this is primarily for making test modules conveniently executable. 22767db96d56Sopenharmony_ci The simplest use for this function is to include the following line at the 22777db96d56Sopenharmony_ci end of a test script:: 22787db96d56Sopenharmony_ci 22797db96d56Sopenharmony_ci if __name__ == '__main__': 22807db96d56Sopenharmony_ci unittest.main() 22817db96d56Sopenharmony_ci 22827db96d56Sopenharmony_ci You can run tests with more detailed information by passing in the verbosity 22837db96d56Sopenharmony_ci argument:: 22847db96d56Sopenharmony_ci 22857db96d56Sopenharmony_ci if __name__ == '__main__': 22867db96d56Sopenharmony_ci unittest.main(verbosity=2) 22877db96d56Sopenharmony_ci 22887db96d56Sopenharmony_ci The *defaultTest* argument is either the name of a single test or an 22897db96d56Sopenharmony_ci iterable of test names to run if no test names are specified via *argv*. If 22907db96d56Sopenharmony_ci not specified or ``None`` and no test names are provided via *argv*, all 22917db96d56Sopenharmony_ci tests found in *module* are run. 22927db96d56Sopenharmony_ci 22937db96d56Sopenharmony_ci The *argv* argument can be a list of options passed to the program, with the 22947db96d56Sopenharmony_ci first element being the program name. If not specified or ``None``, 22957db96d56Sopenharmony_ci the values of :data:`sys.argv` are used. 22967db96d56Sopenharmony_ci 22977db96d56Sopenharmony_ci The *testRunner* argument can either be a test runner class or an already 22987db96d56Sopenharmony_ci created instance of it. By default ``main`` calls :func:`sys.exit` with 22997db96d56Sopenharmony_ci an exit code indicating success or failure of the tests run. 23007db96d56Sopenharmony_ci 23017db96d56Sopenharmony_ci The *testLoader* argument has to be a :class:`TestLoader` instance, 23027db96d56Sopenharmony_ci and defaults to :data:`defaultTestLoader`. 23037db96d56Sopenharmony_ci 23047db96d56Sopenharmony_ci ``main`` supports being used from the interactive interpreter by passing in the 23057db96d56Sopenharmony_ci argument ``exit=False``. This displays the result on standard output without 23067db96d56Sopenharmony_ci calling :func:`sys.exit`:: 23077db96d56Sopenharmony_ci 23087db96d56Sopenharmony_ci >>> from unittest import main 23097db96d56Sopenharmony_ci >>> main(module='test_module', exit=False) 23107db96d56Sopenharmony_ci 23117db96d56Sopenharmony_ci The *failfast*, *catchbreak* and *buffer* parameters have the same 23127db96d56Sopenharmony_ci effect as the same-name `command-line options`_. 23137db96d56Sopenharmony_ci 23147db96d56Sopenharmony_ci The *warnings* argument specifies the :ref:`warning filter <warning-filter>` 23157db96d56Sopenharmony_ci that should be used while running the tests. If it's not specified, it will 23167db96d56Sopenharmony_ci remain ``None`` if a :option:`!-W` option is passed to :program:`python` 23177db96d56Sopenharmony_ci (see :ref:`Warning control <using-on-warnings>`), 23187db96d56Sopenharmony_ci otherwise it will be set to ``'default'``. 23197db96d56Sopenharmony_ci 23207db96d56Sopenharmony_ci Calling ``main`` actually returns an instance of the ``TestProgram`` class. 23217db96d56Sopenharmony_ci This stores the result of the tests run as the ``result`` attribute. 23227db96d56Sopenharmony_ci 23237db96d56Sopenharmony_ci .. versionchanged:: 3.1 23247db96d56Sopenharmony_ci The *exit* parameter was added. 23257db96d56Sopenharmony_ci 23267db96d56Sopenharmony_ci .. versionchanged:: 3.2 23277db96d56Sopenharmony_ci The *verbosity*, *failfast*, *catchbreak*, *buffer* 23287db96d56Sopenharmony_ci and *warnings* parameters were added. 23297db96d56Sopenharmony_ci 23307db96d56Sopenharmony_ci .. versionchanged:: 3.4 23317db96d56Sopenharmony_ci The *defaultTest* parameter was changed to also accept an iterable of 23327db96d56Sopenharmony_ci test names. 23337db96d56Sopenharmony_ci 23347db96d56Sopenharmony_ci 23357db96d56Sopenharmony_ciload_tests Protocol 23367db96d56Sopenharmony_ci################### 23377db96d56Sopenharmony_ci 23387db96d56Sopenharmony_ci.. versionadded:: 3.2 23397db96d56Sopenharmony_ci 23407db96d56Sopenharmony_ciModules or packages can customize how tests are loaded from them during normal 23417db96d56Sopenharmony_citest runs or test discovery by implementing a function called ``load_tests``. 23427db96d56Sopenharmony_ci 23437db96d56Sopenharmony_ciIf a test module defines ``load_tests`` it will be called by 23447db96d56Sopenharmony_ci:meth:`TestLoader.loadTestsFromModule` with the following arguments:: 23457db96d56Sopenharmony_ci 23467db96d56Sopenharmony_ci load_tests(loader, standard_tests, pattern) 23477db96d56Sopenharmony_ci 23487db96d56Sopenharmony_ciwhere *pattern* is passed straight through from ``loadTestsFromModule``. It 23497db96d56Sopenharmony_cidefaults to ``None``. 23507db96d56Sopenharmony_ci 23517db96d56Sopenharmony_ciIt should return a :class:`TestSuite`. 23527db96d56Sopenharmony_ci 23537db96d56Sopenharmony_ci*loader* is the instance of :class:`TestLoader` doing the loading. 23547db96d56Sopenharmony_ci*standard_tests* are the tests that would be loaded by default from the 23557db96d56Sopenharmony_cimodule. It is common for test modules to only want to add or remove tests 23567db96d56Sopenharmony_cifrom the standard set of tests. 23577db96d56Sopenharmony_ciThe third argument is used when loading packages as part of test discovery. 23587db96d56Sopenharmony_ci 23597db96d56Sopenharmony_ciA typical ``load_tests`` function that loads tests from a specific set of 23607db96d56Sopenharmony_ci:class:`TestCase` classes may look like:: 23617db96d56Sopenharmony_ci 23627db96d56Sopenharmony_ci test_cases = (TestCase1, TestCase2, TestCase3) 23637db96d56Sopenharmony_ci 23647db96d56Sopenharmony_ci def load_tests(loader, tests, pattern): 23657db96d56Sopenharmony_ci suite = TestSuite() 23667db96d56Sopenharmony_ci for test_class in test_cases: 23677db96d56Sopenharmony_ci tests = loader.loadTestsFromTestCase(test_class) 23687db96d56Sopenharmony_ci suite.addTests(tests) 23697db96d56Sopenharmony_ci return suite 23707db96d56Sopenharmony_ci 23717db96d56Sopenharmony_ciIf discovery is started in a directory containing a package, either from the 23727db96d56Sopenharmony_cicommand line or by calling :meth:`TestLoader.discover`, then the package 23737db96d56Sopenharmony_ci:file:`__init__.py` will be checked for ``load_tests``. If that function does 23747db96d56Sopenharmony_cinot exist, discovery will recurse into the package as though it were just 23757db96d56Sopenharmony_cianother directory. Otherwise, discovery of the package's tests will be left up 23767db96d56Sopenharmony_cito ``load_tests`` which is called with the following arguments:: 23777db96d56Sopenharmony_ci 23787db96d56Sopenharmony_ci load_tests(loader, standard_tests, pattern) 23797db96d56Sopenharmony_ci 23807db96d56Sopenharmony_ciThis should return a :class:`TestSuite` representing all the tests 23817db96d56Sopenharmony_cifrom the package. (``standard_tests`` will only contain tests 23827db96d56Sopenharmony_cicollected from :file:`__init__.py`.) 23837db96d56Sopenharmony_ci 23847db96d56Sopenharmony_ciBecause the pattern is passed into ``load_tests`` the package is free to 23857db96d56Sopenharmony_cicontinue (and potentially modify) test discovery. A 'do nothing' 23867db96d56Sopenharmony_ci``load_tests`` function for a test package would look like:: 23877db96d56Sopenharmony_ci 23887db96d56Sopenharmony_ci def load_tests(loader, standard_tests, pattern): 23897db96d56Sopenharmony_ci # top level directory cached on loader instance 23907db96d56Sopenharmony_ci this_dir = os.path.dirname(__file__) 23917db96d56Sopenharmony_ci package_tests = loader.discover(start_dir=this_dir, pattern=pattern) 23927db96d56Sopenharmony_ci standard_tests.addTests(package_tests) 23937db96d56Sopenharmony_ci return standard_tests 23947db96d56Sopenharmony_ci 23957db96d56Sopenharmony_ci.. versionchanged:: 3.5 23967db96d56Sopenharmony_ci Discovery no longer checks package names for matching *pattern* due to the 23977db96d56Sopenharmony_ci impossibility of package names matching the default pattern. 23987db96d56Sopenharmony_ci 23997db96d56Sopenharmony_ci 24007db96d56Sopenharmony_ci 24017db96d56Sopenharmony_ciClass and Module Fixtures 24027db96d56Sopenharmony_ci------------------------- 24037db96d56Sopenharmony_ci 24047db96d56Sopenharmony_ciClass and module level fixtures are implemented in :class:`TestSuite`. When 24057db96d56Sopenharmony_cithe test suite encounters a test from a new class then :meth:`tearDownClass` 24067db96d56Sopenharmony_cifrom the previous class (if there is one) is called, followed by 24077db96d56Sopenharmony_ci:meth:`setUpClass` from the new class. 24087db96d56Sopenharmony_ci 24097db96d56Sopenharmony_ciSimilarly if a test is from a different module from the previous test then 24107db96d56Sopenharmony_ci``tearDownModule`` from the previous module is run, followed by 24117db96d56Sopenharmony_ci``setUpModule`` from the new module. 24127db96d56Sopenharmony_ci 24137db96d56Sopenharmony_ciAfter all the tests have run the final ``tearDownClass`` and 24147db96d56Sopenharmony_ci``tearDownModule`` are run. 24157db96d56Sopenharmony_ci 24167db96d56Sopenharmony_ciNote that shared fixtures do not play well with [potential] features like test 24177db96d56Sopenharmony_ciparallelization and they break test isolation. They should be used with care. 24187db96d56Sopenharmony_ci 24197db96d56Sopenharmony_ciThe default ordering of tests created by the unittest test loaders is to group 24207db96d56Sopenharmony_ciall tests from the same modules and classes together. This will lead to 24217db96d56Sopenharmony_ci``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and 24227db96d56Sopenharmony_cimodule. If you randomize the order, so that tests from different modules and 24237db96d56Sopenharmony_ciclasses are adjacent to each other, then these shared fixture functions may be 24247db96d56Sopenharmony_cicalled multiple times in a single test run. 24257db96d56Sopenharmony_ci 24267db96d56Sopenharmony_ciShared fixtures are not intended to work with suites with non-standard 24277db96d56Sopenharmony_ciordering. A ``BaseTestSuite`` still exists for frameworks that don't want to 24287db96d56Sopenharmony_cisupport shared fixtures. 24297db96d56Sopenharmony_ci 24307db96d56Sopenharmony_ciIf there are any exceptions raised during one of the shared fixture functions 24317db96d56Sopenharmony_cithe test is reported as an error. Because there is no corresponding test 24327db96d56Sopenharmony_ciinstance an ``_ErrorHolder`` object (that has the same interface as a 24337db96d56Sopenharmony_ci:class:`TestCase`) is created to represent the error. If you are just using 24347db96d56Sopenharmony_cithe standard unittest test runner then this detail doesn't matter, but if you 24357db96d56Sopenharmony_ciare a framework author it may be relevant. 24367db96d56Sopenharmony_ci 24377db96d56Sopenharmony_ci 24387db96d56Sopenharmony_cisetUpClass and tearDownClass 24397db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 24407db96d56Sopenharmony_ci 24417db96d56Sopenharmony_ciThese must be implemented as class methods:: 24427db96d56Sopenharmony_ci 24437db96d56Sopenharmony_ci import unittest 24447db96d56Sopenharmony_ci 24457db96d56Sopenharmony_ci class Test(unittest.TestCase): 24467db96d56Sopenharmony_ci @classmethod 24477db96d56Sopenharmony_ci def setUpClass(cls): 24487db96d56Sopenharmony_ci cls._connection = createExpensiveConnectionObject() 24497db96d56Sopenharmony_ci 24507db96d56Sopenharmony_ci @classmethod 24517db96d56Sopenharmony_ci def tearDownClass(cls): 24527db96d56Sopenharmony_ci cls._connection.destroy() 24537db96d56Sopenharmony_ci 24547db96d56Sopenharmony_ciIf you want the ``setUpClass`` and ``tearDownClass`` on base classes called 24557db96d56Sopenharmony_cithen you must call up to them yourself. The implementations in 24567db96d56Sopenharmony_ci:class:`TestCase` are empty. 24577db96d56Sopenharmony_ci 24587db96d56Sopenharmony_ciIf an exception is raised during a ``setUpClass`` then the tests in the class 24597db96d56Sopenharmony_ciare not run and the ``tearDownClass`` is not run. Skipped classes will not 24607db96d56Sopenharmony_cihave ``setUpClass`` or ``tearDownClass`` run. If the exception is a 24617db96d56Sopenharmony_ci:exc:`SkipTest` exception then the class will be reported as having been skipped 24627db96d56Sopenharmony_ciinstead of as an error. 24637db96d56Sopenharmony_ci 24647db96d56Sopenharmony_ci 24657db96d56Sopenharmony_cisetUpModule and tearDownModule 24667db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 24677db96d56Sopenharmony_ci 24687db96d56Sopenharmony_ciThese should be implemented as functions:: 24697db96d56Sopenharmony_ci 24707db96d56Sopenharmony_ci def setUpModule(): 24717db96d56Sopenharmony_ci createConnection() 24727db96d56Sopenharmony_ci 24737db96d56Sopenharmony_ci def tearDownModule(): 24747db96d56Sopenharmony_ci closeConnection() 24757db96d56Sopenharmony_ci 24767db96d56Sopenharmony_ciIf an exception is raised in a ``setUpModule`` then none of the tests in the 24777db96d56Sopenharmony_cimodule will be run and the ``tearDownModule`` will not be run. If the exception is a 24787db96d56Sopenharmony_ci:exc:`SkipTest` exception then the module will be reported as having been skipped 24797db96d56Sopenharmony_ciinstead of as an error. 24807db96d56Sopenharmony_ci 24817db96d56Sopenharmony_ciTo add cleanup code that must be run even in the case of an exception, use 24827db96d56Sopenharmony_ci``addModuleCleanup``: 24837db96d56Sopenharmony_ci 24847db96d56Sopenharmony_ci 24857db96d56Sopenharmony_ci.. function:: addModuleCleanup(function, /, *args, **kwargs) 24867db96d56Sopenharmony_ci 24877db96d56Sopenharmony_ci Add a function to be called after :func:`tearDownModule` to cleanup 24887db96d56Sopenharmony_ci resources used during the test class. Functions will be called in reverse 24897db96d56Sopenharmony_ci order to the order they are added (:abbr:`LIFO (last-in, first-out)`). 24907db96d56Sopenharmony_ci They are called with any arguments and keyword arguments passed into 24917db96d56Sopenharmony_ci :meth:`addModuleCleanup` when they are added. 24927db96d56Sopenharmony_ci 24937db96d56Sopenharmony_ci If :meth:`setUpModule` fails, meaning that :func:`tearDownModule` is not 24947db96d56Sopenharmony_ci called, then any cleanup functions added will still be called. 24957db96d56Sopenharmony_ci 24967db96d56Sopenharmony_ci .. versionadded:: 3.8 24977db96d56Sopenharmony_ci 24987db96d56Sopenharmony_ci 24997db96d56Sopenharmony_ci.. classmethod:: enterModuleContext(cm) 25007db96d56Sopenharmony_ci 25017db96d56Sopenharmony_ci Enter the supplied :term:`context manager`. If successful, also 25027db96d56Sopenharmony_ci add its :meth:`~object.__exit__` method as a cleanup function by 25037db96d56Sopenharmony_ci :func:`addModuleCleanup` and return the result of the 25047db96d56Sopenharmony_ci :meth:`~object.__enter__` method. 25057db96d56Sopenharmony_ci 25067db96d56Sopenharmony_ci .. versionadded:: 3.11 25077db96d56Sopenharmony_ci 25087db96d56Sopenharmony_ci 25097db96d56Sopenharmony_ci.. function:: doModuleCleanups() 25107db96d56Sopenharmony_ci 25117db96d56Sopenharmony_ci This function is called unconditionally after :func:`tearDownModule`, or 25127db96d56Sopenharmony_ci after :func:`setUpModule` if :func:`setUpModule` raises an exception. 25137db96d56Sopenharmony_ci 25147db96d56Sopenharmony_ci It is responsible for calling all the cleanup functions added by 25157db96d56Sopenharmony_ci :func:`addModuleCleanup`. If you need cleanup functions to be called 25167db96d56Sopenharmony_ci *prior* to :func:`tearDownModule` then you can call 25177db96d56Sopenharmony_ci :func:`doModuleCleanups` yourself. 25187db96d56Sopenharmony_ci 25197db96d56Sopenharmony_ci :func:`doModuleCleanups` pops methods off the stack of cleanup 25207db96d56Sopenharmony_ci functions one at a time, so it can be called at any time. 25217db96d56Sopenharmony_ci 25227db96d56Sopenharmony_ci .. versionadded:: 3.8 25237db96d56Sopenharmony_ci 25247db96d56Sopenharmony_ci 25257db96d56Sopenharmony_ciSignal Handling 25267db96d56Sopenharmony_ci--------------- 25277db96d56Sopenharmony_ci 25287db96d56Sopenharmony_ci.. versionadded:: 3.2 25297db96d56Sopenharmony_ci 25307db96d56Sopenharmony_ciThe :option:`-c/--catch <unittest -c>` command-line option to unittest, 25317db96d56Sopenharmony_cialong with the ``catchbreak`` parameter to :func:`unittest.main()`, provide 25327db96d56Sopenharmony_cimore friendly handling of control-C during a test run. With catch break 25337db96d56Sopenharmony_cibehavior enabled control-C will allow the currently running test to complete, 25347db96d56Sopenharmony_ciand the test run will then end and report all the results so far. A second 25357db96d56Sopenharmony_cicontrol-c will raise a :exc:`KeyboardInterrupt` in the usual way. 25367db96d56Sopenharmony_ci 25377db96d56Sopenharmony_ciThe control-c handling signal handler attempts to remain compatible with code or 25387db96d56Sopenharmony_citests that install their own :const:`signal.SIGINT` handler. If the ``unittest`` 25397db96d56Sopenharmony_cihandler is called but *isn't* the installed :const:`signal.SIGINT` handler, 25407db96d56Sopenharmony_cii.e. it has been replaced by the system under test and delegated to, then it 25417db96d56Sopenharmony_cicalls the default handler. This will normally be the expected behavior by code 25427db96d56Sopenharmony_cithat replaces an installed handler and delegates to it. For individual tests 25437db96d56Sopenharmony_cithat need ``unittest`` control-c handling disabled the :func:`removeHandler` 25447db96d56Sopenharmony_cidecorator can be used. 25457db96d56Sopenharmony_ci 25467db96d56Sopenharmony_ciThere are a few utility functions for framework authors to enable control-c 25477db96d56Sopenharmony_cihandling functionality within test frameworks. 25487db96d56Sopenharmony_ci 25497db96d56Sopenharmony_ci.. function:: installHandler() 25507db96d56Sopenharmony_ci 25517db96d56Sopenharmony_ci Install the control-c handler. When a :const:`signal.SIGINT` is received 25527db96d56Sopenharmony_ci (usually in response to the user pressing control-c) all registered results 25537db96d56Sopenharmony_ci have :meth:`~TestResult.stop` called. 25547db96d56Sopenharmony_ci 25557db96d56Sopenharmony_ci 25567db96d56Sopenharmony_ci.. function:: registerResult(result) 25577db96d56Sopenharmony_ci 25587db96d56Sopenharmony_ci Register a :class:`TestResult` object for control-c handling. Registering a 25597db96d56Sopenharmony_ci result stores a weak reference to it, so it doesn't prevent the result from 25607db96d56Sopenharmony_ci being garbage collected. 25617db96d56Sopenharmony_ci 25627db96d56Sopenharmony_ci Registering a :class:`TestResult` object has no side-effects if control-c 25637db96d56Sopenharmony_ci handling is not enabled, so test frameworks can unconditionally register 25647db96d56Sopenharmony_ci all results they create independently of whether or not handling is enabled. 25657db96d56Sopenharmony_ci 25667db96d56Sopenharmony_ci 25677db96d56Sopenharmony_ci.. function:: removeResult(result) 25687db96d56Sopenharmony_ci 25697db96d56Sopenharmony_ci Remove a registered result. Once a result has been removed then 25707db96d56Sopenharmony_ci :meth:`~TestResult.stop` will no longer be called on that result object in 25717db96d56Sopenharmony_ci response to a control-c. 25727db96d56Sopenharmony_ci 25737db96d56Sopenharmony_ci 25747db96d56Sopenharmony_ci.. function:: removeHandler(function=None) 25757db96d56Sopenharmony_ci 25767db96d56Sopenharmony_ci When called without arguments this function removes the control-c handler 25777db96d56Sopenharmony_ci if it has been installed. This function can also be used as a test decorator 25787db96d56Sopenharmony_ci to temporarily remove the handler while the test is being executed:: 25797db96d56Sopenharmony_ci 25807db96d56Sopenharmony_ci @unittest.removeHandler 25817db96d56Sopenharmony_ci def test_signal_handling(self): 25827db96d56Sopenharmony_ci ... 2583