1:mod:`unittest` --- Unit testing framework 2========================================== 3 4.. module:: unittest 5 :synopsis: Unit testing framework for Python. 6 7.. moduleauthor:: Steve Purcell <[email protected]> 8.. sectionauthor:: Steve Purcell <[email protected]> 9.. sectionauthor:: Fred L. Drake, Jr. <[email protected]> 10.. sectionauthor:: Raymond Hettinger <[email protected]> 11 12**Source code:** :source:`Lib/unittest/__init__.py` 13 14-------------- 15 16(If you are already familiar with the basic concepts of testing, you might want 17to skip to :ref:`the list of assert methods <assert-methods>`.) 18 19The :mod:`unittest` unit testing framework was originally inspired by JUnit 20and has a similar flavor as major unit testing frameworks in other 21languages. It supports test automation, sharing of setup and shutdown code 22for tests, aggregation of tests into collections, and independence of the 23tests from the reporting framework. 24 25To achieve this, :mod:`unittest` supports some important concepts in an 26object-oriented way: 27 28test fixture 29 A :dfn:`test fixture` represents the preparation needed to perform one or more 30 tests, and any associated cleanup actions. This may involve, for example, 31 creating temporary or proxy databases, directories, or starting a server 32 process. 33 34test case 35 A :dfn:`test case` is the individual unit of testing. It checks for a specific 36 response to a particular set of inputs. :mod:`unittest` provides a base class, 37 :class:`TestCase`, which may be used to create new test cases. 38 39test suite 40 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is 41 used to aggregate tests that should be executed together. 42 43test runner 44 A :dfn:`test runner` is a component which orchestrates the execution of tests 45 and provides the outcome to the user. The runner may use a graphical interface, 46 a textual interface, or return a special value to indicate the results of 47 executing the tests. 48 49 50.. seealso:: 51 52 Module :mod:`doctest` 53 Another test-support module with a very different flavor. 54 55 `Simple Smalltalk Testing: With Patterns <https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm>`_ 56 Kent Beck's original paper on testing frameworks using the pattern shared 57 by :mod:`unittest`. 58 59 `pytest <https://docs.pytest.org/>`_ 60 Third-party unittest framework with a lighter-weight syntax for writing 61 tests. For example, ``assert func(10) == 42``. 62 63 `The Python Testing Tools Taxonomy <https://wiki.python.org/moin/PythonTestingToolsTaxonomy>`_ 64 An extensive list of Python testing tools including functional testing 65 frameworks and mock object libraries. 66 67 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_ 68 A special-interest-group for discussion of testing, and testing tools, 69 in Python. 70 71 The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is 72 a GUI tool for test discovery and execution. This is intended largely for ease of use 73 for those new to unit testing. For production environments it is 74 recommended that tests be driven by a continuous integration system such as 75 `Buildbot <https://buildbot.net/>`_, `Jenkins <https://www.jenkins.io/>`_, 76 `GitHub Actions <https://github.com/features/actions>`_, or 77 `AppVeyor <https://www.appveyor.com/>`_. 78 79 80.. _unittest-minimal-example: 81 82Basic example 83------------- 84 85The :mod:`unittest` module provides a rich set of tools for constructing and 86running tests. This section demonstrates that a small subset of the tools 87suffice to meet the needs of most users. 88 89Here is a short script to test three string methods:: 90 91 import unittest 92 93 class TestStringMethods(unittest.TestCase): 94 95 def test_upper(self): 96 self.assertEqual('foo'.upper(), 'FOO') 97 98 def test_isupper(self): 99 self.assertTrue('FOO'.isupper()) 100 self.assertFalse('Foo'.isupper()) 101 102 def test_split(self): 103 s = 'hello world' 104 self.assertEqual(s.split(), ['hello', 'world']) 105 # check that s.split fails when the separator is not a string 106 with self.assertRaises(TypeError): 107 s.split(2) 108 109 if __name__ == '__main__': 110 unittest.main() 111 112 113A testcase is created by subclassing :class:`unittest.TestCase`. The three 114individual tests are defined with methods whose names start with the letters 115``test``. This naming convention informs the test runner about which methods 116represent tests. 117 118The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an 119expected result; :meth:`~TestCase.assertTrue` or :meth:`~TestCase.assertFalse` 120to verify a condition; or :meth:`~TestCase.assertRaises` to verify that a 121specific exception gets raised. These methods are used instead of the 122:keyword:`assert` statement so the test runner can accumulate all test results 123and produce a report. 124 125The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you 126to define instructions that will be executed before and after each test method. 127They are covered in more detail in the section :ref:`organizing-tests`. 128 129The final block shows a simple way to run the tests. :func:`unittest.main` 130provides a command-line interface to the test script. When run from the command 131line, the above script produces an output that looks like this:: 132 133 ... 134 ---------------------------------------------------------------------- 135 Ran 3 tests in 0.000s 136 137 OK 138 139Passing the ``-v`` option to your test script will instruct :func:`unittest.main` 140to enable a higher level of verbosity, and produce the following output:: 141 142 test_isupper (__main__.TestStringMethods.test_isupper) ... ok 143 test_split (__main__.TestStringMethods.test_split) ... ok 144 test_upper (__main__.TestStringMethods.test_upper) ... ok 145 146 ---------------------------------------------------------------------- 147 Ran 3 tests in 0.001s 148 149 OK 150 151The above examples show the most commonly used :mod:`unittest` features which 152are sufficient to meet many everyday testing needs. The remainder of the 153documentation explores the full feature set from first principles. 154 155.. versionchanged:: 3.11 156 The behavior of returning a value from a test method (other than the default 157 ``None`` value), is now deprecated. 158 159 160.. _unittest-command-line-interface: 161 162Command-Line Interface 163---------------------- 164 165The unittest module can be used from the command line to run tests from 166modules, classes or even individual test methods:: 167 168 python -m unittest test_module1 test_module2 169 python -m unittest test_module.TestClass 170 python -m unittest test_module.TestClass.test_method 171 172You can pass in a list with any combination of module names, and fully 173qualified class or method names. 174 175Test modules can be specified by file path as well:: 176 177 python -m unittest tests/test_something.py 178 179This allows you to use the shell filename completion to specify the test module. 180The file specified must still be importable as a module. The path is converted 181to a module name by removing the '.py' and converting path separators into '.'. 182If you want to execute a test file that isn't importable as a module you should 183execute the file directly instead. 184 185You can run tests with more detail (higher verbosity) by passing in the -v flag:: 186 187 python -m unittest -v test_module 188 189When executed without arguments :ref:`unittest-test-discovery` is started:: 190 191 python -m unittest 192 193For a list of all the command-line options:: 194 195 python -m unittest -h 196 197.. versionchanged:: 3.2 198 In earlier versions it was only possible to run individual test methods and 199 not modules or classes. 200 201 202Command-line options 203~~~~~~~~~~~~~~~~~~~~ 204 205:program:`unittest` supports these command-line options: 206 207.. program:: unittest 208 209.. cmdoption:: -b, --buffer 210 211 The standard output and standard error streams are buffered during the test 212 run. Output during a passing test is discarded. Output is echoed normally 213 on test fail or error and is added to the failure messages. 214 215.. cmdoption:: -c, --catch 216 217 :kbd:`Control-C` during the test run waits for the current test to end and then 218 reports all the results so far. A second :kbd:`Control-C` raises the normal 219 :exc:`KeyboardInterrupt` exception. 220 221 See `Signal Handling`_ for the functions that provide this functionality. 222 223.. cmdoption:: -f, --failfast 224 225 Stop the test run on the first error or failure. 226 227.. cmdoption:: -k 228 229 Only run test methods and classes that match the pattern or substring. 230 This option may be used multiple times, in which case all test cases that 231 match any of the given patterns are included. 232 233 Patterns that contain a wildcard character (``*``) are matched against the 234 test name using :meth:`fnmatch.fnmatchcase`; otherwise simple case-sensitive 235 substring matching is used. 236 237 Patterns are matched against the fully qualified test method name as 238 imported by the test loader. 239 240 For example, ``-k foo`` matches ``foo_tests.SomeTest.test_something``, 241 ``bar_tests.SomeTest.test_foo``, but not ``bar_tests.FooTest.test_something``. 242 243.. cmdoption:: --locals 244 245 Show local variables in tracebacks. 246 247.. versionadded:: 3.2 248 The command-line options ``-b``, ``-c`` and ``-f`` were added. 249 250.. versionadded:: 3.5 251 The command-line option ``--locals``. 252 253.. versionadded:: 3.7 254 The command-line option ``-k``. 255 256The command line can also be used for test discovery, for running all of the 257tests in a project or just a subset. 258 259 260.. _unittest-test-discovery: 261 262Test Discovery 263-------------- 264 265.. versionadded:: 3.2 266 267Unittest supports simple test discovery. In order to be compatible with test 268discovery, all of the test files must be :ref:`modules <tut-modules>` or 269:ref:`packages <tut-packages>` importable from the top-level directory of 270the project (this means that their filenames must be valid :ref:`identifiers 271<identifiers>`). 272 273Test discovery is implemented in :meth:`TestLoader.discover`, but can also be 274used from the command line. The basic command-line usage is:: 275 276 cd project_directory 277 python -m unittest discover 278 279.. note:: 280 281 As a shortcut, ``python -m unittest`` is the equivalent of 282 ``python -m unittest discover``. If you want to pass arguments to test 283 discovery the ``discover`` sub-command must be used explicitly. 284 285The ``discover`` sub-command has the following options: 286 287.. program:: unittest discover 288 289.. cmdoption:: -v, --verbose 290 291 Verbose output 292 293.. cmdoption:: -s, --start-directory directory 294 295 Directory to start discovery (``.`` default) 296 297.. cmdoption:: -p, --pattern pattern 298 299 Pattern to match test files (``test*.py`` default) 300 301.. cmdoption:: -t, --top-level-directory directory 302 303 Top level directory of project (defaults to start directory) 304 305The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in 306as positional arguments in that order. The following two command lines 307are equivalent:: 308 309 python -m unittest discover -s project_directory -p "*_test.py" 310 python -m unittest discover project_directory "*_test.py" 311 312As well as being a path it is possible to pass a package name, for example 313``myproject.subpackage.test``, as the start directory. The package name you 314supply will then be imported and its location on the filesystem will be used 315as the start directory. 316 317.. caution:: 318 319 Test discovery loads tests by importing them. Once test discovery has found 320 all the test files from the start directory you specify it turns the paths 321 into package names to import. For example :file:`foo/bar/baz.py` will be 322 imported as ``foo.bar.baz``. 323 324 If you have a package installed globally and attempt test discovery on 325 a different copy of the package then the import *could* happen from the 326 wrong place. If this happens test discovery will warn you and exit. 327 328 If you supply the start directory as a package name rather than a 329 path to a directory then discover assumes that whichever location it 330 imports from is the location you intended, so you will not get the 331 warning. 332 333Test modules and packages can customize test loading and discovery by through 334the `load_tests protocol`_. 335 336.. versionchanged:: 3.4 337 Test discovery supports :term:`namespace packages <namespace package>` 338 for the start directory. Note that you need to specify the top level 339 directory too (e.g. 340 ``python -m unittest discover -s root/namespace -t root``). 341 342.. versionchanged:: 3.11 343 Python 3.11 dropped the :term:`namespace packages <namespace package>` 344 support. It has been broken since Python 3.7. Start directory and 345 subdirectories containing tests must be regular package that have 346 ``__init__.py`` file. 347 348 Directories containing start directory still can be a namespace package. 349 In this case, you need to specify start directory as dotted package name, 350 and target directory explicitly. For example:: 351 352 # proj/ <-- current directory 353 # namespace/ 354 # mypkg/ 355 # __init__.py 356 # test_mypkg.py 357 358 python -m unittest discover -s namespace.mypkg -t . 359 360 361.. _organizing-tests: 362 363Organizing test code 364-------------------- 365 366The basic building blocks of unit testing are :dfn:`test cases` --- single 367scenarios that must be set up and checked for correctness. In :mod:`unittest`, 368test cases are represented by :class:`unittest.TestCase` instances. 369To make your own test cases you must write subclasses of 370:class:`TestCase` or use :class:`FunctionTestCase`. 371 372The testing code of a :class:`TestCase` instance should be entirely self 373contained, such that it can be run either in isolation or in arbitrary 374combination with any number of other test cases. 375 376The simplest :class:`TestCase` subclass will simply implement a test method 377(i.e. a method whose name starts with ``test``) in order to perform specific 378testing code:: 379 380 import unittest 381 382 class DefaultWidgetSizeTestCase(unittest.TestCase): 383 def test_default_widget_size(self): 384 widget = Widget('The widget') 385 self.assertEqual(widget.size(), (50, 50)) 386 387Note that in order to test something, we use one of the :meth:`assert\*` 388methods provided by the :class:`TestCase` base class. If the test fails, an 389exception will be raised with an explanatory message, and :mod:`unittest` 390will identify the test case as a :dfn:`failure`. Any other exceptions will be 391treated as :dfn:`errors`. 392 393Tests can be numerous, and their set-up can be repetitive. Luckily, we 394can factor out set-up code by implementing a method called 395:meth:`~TestCase.setUp`, which the testing framework will automatically 396call for every single test we run:: 397 398 import unittest 399 400 class WidgetTestCase(unittest.TestCase): 401 def setUp(self): 402 self.widget = Widget('The widget') 403 404 def test_default_widget_size(self): 405 self.assertEqual(self.widget.size(), (50,50), 406 'incorrect default size') 407 408 def test_widget_resize(self): 409 self.widget.resize(100,150) 410 self.assertEqual(self.widget.size(), (100,150), 411 'wrong size after resize') 412 413.. note:: 414 The order in which the various tests will be run is determined 415 by sorting the test method names with respect to the built-in 416 ordering for strings. 417 418If the :meth:`~TestCase.setUp` method raises an exception while the test is 419running, the framework will consider the test to have suffered an error, and 420the test method will not be executed. 421 422Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up 423after the test method has been run:: 424 425 import unittest 426 427 class WidgetTestCase(unittest.TestCase): 428 def setUp(self): 429 self.widget = Widget('The widget') 430 431 def tearDown(self): 432 self.widget.dispose() 433 434If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be 435run whether the test method succeeded or not. 436 437Such a working environment for the testing code is called a 438:dfn:`test fixture`. A new TestCase instance is created as a unique 439test fixture used to execute each individual test method. Thus 440:meth:`~TestCase.setUp`, :meth:`~TestCase.tearDown`, and :meth:`~TestCase.__init__` 441will be called once per test. 442 443It is recommended that you use TestCase implementations to group tests together 444according to the features they test. :mod:`unittest` provides a mechanism for 445this: the :dfn:`test suite`, represented by :mod:`unittest`'s 446:class:`TestSuite` class. In most cases, calling :func:`unittest.main` will do 447the right thing and collect all the module's test cases for you and execute 448them. 449 450However, should you want to customize the building of your test suite, 451you can do it yourself:: 452 453 def suite(): 454 suite = unittest.TestSuite() 455 suite.addTest(WidgetTestCase('test_default_widget_size')) 456 suite.addTest(WidgetTestCase('test_widget_resize')) 457 return suite 458 459 if __name__ == '__main__': 460 runner = unittest.TextTestRunner() 461 runner.run(suite()) 462 463You can place the definitions of test cases and test suites in the same modules 464as the code they are to test (such as :file:`widget.py`), but there are several 465advantages to placing the test code in a separate module, such as 466:file:`test_widget.py`: 467 468* The test module can be run standalone from the command line. 469 470* The test code can more easily be separated from shipped code. 471 472* There is less temptation to change test code to fit the code it tests without 473 a good reason. 474 475* Test code should be modified much less frequently than the code it tests. 476 477* Tested code can be refactored more easily. 478 479* Tests for modules written in C must be in separate modules anyway, so why not 480 be consistent? 481 482* If the testing strategy changes, there is no need to change the source code. 483 484 485.. _legacy-unit-tests: 486 487Re-using old test code 488---------------------- 489 490Some users will find that they have existing test code that they would like to 491run from :mod:`unittest`, without converting every old test function to a 492:class:`TestCase` subclass. 493 494For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class. 495This subclass of :class:`TestCase` can be used to wrap an existing test 496function. Set-up and tear-down functions can also be provided. 497 498Given the following test function:: 499 500 def testSomething(): 501 something = makeSomething() 502 assert something.name is not None 503 # ... 504 505one can create an equivalent test case instance as follows, with optional 506set-up and tear-down methods:: 507 508 testcase = unittest.FunctionTestCase(testSomething, 509 setUp=makeSomethingDB, 510 tearDown=deleteSomethingDB) 511 512.. note:: 513 514 Even though :class:`FunctionTestCase` can be used to quickly convert an 515 existing test base over to a :mod:`unittest`\ -based system, this approach is 516 not recommended. Taking the time to set up proper :class:`TestCase` 517 subclasses will make future test refactorings infinitely easier. 518 519In some cases, the existing tests may have been written using the :mod:`doctest` 520module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can 521automatically build :class:`unittest.TestSuite` instances from the existing 522:mod:`doctest`\ -based tests. 523 524 525.. _unittest-skipping: 526 527Skipping tests and expected failures 528------------------------------------ 529 530.. versionadded:: 3.1 531 532Unittest supports skipping individual test methods and even whole classes of 533tests. In addition, it supports marking a test as an "expected failure," a test 534that is broken and will fail, but shouldn't be counted as a failure on a 535:class:`TestResult`. 536 537Skipping a test is simply a matter of using the :func:`skip` :term:`decorator` 538or one of its conditional variants, calling :meth:`TestCase.skipTest` within a 539:meth:`~TestCase.setUp` or test method, or raising :exc:`SkipTest` directly. 540 541Basic skipping looks like this:: 542 543 class MyTestCase(unittest.TestCase): 544 545 @unittest.skip("demonstrating skipping") 546 def test_nothing(self): 547 self.fail("shouldn't happen") 548 549 @unittest.skipIf(mylib.__version__ < (1, 3), 550 "not supported in this library version") 551 def test_format(self): 552 # Tests that work for only a certain version of the library. 553 pass 554 555 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") 556 def test_windows_support(self): 557 # windows specific testing code 558 pass 559 560 def test_maybe_skipped(self): 561 if not external_resource_available(): 562 self.skipTest("external resource not available") 563 # test code that depends on the external resource 564 pass 565 566This is the output of running the example above in verbose mode:: 567 568 test_format (__main__.MyTestCase.test_format) ... skipped 'not supported in this library version' 569 test_nothing (__main__.MyTestCase.test_nothing) ... skipped 'demonstrating skipping' 570 test_maybe_skipped (__main__.MyTestCase.test_maybe_skipped) ... skipped 'external resource not available' 571 test_windows_support (__main__.MyTestCase.test_windows_support) ... skipped 'requires Windows' 572 573 ---------------------------------------------------------------------- 574 Ran 4 tests in 0.005s 575 576 OK (skipped=4) 577 578Classes can be skipped just like methods:: 579 580 @unittest.skip("showing class skipping") 581 class MySkippedTestCase(unittest.TestCase): 582 def test_not_run(self): 583 pass 584 585:meth:`TestCase.setUp` can also skip the test. This is useful when a resource 586that needs to be set up is not available. 587 588Expected failures use the :func:`expectedFailure` decorator. :: 589 590 class ExpectedFailureTestCase(unittest.TestCase): 591 @unittest.expectedFailure 592 def test_fail(self): 593 self.assertEqual(1, 0, "broken") 594 595It's easy to roll your own skipping decorators by making a decorator that calls 596:func:`skip` on the test when it wants it to be skipped. This decorator skips 597the test unless the passed object has a certain attribute:: 598 599 def skipUnlessHasattr(obj, attr): 600 if hasattr(obj, attr): 601 return lambda func: func 602 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr)) 603 604The following decorators and exception implement test skipping and expected failures: 605 606.. decorator:: skip(reason) 607 608 Unconditionally skip the decorated test. *reason* should describe why the 609 test is being skipped. 610 611.. decorator:: skipIf(condition, reason) 612 613 Skip the decorated test if *condition* is true. 614 615.. decorator:: skipUnless(condition, reason) 616 617 Skip the decorated test unless *condition* is true. 618 619.. decorator:: expectedFailure 620 621 Mark the test as an expected failure or error. If the test fails or errors 622 in the test function itself (rather than in one of the :dfn:`test fixture` 623 methods) then it will be considered a success. If the test passes, it will 624 be considered a failure. 625 626.. exception:: SkipTest(reason) 627 628 This exception is raised to skip a test. 629 630 Usually you can use :meth:`TestCase.skipTest` or one of the skipping 631 decorators instead of raising this directly. 632 633Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them. 634Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run. 635Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run. 636 637 638.. _subtests: 639 640Distinguishing test iterations using subtests 641--------------------------------------------- 642 643.. versionadded:: 3.4 644 645When there are very small differences among your tests, for 646instance some parameters, unittest allows you to distinguish them inside 647the body of a test method using the :meth:`~TestCase.subTest` context manager. 648 649For example, the following test:: 650 651 class NumbersTest(unittest.TestCase): 652 653 def test_even(self): 654 """ 655 Test that numbers between 0 and 5 are all even. 656 """ 657 for i in range(0, 6): 658 with self.subTest(i=i): 659 self.assertEqual(i % 2, 0) 660 661will produce the following output:: 662 663 ====================================================================== 664 FAIL: test_even (__main__.NumbersTest.test_even) (i=1) 665 Test that numbers between 0 and 5 are all even. 666 ---------------------------------------------------------------------- 667 Traceback (most recent call last): 668 File "subtests.py", line 11, in test_even 669 self.assertEqual(i % 2, 0) 670 ^^^^^^^^^^^^^^^^^^^^^^^^^^ 671 AssertionError: 1 != 0 672 673 ====================================================================== 674 FAIL: test_even (__main__.NumbersTest.test_even) (i=3) 675 Test that numbers between 0 and 5 are all even. 676 ---------------------------------------------------------------------- 677 Traceback (most recent call last): 678 File "subtests.py", line 11, in test_even 679 self.assertEqual(i % 2, 0) 680 ^^^^^^^^^^^^^^^^^^^^^^^^^^ 681 AssertionError: 1 != 0 682 683 ====================================================================== 684 FAIL: test_even (__main__.NumbersTest.test_even) (i=5) 685 Test that numbers between 0 and 5 are all even. 686 ---------------------------------------------------------------------- 687 Traceback (most recent call last): 688 File "subtests.py", line 11, in test_even 689 self.assertEqual(i % 2, 0) 690 ^^^^^^^^^^^^^^^^^^^^^^^^^^ 691 AssertionError: 1 != 0 692 693Without using a subtest, execution would stop after the first failure, 694and the error would be less easy to diagnose because the value of ``i`` 695wouldn't be displayed:: 696 697 ====================================================================== 698 FAIL: test_even (__main__.NumbersTest.test_even) 699 ---------------------------------------------------------------------- 700 Traceback (most recent call last): 701 File "subtests.py", line 32, in test_even 702 self.assertEqual(i % 2, 0) 703 AssertionError: 1 != 0 704 705 706.. _unittest-contents: 707 708Classes and functions 709--------------------- 710 711This section describes in depth the API of :mod:`unittest`. 712 713 714.. _testcase-objects: 715 716Test cases 717~~~~~~~~~~ 718 719.. class:: TestCase(methodName='runTest') 720 721 Instances of the :class:`TestCase` class represent the logical test units 722 in the :mod:`unittest` universe. This class is intended to be used as a base 723 class, with specific tests being implemented by concrete subclasses. This class 724 implements the interface needed by the test runner to allow it to drive the 725 tests, and methods that the test code can use to check for and report various 726 kinds of failure. 727 728 Each instance of :class:`TestCase` will run a single base method: the method 729 named *methodName*. 730 In most uses of :class:`TestCase`, you will neither change 731 the *methodName* nor reimplement the default ``runTest()`` method. 732 733 .. versionchanged:: 3.2 734 :class:`TestCase` can be instantiated successfully without providing a 735 *methodName*. This makes it easier to experiment with :class:`TestCase` 736 from the interactive interpreter. 737 738 :class:`TestCase` instances provide three groups of methods: one group used 739 to run the test, another used by the test implementation to check conditions 740 and report failures, and some inquiry methods allowing information about the 741 test itself to be gathered. 742 743 Methods in the first group (running the test) are: 744 745 .. method:: setUp() 746 747 Method called to prepare the test fixture. This is called immediately 748 before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`, 749 any exception raised by this method will be considered an error rather than 750 a test failure. The default implementation does nothing. 751 752 753 .. method:: tearDown() 754 755 Method called immediately after the test method has been called and the 756 result recorded. This is called even if the test method raised an 757 exception, so the implementation in subclasses may need to be particularly 758 careful about checking internal state. Any exception, other than 759 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be 760 considered an additional error rather than a test failure (thus increasing 761 the total number of reported errors). This method will only be called if 762 the :meth:`setUp` succeeds, regardless of the outcome of the test method. 763 The default implementation does nothing. 764 765 766 .. method:: setUpClass() 767 768 A class method called before tests in an individual class are run. 769 ``setUpClass`` is called with the class as the only argument 770 and must be decorated as a :func:`classmethod`:: 771 772 @classmethod 773 def setUpClass(cls): 774 ... 775 776 See `Class and Module Fixtures`_ for more details. 777 778 .. versionadded:: 3.2 779 780 781 .. method:: tearDownClass() 782 783 A class method called after tests in an individual class have run. 784 ``tearDownClass`` is called with the class as the only argument 785 and must be decorated as a :meth:`classmethod`:: 786 787 @classmethod 788 def tearDownClass(cls): 789 ... 790 791 See `Class and Module Fixtures`_ for more details. 792 793 .. versionadded:: 3.2 794 795 796 .. method:: run(result=None) 797 798 Run the test, collecting the result into the :class:`TestResult` object 799 passed as *result*. If *result* is omitted or ``None``, a temporary 800 result object is created (by calling the :meth:`defaultTestResult` 801 method) and used. The result object is returned to :meth:`run`'s 802 caller. 803 804 The same effect may be had by simply calling the :class:`TestCase` 805 instance. 806 807 .. versionchanged:: 3.3 808 Previous versions of ``run`` did not return the result. Neither did 809 calling an instance. 810 811 .. method:: skipTest(reason) 812 813 Calling this during a test method or :meth:`setUp` skips the current 814 test. See :ref:`unittest-skipping` for more information. 815 816 .. versionadded:: 3.1 817 818 819 .. method:: subTest(msg=None, **params) 820 821 Return a context manager which executes the enclosed code block as a 822 subtest. *msg* and *params* are optional, arbitrary values which are 823 displayed whenever a subtest fails, allowing you to identify them 824 clearly. 825 826 A test case can contain any number of subtest declarations, and 827 they can be arbitrarily nested. 828 829 See :ref:`subtests` for more information. 830 831 .. versionadded:: 3.4 832 833 834 .. method:: debug() 835 836 Run the test without collecting the result. This allows exceptions raised 837 by the test to be propagated to the caller, and can be used to support 838 running tests under a debugger. 839 840 .. _assert-methods: 841 842 The :class:`TestCase` class provides several assert methods to check for and 843 report failures. The following table lists the most commonly used methods 844 (see the tables below for more assert methods): 845 846 +-----------------------------------------+-----------------------------+---------------+ 847 | Method | Checks that | New in | 848 +=========================================+=============================+===============+ 849 | :meth:`assertEqual(a, b) | ``a == b`` | | 850 | <TestCase.assertEqual>` | | | 851 +-----------------------------------------+-----------------------------+---------------+ 852 | :meth:`assertNotEqual(a, b) | ``a != b`` | | 853 | <TestCase.assertNotEqual>` | | | 854 +-----------------------------------------+-----------------------------+---------------+ 855 | :meth:`assertTrue(x) | ``bool(x) is True`` | | 856 | <TestCase.assertTrue>` | | | 857 +-----------------------------------------+-----------------------------+---------------+ 858 | :meth:`assertFalse(x) | ``bool(x) is False`` | | 859 | <TestCase.assertFalse>` | | | 860 +-----------------------------------------+-----------------------------+---------------+ 861 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 | 862 | <TestCase.assertIs>` | | | 863 +-----------------------------------------+-----------------------------+---------------+ 864 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 | 865 | <TestCase.assertIsNot>` | | | 866 +-----------------------------------------+-----------------------------+---------------+ 867 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 | 868 | <TestCase.assertIsNone>` | | | 869 +-----------------------------------------+-----------------------------+---------------+ 870 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 | 871 | <TestCase.assertIsNotNone>` | | | 872 +-----------------------------------------+-----------------------------+---------------+ 873 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 | 874 | <TestCase.assertIn>` | | | 875 +-----------------------------------------+-----------------------------+---------------+ 876 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 | 877 | <TestCase.assertNotIn>` | | | 878 +-----------------------------------------+-----------------------------+---------------+ 879 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 | 880 | <TestCase.assertIsInstance>` | | | 881 +-----------------------------------------+-----------------------------+---------------+ 882 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 | 883 | <TestCase.assertNotIsInstance>` | | | 884 +-----------------------------------------+-----------------------------+---------------+ 885 886 All the assert methods accept a *msg* argument that, if specified, is used 887 as the error message on failure (see also :data:`longMessage`). 888 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`, 889 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex` 890 only when they are used as a context manager. 891 892 .. method:: assertEqual(first, second, msg=None) 893 894 Test that *first* and *second* are equal. If the values do not 895 compare equal, the test will fail. 896 897 In addition, if *first* and *second* are the exact same type and one of 898 list, tuple, dict, set, frozenset or str or any type that a subclass 899 registers with :meth:`addTypeEqualityFunc` the type-specific equality 900 function will be called in order to generate a more useful default 901 error message (see also the :ref:`list of type-specific methods 902 <type-specific-methods>`). 903 904 .. versionchanged:: 3.1 905 Added the automatic calling of type-specific equality function. 906 907 .. versionchanged:: 3.2 908 :meth:`assertMultiLineEqual` added as the default type equality 909 function for comparing strings. 910 911 912 .. method:: assertNotEqual(first, second, msg=None) 913 914 Test that *first* and *second* are not equal. If the values do 915 compare equal, the test will fail. 916 917 .. method:: assertTrue(expr, msg=None) 918 assertFalse(expr, msg=None) 919 920 Test that *expr* is true (or false). 921 922 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr 923 is True`` (use ``assertIs(expr, True)`` for the latter). This method 924 should also be avoided when more specific methods are available (e.g. 925 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they 926 provide a better error message in case of failure. 927 928 929 .. method:: assertIs(first, second, msg=None) 930 assertIsNot(first, second, msg=None) 931 932 Test that *first* and *second* are (or are not) the same object. 933 934 .. versionadded:: 3.1 935 936 937 .. method:: assertIsNone(expr, msg=None) 938 assertIsNotNone(expr, msg=None) 939 940 Test that *expr* is (or is not) ``None``. 941 942 .. versionadded:: 3.1 943 944 945 .. method:: assertIn(member, container, msg=None) 946 assertNotIn(member, container, msg=None) 947 948 Test that *member* is (or is not) in *container*. 949 950 .. versionadded:: 3.1 951 952 953 .. method:: assertIsInstance(obj, cls, msg=None) 954 assertNotIsInstance(obj, cls, msg=None) 955 956 Test that *obj* is (or is not) an instance of *cls* (which can be a 957 class or a tuple of classes, as supported by :func:`isinstance`). 958 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`. 959 960 .. versionadded:: 3.2 961 962 963 964 It is also possible to check the production of exceptions, warnings, and 965 log messages using the following methods: 966 967 +---------------------------------------------------------+--------------------------------------+------------+ 968 | Method | Checks that | New in | 969 +=========================================================+======================================+============+ 970 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | | 971 | <TestCase.assertRaises>` | | | 972 +---------------------------------------------------------+--------------------------------------+------------+ 973 | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 | 974 | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | | 975 +---------------------------------------------------------+--------------------------------------+------------+ 976 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 | 977 | <TestCase.assertWarns>` | | | 978 +---------------------------------------------------------+--------------------------------------+------------+ 979 | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 | 980 | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | | 981 +---------------------------------------------------------+--------------------------------------+------------+ 982 | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 | 983 | <TestCase.assertLogs>` | with minimum *level* | | 984 +---------------------------------------------------------+--------------------------------------+------------+ 985 | :meth:`assertNoLogs(logger, level) | The ``with`` block does not log on | 3.10 | 986 | <TestCase.assertNoLogs>` | *logger* with minimum *level* | | 987 +---------------------------------------------------------+--------------------------------------+------------+ 988 989 .. method:: assertRaises(exception, callable, *args, **kwds) 990 assertRaises(exception, *, msg=None) 991 992 Test that an exception is raised when *callable* is called with any 993 positional or keyword arguments that are also passed to 994 :meth:`assertRaises`. The test passes if *exception* is raised, is an 995 error if another exception is raised, or fails if no exception is raised. 996 To catch any of a group of exceptions, a tuple containing the exception 997 classes may be passed as *exception*. 998 999 If only the *exception* and possibly the *msg* arguments are given, 1000 return a context manager so that the code under test can be written 1001 inline rather than as a function:: 1002 1003 with self.assertRaises(SomeException): 1004 do_something() 1005 1006 When used as a context manager, :meth:`assertRaises` accepts the 1007 additional keyword argument *msg*. 1008 1009 The context manager will store the caught exception object in its 1010 :attr:`exception` attribute. This can be useful if the intention 1011 is to perform additional checks on the exception raised:: 1012 1013 with self.assertRaises(SomeException) as cm: 1014 do_something() 1015 1016 the_exception = cm.exception 1017 self.assertEqual(the_exception.error_code, 3) 1018 1019 .. versionchanged:: 3.1 1020 Added the ability to use :meth:`assertRaises` as a context manager. 1021 1022 .. versionchanged:: 3.2 1023 Added the :attr:`exception` attribute. 1024 1025 .. versionchanged:: 3.3 1026 Added the *msg* keyword argument when used as a context manager. 1027 1028 1029 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds) 1030 assertRaisesRegex(exception, regex, *, msg=None) 1031 1032 Like :meth:`assertRaises` but also tests that *regex* matches 1033 on the string representation of the raised exception. *regex* may be 1034 a regular expression object or a string containing a regular expression 1035 suitable for use by :func:`re.search`. Examples:: 1036 1037 self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$", 1038 int, 'XYZ') 1039 1040 or:: 1041 1042 with self.assertRaisesRegex(ValueError, 'literal'): 1043 int('XYZ') 1044 1045 .. versionadded:: 3.1 1046 Added under the name ``assertRaisesRegexp``. 1047 1048 .. versionchanged:: 3.2 1049 Renamed to :meth:`assertRaisesRegex`. 1050 1051 .. versionchanged:: 3.3 1052 Added the *msg* keyword argument when used as a context manager. 1053 1054 1055 .. method:: assertWarns(warning, callable, *args, **kwds) 1056 assertWarns(warning, *, msg=None) 1057 1058 Test that a warning is triggered when *callable* is called with any 1059 positional or keyword arguments that are also passed to 1060 :meth:`assertWarns`. The test passes if *warning* is triggered and 1061 fails if it isn't. Any exception is an error. 1062 To catch any of a group of warnings, a tuple containing the warning 1063 classes may be passed as *warnings*. 1064 1065 If only the *warning* and possibly the *msg* arguments are given, 1066 return a context manager so that the code under test can be written 1067 inline rather than as a function:: 1068 1069 with self.assertWarns(SomeWarning): 1070 do_something() 1071 1072 When used as a context manager, :meth:`assertWarns` accepts the 1073 additional keyword argument *msg*. 1074 1075 The context manager will store the caught warning object in its 1076 :attr:`warning` attribute, and the source line which triggered the 1077 warnings in the :attr:`filename` and :attr:`lineno` attributes. 1078 This can be useful if the intention is to perform additional checks 1079 on the warning caught:: 1080 1081 with self.assertWarns(SomeWarning) as cm: 1082 do_something() 1083 1084 self.assertIn('myfile.py', cm.filename) 1085 self.assertEqual(320, cm.lineno) 1086 1087 This method works regardless of the warning filters in place when it 1088 is called. 1089 1090 .. versionadded:: 3.2 1091 1092 .. versionchanged:: 3.3 1093 Added the *msg* keyword argument when used as a context manager. 1094 1095 1096 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds) 1097 assertWarnsRegex(warning, regex, *, msg=None) 1098 1099 Like :meth:`assertWarns` but also tests that *regex* matches on the 1100 message of the triggered warning. *regex* may be a regular expression 1101 object or a string containing a regular expression suitable for use 1102 by :func:`re.search`. Example:: 1103 1104 self.assertWarnsRegex(DeprecationWarning, 1105 r'legacy_function\(\) is deprecated', 1106 legacy_function, 'XYZ') 1107 1108 or:: 1109 1110 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'): 1111 frobnicate('/etc/passwd') 1112 1113 .. versionadded:: 3.2 1114 1115 .. versionchanged:: 3.3 1116 Added the *msg* keyword argument when used as a context manager. 1117 1118 .. method:: assertLogs(logger=None, level=None) 1119 1120 A context manager to test that at least one message is logged on 1121 the *logger* or one of its children, with at least the given 1122 *level*. 1123 1124 If given, *logger* should be a :class:`logging.Logger` object or a 1125 :class:`str` giving the name of a logger. The default is the root 1126 logger, which will catch all messages that were not blocked by a 1127 non-propagating descendent logger. 1128 1129 If given, *level* should be either a numeric logging level or 1130 its string equivalent (for example either ``"ERROR"`` or 1131 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`. 1132 1133 The test passes if at least one message emitted inside the ``with`` 1134 block matches the *logger* and *level* conditions, otherwise it fails. 1135 1136 The object returned by the context manager is a recording helper 1137 which keeps tracks of the matching log messages. It has two 1138 attributes: 1139 1140 .. attribute:: records 1141 1142 A list of :class:`logging.LogRecord` objects of the matching 1143 log messages. 1144 1145 .. attribute:: output 1146 1147 A list of :class:`str` objects with the formatted output of 1148 matching messages. 1149 1150 Example:: 1151 1152 with self.assertLogs('foo', level='INFO') as cm: 1153 logging.getLogger('foo').info('first message') 1154 logging.getLogger('foo.bar').error('second message') 1155 self.assertEqual(cm.output, ['INFO:foo:first message', 1156 'ERROR:foo.bar:second message']) 1157 1158 .. versionadded:: 3.4 1159 1160 .. method:: assertNoLogs(logger=None, level=None) 1161 1162 A context manager to test that no messages are logged on 1163 the *logger* or one of its children, with at least the given 1164 *level*. 1165 1166 If given, *logger* should be a :class:`logging.Logger` object or a 1167 :class:`str` giving the name of a logger. The default is the root 1168 logger, which will catch all messages. 1169 1170 If given, *level* should be either a numeric logging level or 1171 its string equivalent (for example either ``"ERROR"`` or 1172 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`. 1173 1174 Unlike :meth:`assertLogs`, nothing will be returned by the context 1175 manager. 1176 1177 .. versionadded:: 3.10 1178 1179 There are also other methods used to perform more specific checks, such as: 1180 1181 +---------------------------------------+--------------------------------+--------------+ 1182 | Method | Checks that | New in | 1183 +=======================================+================================+==============+ 1184 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | | 1185 | <TestCase.assertAlmostEqual>` | | | 1186 +---------------------------------------+--------------------------------+--------------+ 1187 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | | 1188 | <TestCase.assertNotAlmostEqual>` | | | 1189 +---------------------------------------+--------------------------------+--------------+ 1190 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 | 1191 | <TestCase.assertGreater>` | | | 1192 +---------------------------------------+--------------------------------+--------------+ 1193 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 | 1194 | <TestCase.assertGreaterEqual>` | | | 1195 +---------------------------------------+--------------------------------+--------------+ 1196 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 | 1197 | <TestCase.assertLess>` | | | 1198 +---------------------------------------+--------------------------------+--------------+ 1199 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 | 1200 | <TestCase.assertLessEqual>` | | | 1201 +---------------------------------------+--------------------------------+--------------+ 1202 | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 | 1203 | <TestCase.assertRegex>` | | | 1204 +---------------------------------------+--------------------------------+--------------+ 1205 | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 | 1206 | <TestCase.assertNotRegex>` | | | 1207 +---------------------------------------+--------------------------------+--------------+ 1208 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 | 1209 | <TestCase.assertCountEqual>` | elements in the same number, | | 1210 | | regardless of their order. | | 1211 +---------------------------------------+--------------------------------+--------------+ 1212 1213 1214 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None) 1215 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None) 1216 1217 Test that *first* and *second* are approximately (or not approximately) 1218 equal by computing the difference, rounding to the given number of 1219 decimal *places* (default 7), and comparing to zero. Note that these 1220 methods round the values to the given number of *decimal places* (i.e. 1221 like the :func:`round` function) and not *significant digits*. 1222 1223 If *delta* is supplied instead of *places* then the difference 1224 between *first* and *second* must be less or equal to (or greater than) *delta*. 1225 1226 Supplying both *delta* and *places* raises a :exc:`TypeError`. 1227 1228 .. versionchanged:: 3.2 1229 :meth:`assertAlmostEqual` automatically considers almost equal objects 1230 that compare equal. :meth:`assertNotAlmostEqual` automatically fails 1231 if the objects compare equal. Added the *delta* keyword argument. 1232 1233 1234 .. method:: assertGreater(first, second, msg=None) 1235 assertGreaterEqual(first, second, msg=None) 1236 assertLess(first, second, msg=None) 1237 assertLessEqual(first, second, msg=None) 1238 1239 Test that *first* is respectively >, >=, < or <= than *second* depending 1240 on the method name. If not, the test will fail:: 1241 1242 >>> self.assertGreaterEqual(3, 4) 1243 AssertionError: "3" unexpectedly not greater than or equal to "4" 1244 1245 .. versionadded:: 3.1 1246 1247 1248 .. method:: assertRegex(text, regex, msg=None) 1249 assertNotRegex(text, regex, msg=None) 1250 1251 Test that a *regex* search matches (or does not match) *text*. In case 1252 of failure, the error message will include the pattern and the *text* (or 1253 the pattern and the part of *text* that unexpectedly matched). *regex* 1254 may be a regular expression object or a string containing a regular 1255 expression suitable for use by :func:`re.search`. 1256 1257 .. versionadded:: 3.1 1258 Added under the name ``assertRegexpMatches``. 1259 .. versionchanged:: 3.2 1260 The method ``assertRegexpMatches()`` has been renamed to 1261 :meth:`.assertRegex`. 1262 .. versionadded:: 3.2 1263 :meth:`.assertNotRegex`. 1264 .. versionadded:: 3.5 1265 The name ``assertNotRegexpMatches`` is a deprecated alias 1266 for :meth:`.assertNotRegex`. 1267 1268 1269 .. method:: assertCountEqual(first, second, msg=None) 1270 1271 Test that sequence *first* contains the same elements as *second*, 1272 regardless of their order. When they don't, an error message listing the 1273 differences between the sequences will be generated. 1274 1275 Duplicate elements are *not* ignored when comparing *first* and 1276 *second*. It verifies whether each element has the same count in both 1277 sequences. Equivalent to: 1278 ``assertEqual(Counter(list(first)), Counter(list(second)))`` 1279 but works with sequences of unhashable objects as well. 1280 1281 .. versionadded:: 3.2 1282 1283 1284 .. _type-specific-methods: 1285 1286 The :meth:`assertEqual` method dispatches the equality check for objects of 1287 the same type to different type-specific methods. These methods are already 1288 implemented for most of the built-in types, but it's also possible to 1289 register new methods using :meth:`addTypeEqualityFunc`: 1290 1291 .. method:: addTypeEqualityFunc(typeobj, function) 1292 1293 Registers a type-specific method called by :meth:`assertEqual` to check 1294 if two objects of exactly the same *typeobj* (not subclasses) compare 1295 equal. *function* must take two positional arguments and a third msg=None 1296 keyword argument just as :meth:`assertEqual` does. It must raise 1297 :data:`self.failureException(msg) <failureException>` when inequality 1298 between the first two parameters is detected -- possibly providing useful 1299 information and explaining the inequalities in details in the error 1300 message. 1301 1302 .. versionadded:: 3.1 1303 1304 The list of type-specific methods automatically used by 1305 :meth:`~TestCase.assertEqual` are summarized in the following table. Note 1306 that it's usually not necessary to invoke these methods directly. 1307 1308 +-----------------------------------------+-----------------------------+--------------+ 1309 | Method | Used to compare | New in | 1310 +=========================================+=============================+==============+ 1311 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 | 1312 | <TestCase.assertMultiLineEqual>` | | | 1313 +-----------------------------------------+-----------------------------+--------------+ 1314 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 | 1315 | <TestCase.assertSequenceEqual>` | | | 1316 +-----------------------------------------+-----------------------------+--------------+ 1317 | :meth:`assertListEqual(a, b) | lists | 3.1 | 1318 | <TestCase.assertListEqual>` | | | 1319 +-----------------------------------------+-----------------------------+--------------+ 1320 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 | 1321 | <TestCase.assertTupleEqual>` | | | 1322 +-----------------------------------------+-----------------------------+--------------+ 1323 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 | 1324 | <TestCase.assertSetEqual>` | | | 1325 +-----------------------------------------+-----------------------------+--------------+ 1326 | :meth:`assertDictEqual(a, b) | dicts | 3.1 | 1327 | <TestCase.assertDictEqual>` | | | 1328 +-----------------------------------------+-----------------------------+--------------+ 1329 1330 1331 1332 .. method:: assertMultiLineEqual(first, second, msg=None) 1333 1334 Test that the multiline string *first* is equal to the string *second*. 1335 When not equal a diff of the two strings highlighting the differences 1336 will be included in the error message. This method is used by default 1337 when comparing strings with :meth:`assertEqual`. 1338 1339 .. versionadded:: 3.1 1340 1341 1342 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None) 1343 1344 Tests that two sequences are equal. If a *seq_type* is supplied, both 1345 *first* and *second* must be instances of *seq_type* or a failure will 1346 be raised. If the sequences are different an error message is 1347 constructed that shows the difference between the two. 1348 1349 This method is not called directly by :meth:`assertEqual`, but 1350 it's used to implement :meth:`assertListEqual` and 1351 :meth:`assertTupleEqual`. 1352 1353 .. versionadded:: 3.1 1354 1355 1356 .. method:: assertListEqual(first, second, msg=None) 1357 assertTupleEqual(first, second, msg=None) 1358 1359 Tests that two lists or tuples are equal. If not, an error message is 1360 constructed that shows only the differences between the two. An error 1361 is also raised if either of the parameters are of the wrong type. 1362 These methods are used by default when comparing lists or tuples with 1363 :meth:`assertEqual`. 1364 1365 .. versionadded:: 3.1 1366 1367 1368 .. method:: assertSetEqual(first, second, msg=None) 1369 1370 Tests that two sets are equal. If not, an error message is constructed 1371 that lists the differences between the sets. This method is used by 1372 default when comparing sets or frozensets with :meth:`assertEqual`. 1373 1374 Fails if either of *first* or *second* does not have a :meth:`set.difference` 1375 method. 1376 1377 .. versionadded:: 3.1 1378 1379 1380 .. method:: assertDictEqual(first, second, msg=None) 1381 1382 Test that two dictionaries are equal. If not, an error message is 1383 constructed that shows the differences in the dictionaries. This 1384 method will be used by default to compare dictionaries in 1385 calls to :meth:`assertEqual`. 1386 1387 .. versionadded:: 3.1 1388 1389 1390 1391 .. _other-methods-and-attrs: 1392 1393 Finally the :class:`TestCase` provides the following methods and attributes: 1394 1395 1396 .. method:: fail(msg=None) 1397 1398 Signals a test failure unconditionally, with *msg* or ``None`` for 1399 the error message. 1400 1401 1402 .. attribute:: failureException 1403 1404 This class attribute gives the exception raised by the test method. If a 1405 test framework needs to use a specialized exception, possibly to carry 1406 additional information, it must subclass this exception in order to "play 1407 fair" with the framework. The initial value of this attribute is 1408 :exc:`AssertionError`. 1409 1410 1411 .. attribute:: longMessage 1412 1413 This class attribute determines what happens when a custom failure message 1414 is passed as the msg argument to an assertXYY call that fails. 1415 ``True`` is the default value. In this case, the custom message is appended 1416 to the end of the standard failure message. 1417 When set to ``False``, the custom message replaces the standard message. 1418 1419 The class setting can be overridden in individual test methods by assigning 1420 an instance attribute, self.longMessage, to ``True`` or ``False`` before 1421 calling the assert methods. 1422 1423 The class setting gets reset before each test call. 1424 1425 .. versionadded:: 3.1 1426 1427 1428 .. attribute:: maxDiff 1429 1430 This attribute controls the maximum length of diffs output by assert 1431 methods that report diffs on failure. It defaults to 80*8 characters. 1432 Assert methods affected by this attribute are 1433 :meth:`assertSequenceEqual` (including all the sequence comparison 1434 methods that delegate to it), :meth:`assertDictEqual` and 1435 :meth:`assertMultiLineEqual`. 1436 1437 Setting ``maxDiff`` to ``None`` means that there is no maximum length of 1438 diffs. 1439 1440 .. versionadded:: 3.2 1441 1442 1443 Testing frameworks can use the following methods to collect information on 1444 the test: 1445 1446 1447 .. method:: countTestCases() 1448 1449 Return the number of tests represented by this test object. For 1450 :class:`TestCase` instances, this will always be ``1``. 1451 1452 1453 .. method:: defaultTestResult() 1454 1455 Return an instance of the test result class that should be used for this 1456 test case class (if no other result instance is provided to the 1457 :meth:`run` method). 1458 1459 For :class:`TestCase` instances, this will always be an instance of 1460 :class:`TestResult`; subclasses of :class:`TestCase` should override this 1461 as necessary. 1462 1463 1464 .. method:: id() 1465 1466 Return a string identifying the specific test case. This is usually the 1467 full name of the test method, including the module and class name. 1468 1469 1470 .. method:: shortDescription() 1471 1472 Returns a description of the test, or ``None`` if no description 1473 has been provided. The default implementation of this method 1474 returns the first line of the test method's docstring, if available, 1475 or ``None``. 1476 1477 .. versionchanged:: 3.1 1478 In 3.1 this was changed to add the test name to the short description 1479 even in the presence of a docstring. This caused compatibility issues 1480 with unittest extensions and adding the test name was moved to the 1481 :class:`TextTestResult` in Python 3.2. 1482 1483 1484 .. method:: addCleanup(function, /, *args, **kwargs) 1485 1486 Add a function to be called after :meth:`tearDown` to cleanup resources 1487 used during the test. Functions will be called in reverse order to the 1488 order they are added (:abbr:`LIFO (last-in, first-out)`). They 1489 are called with any arguments and keyword arguments passed into 1490 :meth:`addCleanup` when they are added. 1491 1492 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called, 1493 then any cleanup functions added will still be called. 1494 1495 .. versionadded:: 3.1 1496 1497 1498 .. method:: enterContext(cm) 1499 1500 Enter the supplied :term:`context manager`. If successful, also 1501 add its :meth:`~object.__exit__` method as a cleanup function by 1502 :meth:`addCleanup` and return the result of the 1503 :meth:`~object.__enter__` method. 1504 1505 .. versionadded:: 3.11 1506 1507 1508 .. method:: doCleanups() 1509 1510 This method is called unconditionally after :meth:`tearDown`, or 1511 after :meth:`setUp` if :meth:`setUp` raises an exception. 1512 1513 It is responsible for calling all the cleanup functions added by 1514 :meth:`addCleanup`. If you need cleanup functions to be called 1515 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups` 1516 yourself. 1517 1518 :meth:`doCleanups` pops methods off the stack of cleanup 1519 functions one at a time, so it can be called at any time. 1520 1521 .. versionadded:: 3.1 1522 1523 1524 .. classmethod:: addClassCleanup(function, /, *args, **kwargs) 1525 1526 Add a function to be called after :meth:`tearDownClass` to cleanup 1527 resources used during the test class. Functions will be called in reverse 1528 order to the order they are added (:abbr:`LIFO (last-in, first-out)`). 1529 They are called with any arguments and keyword arguments passed into 1530 :meth:`addClassCleanup` when they are added. 1531 1532 If :meth:`setUpClass` fails, meaning that :meth:`tearDownClass` is not 1533 called, then any cleanup functions added will still be called. 1534 1535 .. versionadded:: 3.8 1536 1537 1538 .. classmethod:: enterClassContext(cm) 1539 1540 Enter the supplied :term:`context manager`. If successful, also 1541 add its :meth:`~object.__exit__` method as a cleanup function by 1542 :meth:`addClassCleanup` and return the result of the 1543 :meth:`~object.__enter__` method. 1544 1545 .. versionadded:: 3.11 1546 1547 1548 .. classmethod:: doClassCleanups() 1549 1550 This method is called unconditionally after :meth:`tearDownClass`, or 1551 after :meth:`setUpClass` if :meth:`setUpClass` raises an exception. 1552 1553 It is responsible for calling all the cleanup functions added by 1554 :meth:`addClassCleanup`. If you need cleanup functions to be called 1555 *prior* to :meth:`tearDownClass` then you can call 1556 :meth:`doClassCleanups` yourself. 1557 1558 :meth:`doClassCleanups` pops methods off the stack of cleanup 1559 functions one at a time, so it can be called at any time. 1560 1561 .. versionadded:: 3.8 1562 1563 1564.. class:: IsolatedAsyncioTestCase(methodName='runTest') 1565 1566 This class provides an API similar to :class:`TestCase` and also accepts 1567 coroutines as test functions. 1568 1569 .. versionadded:: 3.8 1570 1571 .. coroutinemethod:: asyncSetUp() 1572 1573 Method called to prepare the test fixture. This is called after :meth:`setUp`. 1574 This is called immediately before calling the test method; other than 1575 :exc:`AssertionError` or :exc:`SkipTest`, any exception raised by this method 1576 will be considered an error rather than a test failure. The default implementation 1577 does nothing. 1578 1579 .. coroutinemethod:: asyncTearDown() 1580 1581 Method called immediately after the test method has been called and the 1582 result recorded. This is called before :meth:`tearDown`. This is called even if 1583 the test method raised an exception, so the implementation in subclasses may need 1584 to be particularly careful about checking internal state. Any exception, other than 1585 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be 1586 considered an additional error rather than a test failure (thus increasing 1587 the total number of reported errors). This method will only be called if 1588 the :meth:`asyncSetUp` succeeds, regardless of the outcome of the test method. 1589 The default implementation does nothing. 1590 1591 .. method:: addAsyncCleanup(function, /, *args, **kwargs) 1592 1593 This method accepts a coroutine that can be used as a cleanup function. 1594 1595 .. coroutinemethod:: enterAsyncContext(cm) 1596 1597 Enter the supplied :term:`asynchronous context manager`. If successful, 1598 also add its :meth:`~object.__aexit__` method as a cleanup function by 1599 :meth:`addAsyncCleanup` and return the result of the 1600 :meth:`~object.__aenter__` method. 1601 1602 .. versionadded:: 3.11 1603 1604 1605 .. method:: run(result=None) 1606 1607 Sets up a new event loop to run the test, collecting the result into 1608 the :class:`TestResult` object passed as *result*. If *result* is 1609 omitted or ``None``, a temporary result object is created (by calling 1610 the :meth:`defaultTestResult` method) and used. The result object is 1611 returned to :meth:`run`'s caller. At the end of the test all the tasks 1612 in the event loop are cancelled. 1613 1614 1615 An example illustrating the order:: 1616 1617 from unittest import IsolatedAsyncioTestCase 1618 1619 events = [] 1620 1621 1622 class Test(IsolatedAsyncioTestCase): 1623 1624 1625 def setUp(self): 1626 events.append("setUp") 1627 1628 async def asyncSetUp(self): 1629 self._async_connection = await AsyncConnection() 1630 events.append("asyncSetUp") 1631 1632 async def test_response(self): 1633 events.append("test_response") 1634 response = await self._async_connection.get("https://example.com") 1635 self.assertEqual(response.status_code, 200) 1636 self.addAsyncCleanup(self.on_cleanup) 1637 1638 def tearDown(self): 1639 events.append("tearDown") 1640 1641 async def asyncTearDown(self): 1642 await self._async_connection.close() 1643 events.append("asyncTearDown") 1644 1645 async def on_cleanup(self): 1646 events.append("cleanup") 1647 1648 if __name__ == "__main__": 1649 unittest.main() 1650 1651 After running the test, ``events`` would contain ``["setUp", "asyncSetUp", "test_response", "asyncTearDown", "tearDown", "cleanup"]``. 1652 1653 1654.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None) 1655 1656 This class implements the portion of the :class:`TestCase` interface which 1657 allows the test runner to drive the test, but does not provide the methods 1658 which test code can use to check and report errors. This is used to create 1659 test cases using legacy test code, allowing it to be integrated into a 1660 :mod:`unittest`-based test framework. 1661 1662 1663.. _deprecated-aliases: 1664 1665Deprecated aliases 1666################## 1667 1668For historical reasons, some of the :class:`TestCase` methods had one or more 1669aliases that are now deprecated. The following table lists the correct names 1670along with their deprecated aliases: 1671 1672 ============================== ====================== ======================= 1673 Method Name Deprecated alias Deprecated alias 1674 ============================== ====================== ======================= 1675 :meth:`.assertEqual` failUnlessEqual assertEquals 1676 :meth:`.assertNotEqual` failIfEqual assertNotEquals 1677 :meth:`.assertTrue` failUnless assert\_ 1678 :meth:`.assertFalse` failIf 1679 :meth:`.assertRaises` failUnlessRaises 1680 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals 1681 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals 1682 :meth:`.assertRegex` assertRegexpMatches 1683 :meth:`.assertNotRegex` assertNotRegexpMatches 1684 :meth:`.assertRaisesRegex` assertRaisesRegexp 1685 ============================== ====================== ======================= 1686 1687 .. deprecated:: 3.1 1688 The fail* aliases listed in the second column have been deprecated. 1689 .. deprecated:: 3.2 1690 The assert* aliases listed in the third column have been deprecated. 1691 .. deprecated:: 3.2 1692 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to 1693 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`. 1694 .. deprecated:: 3.5 1695 The ``assertNotRegexpMatches`` name is deprecated in favor of :meth:`.assertNotRegex`. 1696 1697.. _testsuite-objects: 1698 1699Grouping tests 1700~~~~~~~~~~~~~~ 1701 1702.. class:: TestSuite(tests=()) 1703 1704 This class represents an aggregation of individual test cases and test suites. 1705 The class presents the interface needed by the test runner to allow it to be run 1706 as any other test case. Running a :class:`TestSuite` instance is the same as 1707 iterating over the suite, running each test individually. 1708 1709 If *tests* is given, it must be an iterable of individual test cases or other 1710 test suites that will be used to build the suite initially. Additional methods 1711 are provided to add test cases and suites to the collection later on. 1712 1713 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except 1714 they do not actually implement a test. Instead, they are used to aggregate 1715 tests into groups of tests that should be run together. Some additional 1716 methods are available to add tests to :class:`TestSuite` instances: 1717 1718 1719 .. method:: TestSuite.addTest(test) 1720 1721 Add a :class:`TestCase` or :class:`TestSuite` to the suite. 1722 1723 1724 .. method:: TestSuite.addTests(tests) 1725 1726 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite` 1727 instances to this test suite. 1728 1729 This is equivalent to iterating over *tests*, calling :meth:`addTest` for 1730 each element. 1731 1732 :class:`TestSuite` shares the following methods with :class:`TestCase`: 1733 1734 1735 .. method:: run(result) 1736 1737 Run the tests associated with this suite, collecting the result into the 1738 test result object passed as *result*. Note that unlike 1739 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to 1740 be passed in. 1741 1742 1743 .. method:: debug() 1744 1745 Run the tests associated with this suite without collecting the 1746 result. This allows exceptions raised by the test to be propagated to the 1747 caller and can be used to support running tests under a debugger. 1748 1749 1750 .. method:: countTestCases() 1751 1752 Return the number of tests represented by this test object, including all 1753 individual tests and sub-suites. 1754 1755 1756 .. method:: __iter__() 1757 1758 Tests grouped by a :class:`TestSuite` are always accessed by iteration. 1759 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note 1760 that this method may be called several times on a single suite (for 1761 example when counting tests or comparing for equality) so the tests 1762 returned by repeated iterations before :meth:`TestSuite.run` must be the 1763 same for each call iteration. After :meth:`TestSuite.run`, callers should 1764 not rely on the tests returned by this method unless the caller uses a 1765 subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve 1766 test references. 1767 1768 .. versionchanged:: 3.2 1769 In earlier versions the :class:`TestSuite` accessed tests directly rather 1770 than through iteration, so overriding :meth:`__iter__` wasn't sufficient 1771 for providing tests. 1772 1773 .. versionchanged:: 3.4 1774 In earlier versions the :class:`TestSuite` held references to each 1775 :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore 1776 that behavior by overriding :meth:`TestSuite._removeTestAtIndex`. 1777 1778 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method 1779 is invoked by a :class:`TestRunner` rather than by the end-user test harness. 1780 1781 1782Loading and running tests 1783~~~~~~~~~~~~~~~~~~~~~~~~~ 1784 1785.. class:: TestLoader() 1786 1787 The :class:`TestLoader` class is used to create test suites from classes and 1788 modules. Normally, there is no need to create an instance of this class; the 1789 :mod:`unittest` module provides an instance that can be shared as 1790 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however, 1791 allows customization of some configurable properties. 1792 1793 :class:`TestLoader` objects have the following attributes: 1794 1795 1796 .. attribute:: errors 1797 1798 A list of the non-fatal errors encountered while loading tests. Not reset 1799 by the loader at any point. Fatal errors are signalled by the relevant 1800 method raising an exception to the caller. Non-fatal errors are also 1801 indicated by a synthetic test that will raise the original error when 1802 run. 1803 1804 .. versionadded:: 3.5 1805 1806 1807 :class:`TestLoader` objects have the following methods: 1808 1809 1810 .. method:: loadTestsFromTestCase(testCaseClass) 1811 1812 Return a suite of all test cases contained in the :class:`TestCase`\ -derived 1813 :class:`testCaseClass`. 1814 1815 A test case instance is created for each method named by 1816 :meth:`getTestCaseNames`. By default these are the method names 1817 beginning with ``test``. If :meth:`getTestCaseNames` returns no 1818 methods, but the :meth:`runTest` method is implemented, a single test 1819 case is created for that method instead. 1820 1821 1822 .. method:: loadTestsFromModule(module, pattern=None) 1823 1824 Return a suite of all test cases contained in the given module. This 1825 method searches *module* for classes derived from :class:`TestCase` and 1826 creates an instance of the class for each test method defined for the 1827 class. 1828 1829 .. note:: 1830 1831 While using a hierarchy of :class:`TestCase`\ -derived classes can be 1832 convenient in sharing fixtures and helper functions, defining test 1833 methods on base classes that are not intended to be instantiated 1834 directly does not play well with this method. Doing so, however, can 1835 be useful when the fixtures are different and defined in subclasses. 1836 1837 If a module provides a ``load_tests`` function it will be called to 1838 load the tests. This allows modules to customize test loading. 1839 This is the `load_tests protocol`_. The *pattern* argument is passed as 1840 the third argument to ``load_tests``. 1841 1842 .. versionchanged:: 3.2 1843 Support for ``load_tests`` added. 1844 1845 .. versionchanged:: 3.5 1846 The undocumented and unofficial *use_load_tests* default argument is 1847 deprecated and ignored, although it is still accepted for backward 1848 compatibility. The method also now accepts a keyword-only argument 1849 *pattern* which is passed to ``load_tests`` as the third argument. 1850 1851 1852 .. method:: loadTestsFromName(name, module=None) 1853 1854 Return a suite of all test cases given a string specifier. 1855 1856 The specifier *name* is a "dotted name" that may resolve either to a 1857 module, a test case class, a test method within a test case class, a 1858 :class:`TestSuite` instance, or a callable object which returns a 1859 :class:`TestCase` or :class:`TestSuite` instance. These checks are 1860 applied in the order listed here; that is, a method on a possible test 1861 case class will be picked up as "a test method within a test case class", 1862 rather than "a callable object". 1863 1864 For example, if you have a module :mod:`SampleTests` containing a 1865 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test 1866 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the 1867 specifier ``'SampleTests.SampleTestCase'`` would cause this method to 1868 return a suite which will run all three test methods. Using the specifier 1869 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test 1870 suite which will run only the :meth:`test_two` test method. The specifier 1871 can refer to modules and packages which have not been imported; they will 1872 be imported as a side-effect. 1873 1874 The method optionally resolves *name* relative to the given *module*. 1875 1876 .. versionchanged:: 3.5 1877 If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing 1878 *name* then a synthetic test that raises that error when run will be 1879 returned. These errors are included in the errors accumulated by 1880 self.errors. 1881 1882 1883 .. method:: loadTestsFromNames(names, module=None) 1884 1885 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather 1886 than a single name. The return value is a test suite which supports all 1887 the tests defined for each name. 1888 1889 1890 .. method:: getTestCaseNames(testCaseClass) 1891 1892 Return a sorted sequence of method names found within *testCaseClass*; 1893 this should be a subclass of :class:`TestCase`. 1894 1895 1896 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None) 1897 1898 Find all the test modules by recursing into subdirectories from the 1899 specified start directory, and return a TestSuite object containing them. 1900 Only test files that match *pattern* will be loaded. (Using shell style 1901 pattern matching.) Only module names that are importable (i.e. are valid 1902 Python identifiers) will be loaded. 1903 1904 All test modules must be importable from the top level of the project. If 1905 the start directory is not the top level directory then the top level 1906 directory must be specified separately. 1907 1908 If importing a module fails, for example due to a syntax error, then 1909 this will be recorded as a single error and discovery will continue. If 1910 the import failure is due to :exc:`SkipTest` being raised, it will be 1911 recorded as a skip instead of an error. 1912 1913 If a package (a directory containing a file named :file:`__init__.py`) is 1914 found, the package will be checked for a ``load_tests`` function. If this 1915 exists then it will be called 1916 ``package.load_tests(loader, tests, pattern)``. Test discovery takes care 1917 to ensure that a package is only checked for tests once during an 1918 invocation, even if the load_tests function itself calls 1919 ``loader.discover``. 1920 1921 If ``load_tests`` exists then discovery does *not* recurse into the 1922 package, ``load_tests`` is responsible for loading all tests in the 1923 package. 1924 1925 The pattern is deliberately not stored as a loader attribute so that 1926 packages can continue discovery themselves. *top_level_dir* is stored so 1927 ``load_tests`` does not need to pass this argument in to 1928 ``loader.discover()``. 1929 1930 *start_dir* can be a dotted module name as well as a directory. 1931 1932 .. versionadded:: 3.2 1933 1934 .. versionchanged:: 3.4 1935 Modules that raise :exc:`SkipTest` on import are recorded as skips, 1936 not errors. 1937 1938 .. versionchanged:: 3.4 1939 *start_dir* can be a :term:`namespace packages <namespace package>`. 1940 1941 .. versionchanged:: 3.4 1942 Paths are sorted before being imported so that execution order is the 1943 same even if the underlying file system's ordering is not dependent 1944 on file name. 1945 1946 .. versionchanged:: 3.5 1947 Found packages are now checked for ``load_tests`` regardless of 1948 whether their path matches *pattern*, because it is impossible for 1949 a package name to match the default pattern. 1950 1951 .. versionchanged:: 3.11 1952 *start_dir* can not be a :term:`namespace packages <namespace package>`. 1953 It has been broken since Python 3.7 and Python 3.11 officially remove it. 1954 1955 1956 The following attributes of a :class:`TestLoader` can be configured either by 1957 subclassing or assignment on an instance: 1958 1959 1960 .. attribute:: testMethodPrefix 1961 1962 String giving the prefix of method names which will be interpreted as test 1963 methods. The default value is ``'test'``. 1964 1965 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` 1966 methods. 1967 1968 1969 .. attribute:: sortTestMethodsUsing 1970 1971 Function to be used to compare method names when sorting them in 1972 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. 1973 1974 1975 .. attribute:: suiteClass 1976 1977 Callable object that constructs a test suite from a list of tests. No 1978 methods on the resulting object are needed. The default value is the 1979 :class:`TestSuite` class. 1980 1981 This affects all the :meth:`loadTestsFrom\*` methods. 1982 1983 .. attribute:: testNamePatterns 1984 1985 List of Unix shell-style wildcard test name patterns that test methods 1986 have to match to be included in test suites (see ``-k`` option). 1987 1988 If this attribute is not ``None`` (the default), all test methods to be 1989 included in test suites must match one of the patterns in this list. 1990 Note that matches are always performed using :meth:`fnmatch.fnmatchcase`, 1991 so unlike patterns passed to the ``-k`` option, simple substring patterns 1992 will have to be converted using ``*`` wildcards. 1993 1994 This affects all the :meth:`loadTestsFrom\*` methods. 1995 1996 .. versionadded:: 3.7 1997 1998 1999.. class:: TestResult 2000 2001 This class is used to compile information about which tests have succeeded 2002 and which have failed. 2003 2004 A :class:`TestResult` object stores the results of a set of tests. The 2005 :class:`TestCase` and :class:`TestSuite` classes ensure that results are 2006 properly recorded; test authors do not need to worry about recording the 2007 outcome of tests. 2008 2009 Testing frameworks built on top of :mod:`unittest` may want access to the 2010 :class:`TestResult` object generated by running a set of tests for reporting 2011 purposes; a :class:`TestResult` instance is returned by the 2012 :meth:`TestRunner.run` method for this purpose. 2013 2014 :class:`TestResult` instances have the following attributes that will be of 2015 interest when inspecting the results of running a set of tests: 2016 2017 2018 .. attribute:: errors 2019 2020 A list containing 2-tuples of :class:`TestCase` instances and strings 2021 holding formatted tracebacks. Each tuple represents a test which raised an 2022 unexpected exception. 2023 2024 .. attribute:: failures 2025 2026 A list containing 2-tuples of :class:`TestCase` instances and strings 2027 holding formatted tracebacks. Each tuple represents a test where a failure 2028 was explicitly signalled using the :meth:`TestCase.assert\*` methods. 2029 2030 .. attribute:: skipped 2031 2032 A list containing 2-tuples of :class:`TestCase` instances and strings 2033 holding the reason for skipping the test. 2034 2035 .. versionadded:: 3.1 2036 2037 .. attribute:: expectedFailures 2038 2039 A list containing 2-tuples of :class:`TestCase` instances and strings 2040 holding formatted tracebacks. Each tuple represents an expected failure 2041 or error of the test case. 2042 2043 .. attribute:: unexpectedSuccesses 2044 2045 A list containing :class:`TestCase` instances that were marked as expected 2046 failures, but succeeded. 2047 2048 .. attribute:: shouldStop 2049 2050 Set to ``True`` when the execution of tests should stop by :meth:`stop`. 2051 2052 .. attribute:: testsRun 2053 2054 The total number of tests run so far. 2055 2056 .. attribute:: buffer 2057 2058 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between 2059 :meth:`startTest` and :meth:`stopTest` being called. Collected output will 2060 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test 2061 fails or errors. Any output is also attached to the failure / error message. 2062 2063 .. versionadded:: 3.2 2064 2065 .. attribute:: failfast 2066 2067 If set to true :meth:`stop` will be called on the first failure or error, 2068 halting the test run. 2069 2070 .. versionadded:: 3.2 2071 2072 .. attribute:: tb_locals 2073 2074 If set to true then local variables will be shown in tracebacks. 2075 2076 .. versionadded:: 3.5 2077 2078 .. method:: wasSuccessful() 2079 2080 Return ``True`` if all tests run so far have passed, otherwise returns 2081 ``False``. 2082 2083 .. versionchanged:: 3.4 2084 Returns ``False`` if there were any :attr:`unexpectedSuccesses` 2085 from tests marked with the :func:`expectedFailure` decorator. 2086 2087 .. method:: stop() 2088 2089 This method can be called to signal that the set of tests being run should 2090 be aborted by setting the :attr:`shouldStop` attribute to ``True``. 2091 :class:`TestRunner` objects should respect this flag and return without 2092 running any additional tests. 2093 2094 For example, this feature is used by the :class:`TextTestRunner` class to 2095 stop the test framework when the user signals an interrupt from the 2096 keyboard. Interactive tools which provide :class:`TestRunner` 2097 implementations can use this in a similar manner. 2098 2099 The following methods of the :class:`TestResult` class are used to maintain 2100 the internal data structures, and may be extended in subclasses to support 2101 additional reporting requirements. This is particularly useful in building 2102 tools which support interactive reporting while tests are being run. 2103 2104 2105 .. method:: startTest(test) 2106 2107 Called when the test case *test* is about to be run. 2108 2109 .. method:: stopTest(test) 2110 2111 Called after the test case *test* has been executed, regardless of the 2112 outcome. 2113 2114 .. method:: startTestRun() 2115 2116 Called once before any tests are executed. 2117 2118 .. versionadded:: 3.1 2119 2120 2121 .. method:: stopTestRun() 2122 2123 Called once after all tests are executed. 2124 2125 .. versionadded:: 3.1 2126 2127 2128 .. method:: addError(test, err) 2129 2130 Called when the test case *test* raises an unexpected exception. *err* is a 2131 tuple of the form returned by :func:`sys.exc_info`: ``(type, value, 2132 traceback)``. 2133 2134 The default implementation appends a tuple ``(test, formatted_err)`` to 2135 the instance's :attr:`errors` attribute, where *formatted_err* is a 2136 formatted traceback derived from *err*. 2137 2138 2139 .. method:: addFailure(test, err) 2140 2141 Called when the test case *test* signals a failure. *err* is a tuple of 2142 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``. 2143 2144 The default implementation appends a tuple ``(test, formatted_err)`` to 2145 the instance's :attr:`failures` attribute, where *formatted_err* is a 2146 formatted traceback derived from *err*. 2147 2148 2149 .. method:: addSuccess(test) 2150 2151 Called when the test case *test* succeeds. 2152 2153 The default implementation does nothing. 2154 2155 2156 .. method:: addSkip(test, reason) 2157 2158 Called when the test case *test* is skipped. *reason* is the reason the 2159 test gave for skipping. 2160 2161 The default implementation appends a tuple ``(test, reason)`` to the 2162 instance's :attr:`skipped` attribute. 2163 2164 2165 .. method:: addExpectedFailure(test, err) 2166 2167 Called when the test case *test* fails or errors, but was marked with 2168 the :func:`expectedFailure` decorator. 2169 2170 The default implementation appends a tuple ``(test, formatted_err)`` to 2171 the instance's :attr:`expectedFailures` attribute, where *formatted_err* 2172 is a formatted traceback derived from *err*. 2173 2174 2175 .. method:: addUnexpectedSuccess(test) 2176 2177 Called when the test case *test* was marked with the 2178 :func:`expectedFailure` decorator, but succeeded. 2179 2180 The default implementation appends the test to the instance's 2181 :attr:`unexpectedSuccesses` attribute. 2182 2183 2184 .. method:: addSubTest(test, subtest, outcome) 2185 2186 Called when a subtest finishes. *test* is the test case 2187 corresponding to the test method. *subtest* is a custom 2188 :class:`TestCase` instance describing the subtest. 2189 2190 If *outcome* is :const:`None`, the subtest succeeded. Otherwise, 2191 it failed with an exception where *outcome* is a tuple of the form 2192 returned by :func:`sys.exc_info`: ``(type, value, traceback)``. 2193 2194 The default implementation does nothing when the outcome is a 2195 success, and records subtest failures as normal failures. 2196 2197 .. versionadded:: 3.4 2198 2199 2200.. class:: TextTestResult(stream, descriptions, verbosity) 2201 2202 A concrete implementation of :class:`TestResult` used by the 2203 :class:`TextTestRunner`. 2204 2205 .. versionadded:: 3.2 2206 This class was previously named ``_TextTestResult``. The old name still 2207 exists as an alias but is deprecated. 2208 2209 2210.. data:: defaultTestLoader 2211 2212 Instance of the :class:`TestLoader` class intended to be shared. If no 2213 customization of the :class:`TestLoader` is needed, this instance can be used 2214 instead of repeatedly creating new instances. 2215 2216 2217.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \ 2218 buffer=False, resultclass=None, warnings=None, *, tb_locals=False) 2219 2220 A basic test runner implementation that outputs results to a stream. If *stream* 2221 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class 2222 has a few configurable parameters, but is essentially very simple. Graphical 2223 applications which run test suites should provide alternate implementations. Such 2224 implementations should accept ``**kwargs`` as the interface to construct runners 2225 changes when features are added to unittest. 2226 2227 By default this runner shows :exc:`DeprecationWarning`, 2228 :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and 2229 :exc:`ImportWarning` even if they are :ref:`ignored by default 2230 <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest 2231 methods <deprecated-aliases>` are also special-cased and, when the warning 2232 filters are ``'default'`` or ``'always'``, they will appear only once 2233 per-module, in order to avoid too many warning messages. This behavior can 2234 be overridden using Python's :option:`!-Wd` or :option:`!-Wa` options 2235 (see :ref:`Warning control <using-on-warnings>`) and leaving 2236 *warnings* to ``None``. 2237 2238 .. versionchanged:: 3.2 2239 Added the ``warnings`` argument. 2240 2241 .. versionchanged:: 3.2 2242 The default stream is set to :data:`sys.stderr` at instantiation time rather 2243 than import time. 2244 2245 .. versionchanged:: 3.5 2246 Added the tb_locals parameter. 2247 2248 .. method:: _makeResult() 2249 2250 This method returns the instance of ``TestResult`` used by :meth:`run`. 2251 It is not intended to be called directly, but can be overridden in 2252 subclasses to provide a custom ``TestResult``. 2253 2254 ``_makeResult()`` instantiates the class or callable passed in the 2255 ``TextTestRunner`` constructor as the ``resultclass`` argument. It 2256 defaults to :class:`TextTestResult` if no ``resultclass`` is provided. 2257 The result class is instantiated with the following arguments:: 2258 2259 stream, descriptions, verbosity 2260 2261 .. method:: run(test) 2262 2263 This method is the main public interface to the ``TextTestRunner``. This 2264 method takes a :class:`TestSuite` or :class:`TestCase` instance. A 2265 :class:`TestResult` is created by calling 2266 :func:`_makeResult` and the test(s) are run and the 2267 results printed to stdout. 2268 2269 2270.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \ 2271 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \ 2272 failfast=None, catchbreak=None, buffer=None, warnings=None) 2273 2274 A command-line program that loads a set of tests from *module* and runs them; 2275 this is primarily for making test modules conveniently executable. 2276 The simplest use for this function is to include the following line at the 2277 end of a test script:: 2278 2279 if __name__ == '__main__': 2280 unittest.main() 2281 2282 You can run tests with more detailed information by passing in the verbosity 2283 argument:: 2284 2285 if __name__ == '__main__': 2286 unittest.main(verbosity=2) 2287 2288 The *defaultTest* argument is either the name of a single test or an 2289 iterable of test names to run if no test names are specified via *argv*. If 2290 not specified or ``None`` and no test names are provided via *argv*, all 2291 tests found in *module* are run. 2292 2293 The *argv* argument can be a list of options passed to the program, with the 2294 first element being the program name. If not specified or ``None``, 2295 the values of :data:`sys.argv` are used. 2296 2297 The *testRunner* argument can either be a test runner class or an already 2298 created instance of it. By default ``main`` calls :func:`sys.exit` with 2299 an exit code indicating success or failure of the tests run. 2300 2301 The *testLoader* argument has to be a :class:`TestLoader` instance, 2302 and defaults to :data:`defaultTestLoader`. 2303 2304 ``main`` supports being used from the interactive interpreter by passing in the 2305 argument ``exit=False``. This displays the result on standard output without 2306 calling :func:`sys.exit`:: 2307 2308 >>> from unittest import main 2309 >>> main(module='test_module', exit=False) 2310 2311 The *failfast*, *catchbreak* and *buffer* parameters have the same 2312 effect as the same-name `command-line options`_. 2313 2314 The *warnings* argument specifies the :ref:`warning filter <warning-filter>` 2315 that should be used while running the tests. If it's not specified, it will 2316 remain ``None`` if a :option:`!-W` option is passed to :program:`python` 2317 (see :ref:`Warning control <using-on-warnings>`), 2318 otherwise it will be set to ``'default'``. 2319 2320 Calling ``main`` actually returns an instance of the ``TestProgram`` class. 2321 This stores the result of the tests run as the ``result`` attribute. 2322 2323 .. versionchanged:: 3.1 2324 The *exit* parameter was added. 2325 2326 .. versionchanged:: 3.2 2327 The *verbosity*, *failfast*, *catchbreak*, *buffer* 2328 and *warnings* parameters were added. 2329 2330 .. versionchanged:: 3.4 2331 The *defaultTest* parameter was changed to also accept an iterable of 2332 test names. 2333 2334 2335load_tests Protocol 2336################### 2337 2338.. versionadded:: 3.2 2339 2340Modules or packages can customize how tests are loaded from them during normal 2341test runs or test discovery by implementing a function called ``load_tests``. 2342 2343If a test module defines ``load_tests`` it will be called by 2344:meth:`TestLoader.loadTestsFromModule` with the following arguments:: 2345 2346 load_tests(loader, standard_tests, pattern) 2347 2348where *pattern* is passed straight through from ``loadTestsFromModule``. It 2349defaults to ``None``. 2350 2351It should return a :class:`TestSuite`. 2352 2353*loader* is the instance of :class:`TestLoader` doing the loading. 2354*standard_tests* are the tests that would be loaded by default from the 2355module. It is common for test modules to only want to add or remove tests 2356from the standard set of tests. 2357The third argument is used when loading packages as part of test discovery. 2358 2359A typical ``load_tests`` function that loads tests from a specific set of 2360:class:`TestCase` classes may look like:: 2361 2362 test_cases = (TestCase1, TestCase2, TestCase3) 2363 2364 def load_tests(loader, tests, pattern): 2365 suite = TestSuite() 2366 for test_class in test_cases: 2367 tests = loader.loadTestsFromTestCase(test_class) 2368 suite.addTests(tests) 2369 return suite 2370 2371If discovery is started in a directory containing a package, either from the 2372command line or by calling :meth:`TestLoader.discover`, then the package 2373:file:`__init__.py` will be checked for ``load_tests``. If that function does 2374not exist, discovery will recurse into the package as though it were just 2375another directory. Otherwise, discovery of the package's tests will be left up 2376to ``load_tests`` which is called with the following arguments:: 2377 2378 load_tests(loader, standard_tests, pattern) 2379 2380This should return a :class:`TestSuite` representing all the tests 2381from the package. (``standard_tests`` will only contain tests 2382collected from :file:`__init__.py`.) 2383 2384Because the pattern is passed into ``load_tests`` the package is free to 2385continue (and potentially modify) test discovery. A 'do nothing' 2386``load_tests`` function for a test package would look like:: 2387 2388 def load_tests(loader, standard_tests, pattern): 2389 # top level directory cached on loader instance 2390 this_dir = os.path.dirname(__file__) 2391 package_tests = loader.discover(start_dir=this_dir, pattern=pattern) 2392 standard_tests.addTests(package_tests) 2393 return standard_tests 2394 2395.. versionchanged:: 3.5 2396 Discovery no longer checks package names for matching *pattern* due to the 2397 impossibility of package names matching the default pattern. 2398 2399 2400 2401Class and Module Fixtures 2402------------------------- 2403 2404Class and module level fixtures are implemented in :class:`TestSuite`. When 2405the test suite encounters a test from a new class then :meth:`tearDownClass` 2406from the previous class (if there is one) is called, followed by 2407:meth:`setUpClass` from the new class. 2408 2409Similarly if a test is from a different module from the previous test then 2410``tearDownModule`` from the previous module is run, followed by 2411``setUpModule`` from the new module. 2412 2413After all the tests have run the final ``tearDownClass`` and 2414``tearDownModule`` are run. 2415 2416Note that shared fixtures do not play well with [potential] features like test 2417parallelization and they break test isolation. They should be used with care. 2418 2419The default ordering of tests created by the unittest test loaders is to group 2420all tests from the same modules and classes together. This will lead to 2421``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and 2422module. If you randomize the order, so that tests from different modules and 2423classes are adjacent to each other, then these shared fixture functions may be 2424called multiple times in a single test run. 2425 2426Shared fixtures are not intended to work with suites with non-standard 2427ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to 2428support shared fixtures. 2429 2430If there are any exceptions raised during one of the shared fixture functions 2431the test is reported as an error. Because there is no corresponding test 2432instance an ``_ErrorHolder`` object (that has the same interface as a 2433:class:`TestCase`) is created to represent the error. If you are just using 2434the standard unittest test runner then this detail doesn't matter, but if you 2435are a framework author it may be relevant. 2436 2437 2438setUpClass and tearDownClass 2439~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 2440 2441These must be implemented as class methods:: 2442 2443 import unittest 2444 2445 class Test(unittest.TestCase): 2446 @classmethod 2447 def setUpClass(cls): 2448 cls._connection = createExpensiveConnectionObject() 2449 2450 @classmethod 2451 def tearDownClass(cls): 2452 cls._connection.destroy() 2453 2454If you want the ``setUpClass`` and ``tearDownClass`` on base classes called 2455then you must call up to them yourself. The implementations in 2456:class:`TestCase` are empty. 2457 2458If an exception is raised during a ``setUpClass`` then the tests in the class 2459are not run and the ``tearDownClass`` is not run. Skipped classes will not 2460have ``setUpClass`` or ``tearDownClass`` run. If the exception is a 2461:exc:`SkipTest` exception then the class will be reported as having been skipped 2462instead of as an error. 2463 2464 2465setUpModule and tearDownModule 2466~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 2467 2468These should be implemented as functions:: 2469 2470 def setUpModule(): 2471 createConnection() 2472 2473 def tearDownModule(): 2474 closeConnection() 2475 2476If an exception is raised in a ``setUpModule`` then none of the tests in the 2477module will be run and the ``tearDownModule`` will not be run. If the exception is a 2478:exc:`SkipTest` exception then the module will be reported as having been skipped 2479instead of as an error. 2480 2481To add cleanup code that must be run even in the case of an exception, use 2482``addModuleCleanup``: 2483 2484 2485.. function:: addModuleCleanup(function, /, *args, **kwargs) 2486 2487 Add a function to be called after :func:`tearDownModule` to cleanup 2488 resources used during the test class. Functions will be called in reverse 2489 order to the order they are added (:abbr:`LIFO (last-in, first-out)`). 2490 They are called with any arguments and keyword arguments passed into 2491 :meth:`addModuleCleanup` when they are added. 2492 2493 If :meth:`setUpModule` fails, meaning that :func:`tearDownModule` is not 2494 called, then any cleanup functions added will still be called. 2495 2496 .. versionadded:: 3.8 2497 2498 2499.. classmethod:: enterModuleContext(cm) 2500 2501 Enter the supplied :term:`context manager`. If successful, also 2502 add its :meth:`~object.__exit__` method as a cleanup function by 2503 :func:`addModuleCleanup` and return the result of the 2504 :meth:`~object.__enter__` method. 2505 2506 .. versionadded:: 3.11 2507 2508 2509.. function:: doModuleCleanups() 2510 2511 This function is called unconditionally after :func:`tearDownModule`, or 2512 after :func:`setUpModule` if :func:`setUpModule` raises an exception. 2513 2514 It is responsible for calling all the cleanup functions added by 2515 :func:`addModuleCleanup`. If you need cleanup functions to be called 2516 *prior* to :func:`tearDownModule` then you can call 2517 :func:`doModuleCleanups` yourself. 2518 2519 :func:`doModuleCleanups` pops methods off the stack of cleanup 2520 functions one at a time, so it can be called at any time. 2521 2522 .. versionadded:: 3.8 2523 2524 2525Signal Handling 2526--------------- 2527 2528.. versionadded:: 3.2 2529 2530The :option:`-c/--catch <unittest -c>` command-line option to unittest, 2531along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide 2532more friendly handling of control-C during a test run. With catch break 2533behavior enabled control-C will allow the currently running test to complete, 2534and the test run will then end and report all the results so far. A second 2535control-c will raise a :exc:`KeyboardInterrupt` in the usual way. 2536 2537The control-c handling signal handler attempts to remain compatible with code or 2538tests that install their own :const:`signal.SIGINT` handler. If the ``unittest`` 2539handler is called but *isn't* the installed :const:`signal.SIGINT` handler, 2540i.e. it has been replaced by the system under test and delegated to, then it 2541calls the default handler. This will normally be the expected behavior by code 2542that replaces an installed handler and delegates to it. For individual tests 2543that need ``unittest`` control-c handling disabled the :func:`removeHandler` 2544decorator can be used. 2545 2546There are a few utility functions for framework authors to enable control-c 2547handling functionality within test frameworks. 2548 2549.. function:: installHandler() 2550 2551 Install the control-c handler. When a :const:`signal.SIGINT` is received 2552 (usually in response to the user pressing control-c) all registered results 2553 have :meth:`~TestResult.stop` called. 2554 2555 2556.. function:: registerResult(result) 2557 2558 Register a :class:`TestResult` object for control-c handling. Registering a 2559 result stores a weak reference to it, so it doesn't prevent the result from 2560 being garbage collected. 2561 2562 Registering a :class:`TestResult` object has no side-effects if control-c 2563 handling is not enabled, so test frameworks can unconditionally register 2564 all results they create independently of whether or not handling is enabled. 2565 2566 2567.. function:: removeResult(result) 2568 2569 Remove a registered result. Once a result has been removed then 2570 :meth:`~TestResult.stop` will no longer be called on that result object in 2571 response to a control-c. 2572 2573 2574.. function:: removeHandler(function=None) 2575 2576 When called without arguments this function removes the control-c handler 2577 if it has been installed. This function can also be used as a test decorator 2578 to temporarily remove the handler while the test is being executed:: 2579 2580 @unittest.removeHandler 2581 def test_signal_handling(self): 2582 ... 2583