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