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