blob: 0c29408cb192146e7d1e1919736ccf57e44614cd [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`unittest` --- Unit testing framework
2==========================================
3
4.. module:: unittest
5 :synopsis: Unit testing framework for Python.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. 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
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040012**Source code:** :source:`Lib/unittest/__init__.py`
13
14--------------
15
Ezio Melotti22170ed2010-11-20 09:57:27 +000016(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>`.)
Georg Brandl116aa622007-08-15 14:28:22 +000018
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010019The :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.
Georg Brandl116aa622007-08-15 14:28:22 +000024
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010025To achieve this, :mod:`unittest` supports some important concepts in an
26object-oriented way:
Georg Brandl116aa622007-08-15 14:28:22 +000027
28test fixture
29 A :dfn:`test fixture` represents the preparation needed to perform one or more
Julien Palard513e9b442019-02-19 15:46:07 +010030 tests, and any associated cleanup actions. This may involve, for example,
Georg Brandl116aa622007-08-15 14:28:22 +000031 creating temporary or proxy databases, directories, or starting a server
32 process.
33
34test case
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010035 A :dfn:`test case` is the individual unit of testing. It checks for a specific
Georg Brandl116aa622007-08-15 14:28:22 +000036 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
Georg Brandl116aa622007-08-15 14:28:22 +000049
50.. seealso::
51
52 Module :mod:`doctest`
53 Another test-support module with a very different flavor.
54
R David Murraya1005ed2015-07-04 15:44:14 -040055 `Simple Smalltalk Testing: With Patterns <https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000056 Kent Beck's original paper on testing frameworks using the pattern shared
57 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000058
Jon Dufresne88eeda62019-10-19 12:22:20 -070059 `pytest <https://docs.pytest.org/>`_
60 Third-party unittest framework with a lighter-weight syntax for writing
Benjamin Petersond2397752009-06-27 23:45:02 +000061 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000062
Georg Brandle73778c2014-10-29 08:36:35 +010063 `The Python Testing Tools Taxonomy <https://wiki.python.org/moin/PythonTestingToolsTaxonomy>`_
Benjamin Petersonb48af542010-04-11 20:43:16 +000064 An extensive list of Python testing tools including functional testing
65 frameworks and mock object libraries.
Benjamin Petersond2397752009-06-27 23:45:02 +000066
Benjamin Petersonb48af542010-04-11 20:43:16 +000067 `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.
Benjamin Petersond2397752009-06-27 23:45:02 +000070
Michael Foord90efac72011-01-03 15:39:49 +000071 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
Senthil Kumaran847c33c2012-10-27 11:04:55 -070073 for those new to unit testing. For production environments it is
74 recommended that tests be driven by a continuous integration system such as
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030075 `Buildbot <https://buildbot.net/>`_, `Jenkins <https://jenkins.io/>`_
Dmytro Litvinov5e382672020-07-28 17:48:32 +030076 or `Travis-CI <https://travis-ci.com>`_, or `AppVeyor <https://www.appveyor.com/>`_.
Michael Foord90efac72011-01-03 15:39:49 +000077
78
Georg Brandl116aa622007-08-15 14:28:22 +000079.. _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
Ezio Melotti2e3998f2015-03-24 12:42:41 +020088Here is a short script to test three string methods::
Georg Brandl116aa622007-08-15 14:28:22 +000089
Ezio Melotti2e3998f2015-03-24 12:42:41 +020090 import unittest
Georg Brandl116aa622007-08-15 14:28:22 +000091
Ezio Melotti2e3998f2015-03-24 12:42:41 +020092 class TestStringMethods(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +000093
Serhiy Storchakadba90392016-05-10 12:01:23 +030094 def test_upper(self):
95 self.assertEqual('foo'.upper(), 'FOO')
Georg Brandl116aa622007-08-15 14:28:22 +000096
Serhiy Storchakadba90392016-05-10 12:01:23 +030097 def test_isupper(self):
98 self.assertTrue('FOO'.isupper())
99 self.assertFalse('Foo'.isupper())
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Serhiy Storchakadba90392016-05-10 12:01:23 +0300101 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)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000107
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200108 if __name__ == '__main__':
109 unittest.main()
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Benjamin Peterson52baa292009-03-24 00:56:30 +0000112A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000113individual 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
Benjamin Peterson52baa292009-03-24 00:56:30 +0000117The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200118expected 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200124The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you
125to define instructions that will be executed before and after each test method.
Benjamin Peterson8a6ddb92016-01-07 22:01:26 -0800126They are covered in more detail in the section :ref:`organizing-tests`.
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000129provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000130line, the above script produces an output that looks like this::
131
132 ...
133 ----------------------------------------------------------------------
134 Ran 3 tests in 0.000s
135
136 OK
137
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100138Passing the ``-v`` option to your test script will instruct :func:`unittest.main`
139to enable a higher level of verbosity, and produce the following output::
Georg Brandl116aa622007-08-15 14:28:22 +0000140
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200141 test_isupper (__main__.TestStringMethods) ... ok
142 test_split (__main__.TestStringMethods) ... ok
143 test_upper (__main__.TestStringMethods) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145 ----------------------------------------------------------------------
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200146 Ran 3 tests in 0.001s
Georg Brandl116aa622007-08-15 14:28:22 +0000147
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
Benjamin Petersonb48af542010-04-11 20:43:16 +0000154
155.. _unittest-command-line-interface:
156
Éric Araujo76338ec2010-11-26 23:46:18 +0000157Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000158----------------------
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
Michael Foord37d120a2010-12-04 01:11:21 +0000170Test 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
Benjamin Petersonb48af542010-04-11 20:43:16 +0000180You can run tests with more detail (higher verbosity) by passing in the -v flag::
181
182 python -m unittest -v test_module
183
Michael Foord086f3082010-11-21 21:28:01 +0000184When executed without arguments :ref:`unittest-test-discovery` is started::
185
186 python -m unittest
187
Éric Araujo713d3032010-11-18 16:38:46 +0000188For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000189
190 python -m unittest -h
191
Georg Brandl67b21b72010-08-17 15:07:14 +0000192.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000193 In earlier versions it was only possible to run individual test methods and
194 not modules or classes.
195
196
Éric Araujo76338ec2010-11-26 23:46:18 +0000197Command-line options
198~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000199
Éric Araujod3309df2010-11-21 03:09:17 +0000200:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000201
Éric Araujo713d3032010-11-18 16:38:46 +0000202.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000203
Éric Araujo713d3032010-11-18 16:38:46 +0000204.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000205
Éric Araujo713d3032010-11-18 16:38:46 +0000206 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.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000209
Éric Araujo713d3032010-11-18 16:38:46 +0000210.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000211
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300212 :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
Éric Araujo713d3032010-11-18 16:38:46 +0000214 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000215
Éric Araujo713d3032010-11-18 16:38:46 +0000216 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000217
Éric Araujo713d3032010-11-18 16:38:46 +0000218.. cmdoption:: -f, --failfast
219
220 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000221
Jonas Haag5b48dc62017-11-25 16:23:52 +0100222.. cmdoption:: -k
223
224 Only run test methods and classes that match the pattern or substring.
225 This option may be used multiple times, in which case all test cases that
226 match of the given patterns are included.
227
228 Patterns that contain a wildcard character (``*``) are matched against the
229 test name using :meth:`fnmatch.fnmatchcase`; otherwise simple case-sensitive
230 substring matching is used.
231
232 Patterns are matched against the fully qualified test method name as
233 imported by the test loader.
234
235 For example, ``-k foo`` matches ``foo_tests.SomeTest.test_something``,
236 ``bar_tests.SomeTest.test_foo``, but not ``bar_tests.FooTest.test_something``.
237
Robert Collinsf0c819a2015-03-06 13:46:35 +1300238.. cmdoption:: --locals
239
240 Show local variables in tracebacks.
241
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000242.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000243 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000244
Robert Collinsf0c819a2015-03-06 13:46:35 +1300245.. versionadded:: 3.5
246 The command-line option ``--locals``.
247
Jonas Haag5b48dc62017-11-25 16:23:52 +0100248.. versionadded:: 3.7
249 The command-line option ``-k``.
250
Benjamin Petersonb48af542010-04-11 20:43:16 +0000251The 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
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000260.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000261
Ezio Melotti3d995842011-03-08 16:17:35 +0200262Unittest supports simple test discovery. In order to be compatible with test
263discovery, all of the test files must be :ref:`modules <tut-modules>` or
Larry Hastings3732ed22014-03-15 21:13:56 -0700264: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>`).
Benjamin Petersonb48af542010-04-11 20:43:16 +0000268
269Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000270used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000271
272 cd project_directory
273 python -m unittest discover
274
Michael Foord086f3082010-11-21 21:28:01 +0000275.. 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
Éric Araujo941afed2011-09-01 02:47:34 +0200279 discovery the ``discover`` sub-command must be used explicitly.
Michael Foord086f3082010-11-21 21:28:01 +0000280
Benjamin Petersonb48af542010-04-11 20:43:16 +0000281The ``discover`` sub-command has the following options:
282
Éric Araujo713d3032010-11-18 16:38:46 +0000283.. program:: unittest discover
284
285.. cmdoption:: -v, --verbose
286
287 Verbose output
288
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800289.. cmdoption:: -s, --start-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000290
Éric Araujo941afed2011-09-01 02:47:34 +0200291 Directory to start discovery (``.`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000292
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800293.. cmdoption:: -p, --pattern pattern
Éric Araujo713d3032010-11-18 16:38:46 +0000294
Éric Araujo941afed2011-09-01 02:47:34 +0200295 Pattern to match test files (``test*.py`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000296
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800297.. cmdoption:: -t, --top-level-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000298
299 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000300
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000301The :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::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000304
Robert Collinsa2b00552015-08-24 12:14:28 +1200305 python -m unittest discover -s project_directory -p "*_test.py"
306 python -m unittest discover project_directory "*_test.py"
Benjamin Petersonb48af542010-04-11 20:43:16 +0000307
Michael Foord16f3e902010-05-08 15:13:42 +0000308As 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
Senthil Kumaran916bd382010-10-15 12:55:19 +0000315 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
Michael Foord16f3e902010-05-08 15:13:42 +0000318 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
Benjamin Petersonb48af542010-04-11 20:43:16 +0000329Test modules and packages can customize test loading and discovery by through
330the `load_tests protocol`_.
331
Larry Hastings3732ed22014-03-15 21:13:56 -0700332.. versionchanged:: 3.4
Inada Naoki5a4aa4c2021-02-22 15:14:26 +0900333 Test discovery supports :term:`namespace packages <namespace package>`
Zackery Spytz2abbd8f2021-04-30 01:32:19 -0600334 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``).
Larry Hastings3732ed22014-03-15 21:13:56 -0700337
Benjamin Petersonb48af542010-04-11 20:43:16 +0000338
Georg Brandl116aa622007-08-15 14:28:22 +0000339.. _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`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000346test 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`.
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Georg Brandl116aa622007-08-15 14:28:22 +0000350The 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
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100354The 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::
Georg Brandl116aa622007-08-15 14:28:22 +0000357
358 import unittest
359
360 class DefaultWidgetSizeTestCase(unittest.TestCase):
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100361 def test_default_widget_size(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000362 widget = Widget('The widget')
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100363 self.assertEqual(widget.size(), (50, 50))
Georg Brandl116aa622007-08-15 14:28:22 +0000364
Sandro Tosi41b24042012-01-21 10:59:37 +0100365Note that in order to test something, we use one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000366methods provided by the :class:`TestCase` base class. If the test fails, an
Gregory P. Smithdff46752018-05-17 10:08:45 -0500367exception 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`.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100371Tests 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::
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376 import unittest
377
Berker Peksagab75e022016-08-06 03:00:03 +0300378 class WidgetTestCase(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000379 def setUp(self):
380 self.widget = Widget('The widget')
381
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100382 def test_default_widget_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000383 self.assertEqual(self.widget.size(), (50,50),
384 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100386 def test_widget_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000387 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000388 self.assertEqual(self.widget.size(), (100,150),
389 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100391.. 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
Benjamin Peterson52baa292009-03-24 00:56:30 +0000396If the :meth:`~TestCase.setUp` method raises an exception while the test is
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100397running, the framework will consider the test to have suffered an error, and
398the test method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000399
Benjamin Peterson52baa292009-03-24 00:56:30 +0000400Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100401after the test method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403 import unittest
404
Berker Peksagab75e022016-08-06 03:00:03 +0300405 class WidgetTestCase(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000406 def setUp(self):
407 self.widget = Widget('The widget')
408
409 def tearDown(self):
410 self.widget.dispose()
Georg Brandl116aa622007-08-15 14:28:22 +0000411
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100412If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be
413run whether the test method succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Gregory P. Smithdff46752018-05-17 10:08:45 -0500415Such 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
Berker Peksag2e5566d2018-08-04 00:56:55 +0300418:meth:`~TestCase.setUp`, :meth:`~TestCase.tearDown`, and :meth:`~TestCase.__init__`
Gregory P. Smithdff46752018-05-17 10:08:45 -0500419will be called once per test.
Georg Brandl116aa622007-08-15 14:28:22 +0000420
Gregory P. Smithdff46752018-05-17 10:08:45 -0500421It 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000427
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100428However, should you want to customize the building of your test suite,
429you can do it yourself::
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431 def suite():
432 suite = unittest.TestSuite()
Berker Peksag92551042017-10-13 06:41:57 +0300433 suite.addTest(WidgetTestCase('test_default_widget_size'))
434 suite.addTest(WidgetTestCase('test_widget_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000435 return suite
436
Berker Peksag92551042017-10-13 06:41:57 +0300437 if __name__ == '__main__':
438 runner = unittest.TextTestRunner()
439 runner.run(suite())
440
Georg Brandl116aa622007-08-15 14:28:22 +0000441You 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
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100483one can create an equivalent test case instance as follows, with optional
484set-up and tear-down methods::
Georg Brandl116aa622007-08-15 14:28:22 +0000485
486 testcase = unittest.FunctionTestCase(testSomething,
487 setUp=makeSomethingDB,
488 tearDown=deleteSomethingDB)
489
Georg Brandl116aa622007-08-15 14:28:22 +0000490.. note::
491
Benjamin Petersond2397752009-06-27 23:45:02 +0000492 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000496
Benjamin Peterson52baa292009-03-24 00:56:30 +0000497In 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
Georg Brandl116aa622007-08-15 14:28:22 +0000502
Benjamin Peterson5254c042009-03-23 22:25:03 +0000503.. _unittest-skipping:
504
505Skipping tests and expected failures
506------------------------------------
507
Michael Foordf5c851a2010-02-05 21:48:03 +0000508.. versionadded:: 3.1
509
Benjamin Peterson5254c042009-03-23 22:25:03 +0000510Unittest supports skipping individual test methods and even whole classes of
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200511tests. In addition, it supports marking a test as an "expected failure," a test
Benjamin Peterson5254c042009-03-23 22:25:03 +0000512that 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`
Makdonffed76b2019-06-01 00:19:12 +0800516or one of its conditional variants, calling :meth:`TestCase.skipTest` within a
517:meth:`~TestCase.setUp` or test method, or raising :exc:`SkipTest` directly.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000518
Ezio Melottifed69ba2013-03-01 21:26:04 +0200519Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000520
521 class MyTestCase(unittest.TestCase):
522
523 @unittest.skip("demonstrating skipping")
524 def test_nothing(self):
525 self.fail("shouldn't happen")
526
Benjamin Petersond2397752009-06-27 23:45:02 +0000527 @unittest.skipIf(mylib.__version__ < (1, 3),
528 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000529 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
Makdonffed76b2019-06-01 00:19:12 +0800538 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
Ezio Melottifed69ba2013-03-01 21:26:04 +0200544This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000545
Benjamin Petersonded31c42009-03-30 15:04:16 +0000546 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000547 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Makdonffed76b2019-06-01 00:19:12 +0800548 test_maybe_skipped (__main__.MyTestCase) ... skipped 'external resource not available'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000549 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000550
551 ----------------------------------------------------------------------
Makdonffed76b2019-06-01 00:19:12 +0800552 Ran 4 tests in 0.005s
Benjamin Petersonded31c42009-03-30 15:04:16 +0000553
Makdonffed76b2019-06-01 00:19:12 +0800554 OK (skipped=4)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000555
Ezio Melottifed69ba2013-03-01 21:26:04 +0200556Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000557
Sandro Tosi317075d2012-03-31 18:34:59 +0200558 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000559 class MySkippedTestCase(unittest.TestCase):
560 def test_not_run(self):
561 pass
562
Benjamin Peterson52baa292009-03-24 00:56:30 +0000563:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
564that needs to be set up is not available.
565
Benjamin Peterson5254c042009-03-23 22:25:03 +0000566Expected 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
Ezio Melottifed69ba2013-03-01 21:26:04 +0200575the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000576
577 def skipUnlessHasattr(obj, attr):
578 if hasattr(obj, attr):
579 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200580 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000581
Makdonffed76b2019-06-01 00:19:12 +0800582The following decorators and exception implement test skipping and expected failures:
Benjamin Peterson5254c042009-03-23 22:25:03 +0000583
Georg Brandl8a1caa22010-07-29 16:01:11 +0000584.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000585
586 Unconditionally skip the decorated test. *reason* should describe why the
587 test is being skipped.
588
Georg Brandl8a1caa22010-07-29 16:01:11 +0000589.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000590
591 Skip the decorated test if *condition* is true.
592
Georg Brandl8a1caa22010-07-29 16:01:11 +0000593.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000594
Georg Brandl6faee4e2010-09-21 14:48:28 +0000595 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000596
Georg Brandl8a1caa22010-07-29 16:01:11 +0000597.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000598
Irit Katrielfa874822020-10-19 22:27:16 +0100599 Mark the test as an expected failure or error. If the test fails or errors
600 it will be considered a success. If the test passes, it will be considered
601 a failure.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000602
Ezio Melotti265281a2013-03-27 20:11:55 +0200603.. exception:: SkipTest(reason)
604
605 This exception is raised to skip a test.
606
607 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
608 decorators instead of raising this directly.
609
R David Murray42fa1102014-01-03 13:03:36 -0500610Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them.
611Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run.
612Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000613
Benjamin Peterson5254c042009-03-23 22:25:03 +0000614
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100615.. _subtests:
616
617Distinguishing test iterations using subtests
618---------------------------------------------
619
620.. versionadded:: 3.4
621
Géry Ogam009b2f02018-11-09 20:34:54 +0100622When there are very small differences among your tests, for
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100623instance some parameters, unittest allows you to distinguish them inside
624the body of a test method using the :meth:`~TestCase.subTest` context manager.
625
626For example, the following test::
627
628 class NumbersTest(unittest.TestCase):
629
630 def test_even(self):
631 """
632 Test that numbers between 0 and 5 are all even.
633 """
634 for i in range(0, 6):
635 with self.subTest(i=i):
636 self.assertEqual(i % 2, 0)
637
638will produce the following output::
639
640 ======================================================================
641 FAIL: test_even (__main__.NumbersTest) (i=1)
642 ----------------------------------------------------------------------
643 Traceback (most recent call last):
644 File "subtests.py", line 32, in test_even
645 self.assertEqual(i % 2, 0)
646 AssertionError: 1 != 0
647
648 ======================================================================
649 FAIL: test_even (__main__.NumbersTest) (i=3)
650 ----------------------------------------------------------------------
651 Traceback (most recent call last):
652 File "subtests.py", line 32, in test_even
653 self.assertEqual(i % 2, 0)
654 AssertionError: 1 != 0
655
656 ======================================================================
657 FAIL: test_even (__main__.NumbersTest) (i=5)
658 ----------------------------------------------------------------------
659 Traceback (most recent call last):
660 File "subtests.py", line 32, in test_even
661 self.assertEqual(i % 2, 0)
662 AssertionError: 1 != 0
663
664Without using a subtest, execution would stop after the first failure,
665and the error would be less easy to diagnose because the value of ``i``
666wouldn't be displayed::
667
668 ======================================================================
669 FAIL: test_even (__main__.NumbersTest)
670 ----------------------------------------------------------------------
671 Traceback (most recent call last):
672 File "subtests.py", line 32, in test_even
673 self.assertEqual(i % 2, 0)
674 AssertionError: 1 != 0
675
676
Georg Brandl116aa622007-08-15 14:28:22 +0000677.. _unittest-contents:
678
679Classes and functions
680---------------------
681
Benjamin Peterson52baa292009-03-24 00:56:30 +0000682This section describes in depth the API of :mod:`unittest`.
683
684
685.. _testcase-objects:
686
687Test cases
688~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Georg Brandl7f01a132009-09-16 15:58:14 +0000690.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100692 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000693 in the :mod:`unittest` universe. This class is intended to be used as a base
694 class, with specific tests being implemented by concrete subclasses. This class
695 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100696 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000697 kinds of failure.
698
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100699 Each instance of :class:`TestCase` will run a single base method: the method
Robert Collinse02f6c22015-07-23 06:37:26 +1200700 named *methodName*.
701 In most uses of :class:`TestCase`, you will neither change
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100702 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Michael Foord1341bb02011-03-14 19:01:46 -0400704 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100705 :class:`TestCase` can be instantiated successfully without providing a
706 *methodName*. This makes it easier to experiment with :class:`TestCase`
707 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000708
709 :class:`TestCase` instances provide three groups of methods: one group used
710 to run the test, another used by the test implementation to check conditions
711 and report failures, and some inquiry methods allowing information about the
712 test itself to be gathered.
713
714 Methods in the first group (running the test) are:
715
Benjamin Peterson52baa292009-03-24 00:56:30 +0000716 .. method:: setUp()
717
718 Method called to prepare the test fixture. This is called immediately
Terry Jan Reedy7f84d1e2014-04-15 23:44:14 -0400719 before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`,
720 any exception raised by this method will be considered an error rather than
Terry Jan Reedy6ac42402014-04-15 23:38:18 -0400721 a test failure. The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000722
723
724 .. method:: tearDown()
725
726 Method called immediately after the test method has been called and the
727 result recorded. This is called even if the test method raised an
728 exception, so the implementation in subclasses may need to be particularly
Ezio Melotti8dea74f2016-03-13 09:40:09 +0200729 careful about checking internal state. Any exception, other than
730 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
731 considered an additional error rather than a test failure (thus increasing
732 the total number of reported errors). This method will only be called if
733 the :meth:`setUp` succeeds, regardless of the outcome of the test method.
734 The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000735
736
Benjamin Petersonb48af542010-04-11 20:43:16 +0000737 .. method:: setUpClass()
738
Ville Skyttäc33bb5d2018-08-23 17:49:18 +0300739 A class method called before tests in an individual class are run.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000740 ``setUpClass`` is called with the class as the only argument
741 and must be decorated as a :func:`classmethod`::
742
743 @classmethod
744 def setUpClass(cls):
745 ...
746
747 See `Class and Module Fixtures`_ for more details.
748
749 .. versionadded:: 3.2
750
751
752 .. method:: tearDownClass()
753
754 A class method called after tests in an individual class have run.
755 ``tearDownClass`` is called with the class as the only argument
756 and must be decorated as a :meth:`classmethod`::
757
758 @classmethod
759 def tearDownClass(cls):
760 ...
761
762 See `Class and Module Fixtures`_ for more details.
763
764 .. versionadded:: 3.2
765
766
Georg Brandl7f01a132009-09-16 15:58:14 +0000767 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000768
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100769 Run the test, collecting the result into the :class:`TestResult` object
770 passed as *result*. If *result* is omitted or ``None``, a temporary
771 result object is created (by calling the :meth:`defaultTestResult`
772 method) and used. The result object is returned to :meth:`run`'s
773 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000774
775 The same effect may be had by simply calling the :class:`TestCase`
776 instance.
777
Michael Foord1341bb02011-03-14 19:01:46 -0400778 .. versionchanged:: 3.3
779 Previous versions of ``run`` did not return the result. Neither did
780 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000781
Benjamin Petersone549ead2009-03-28 21:42:05 +0000782 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000783
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000784 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000785 test. See :ref:`unittest-skipping` for more information.
786
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000787 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000788
Benjamin Peterson52baa292009-03-24 00:56:30 +0000789
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100790 .. method:: subTest(msg=None, **params)
791
792 Return a context manager which executes the enclosed code block as a
793 subtest. *msg* and *params* are optional, arbitrary values which are
794 displayed whenever a subtest fails, allowing you to identify them
795 clearly.
796
797 A test case can contain any number of subtest declarations, and
798 they can be arbitrarily nested.
799
800 See :ref:`subtests` for more information.
801
802 .. versionadded:: 3.4
803
804
Benjamin Peterson52baa292009-03-24 00:56:30 +0000805 .. method:: debug()
806
807 Run the test without collecting the result. This allows exceptions raised
808 by the test to be propagated to the caller, and can be used to support
809 running tests under a debugger.
810
Ezio Melotti22170ed2010-11-20 09:57:27 +0000811 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000812
Ezio Melottif418db22016-01-12 11:03:31 +0200813 The :class:`TestCase` class provides several assert methods to check for and
814 report failures. The following table lists the most commonly used methods
815 (see the tables below for more assert methods):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000816
Ezio Melotti4370b302010-11-03 20:39:14 +0000817 +-----------------------------------------+-----------------------------+---------------+
818 | Method | Checks that | New in |
819 +=========================================+=============================+===============+
820 | :meth:`assertEqual(a, b) | ``a == b`` | |
821 | <TestCase.assertEqual>` | | |
822 +-----------------------------------------+-----------------------------+---------------+
823 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
824 | <TestCase.assertNotEqual>` | | |
825 +-----------------------------------------+-----------------------------+---------------+
826 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
827 | <TestCase.assertTrue>` | | |
828 +-----------------------------------------+-----------------------------+---------------+
829 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
830 | <TestCase.assertFalse>` | | |
831 +-----------------------------------------+-----------------------------+---------------+
832 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
833 | <TestCase.assertIs>` | | |
834 +-----------------------------------------+-----------------------------+---------------+
835 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
836 | <TestCase.assertIsNot>` | | |
837 +-----------------------------------------+-----------------------------+---------------+
838 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
839 | <TestCase.assertIsNone>` | | |
840 +-----------------------------------------+-----------------------------+---------------+
841 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
842 | <TestCase.assertIsNotNone>` | | |
843 +-----------------------------------------+-----------------------------+---------------+
844 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
845 | <TestCase.assertIn>` | | |
846 +-----------------------------------------+-----------------------------+---------------+
847 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
848 | <TestCase.assertNotIn>` | | |
849 +-----------------------------------------+-----------------------------+---------------+
850 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
851 | <TestCase.assertIsInstance>` | | |
852 +-----------------------------------------+-----------------------------+---------------+
853 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
854 | <TestCase.assertNotIsInstance>` | | |
855 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000856
Ezio Melottib4dc2502011-05-06 15:01:41 +0300857 All the assert methods accept a *msg* argument that, if specified, is used
858 as the error message on failure (see also :data:`longMessage`).
859 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
860 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
861 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000862
Michael Foorde180d392011-01-28 19:51:48 +0000863 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000864
Michael Foorde180d392011-01-28 19:51:48 +0000865 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000866 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000867
Michael Foorde180d392011-01-28 19:51:48 +0000868 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000869 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200870 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000871 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000872 error message (see also the :ref:`list of type-specific methods
873 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000874
Raymond Hettinger35a88362009-04-09 00:08:24 +0000875 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200876 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000877
Michael Foord28a817e2010-02-09 00:03:57 +0000878 .. versionchanged:: 3.2
879 :meth:`assertMultiLineEqual` added as the default type equality
880 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000881
Benjamin Peterson52baa292009-03-24 00:56:30 +0000882
Michael Foorde180d392011-01-28 19:51:48 +0000883 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000884
Michael Foorde180d392011-01-28 19:51:48 +0000885 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000886 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000887
Ezio Melotti4370b302010-11-03 20:39:14 +0000888 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000889 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000890
Ezio Melotti4841fd62010-11-05 15:43:40 +0000891 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000892
Ezio Melotti4841fd62010-11-05 15:43:40 +0000893 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
894 is True`` (use ``assertIs(expr, True)`` for the latter). This method
895 should also be avoided when more specific methods are available (e.g.
896 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
897 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000898
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000899
Michael Foorde180d392011-01-28 19:51:48 +0000900 .. method:: assertIs(first, second, msg=None)
901 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000902
Ram Rachumbd8c22e2020-11-22 07:59:48 +0200903 Test that *first* and *second* are (or are not) the same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000904
Raymond Hettinger35a88362009-04-09 00:08:24 +0000905 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000906
907
Ezio Melotti4370b302010-11-03 20:39:14 +0000908 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000909 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000910
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300911 Test that *expr* is (or is not) ``None``.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000912
Ezio Melotti4370b302010-11-03 20:39:14 +0000913 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000914
915
Christoph Zwerschkea388bbd2020-04-17 03:54:53 +0200916 .. method:: assertIn(member, container, msg=None)
917 assertNotIn(member, container, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000918
Christoph Zwerschkea388bbd2020-04-17 03:54:53 +0200919 Test that *member* is (or is not) in *container*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000920
Raymond Hettinger35a88362009-04-09 00:08:24 +0000921 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000922
923
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000924 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000925 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000926
Ezio Melotti9794a262010-11-04 14:52:13 +0000927 Test that *obj* is (or is not) an instance of *cls* (which can be a
928 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200929 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000930
Ezio Melotti4370b302010-11-03 20:39:14 +0000931 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000932
933
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000934
Ezio Melottif418db22016-01-12 11:03:31 +0200935 It is also possible to check the production of exceptions, warnings, and
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200936 log messages using the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000937
Ezio Melotti4370b302010-11-03 20:39:14 +0000938 +---------------------------------------------------------+--------------------------------------+------------+
939 | Method | Checks that | New in |
940 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200941 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000942 | <TestCase.assertRaises>` | | |
943 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300944 | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
945 | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000946 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200947 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000948 | <TestCase.assertWarns>` | | |
949 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300950 | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
951 | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000952 +---------------------------------------------------------+--------------------------------------+------------+
Georg Brandled007d52013-11-24 16:09:26 +0100953 | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 |
954 | <TestCase.assertLogs>` | with minimum *level* | |
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200955 +---------------------------------------------------------+--------------------------------------+------------+
Kit Choi6b34d7b2020-07-01 22:08:38 +0100956 | :meth:`assertNoLogs(logger, level) | The ``with`` block does not log on | 3.10 |
957 | <TestCase.assertNoLogs>` | *logger* with minimum *level* | |
958 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000959
Georg Brandl7f01a132009-09-16 15:58:14 +0000960 .. method:: assertRaises(exception, callable, *args, **kwds)
Benjamin Petersonbe4e5b82018-10-01 22:18:44 -0700961 assertRaises(exception, *, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000962
963 Test that an exception is raised when *callable* is called with any
964 positional or keyword arguments that are also passed to
965 :meth:`assertRaises`. The test passes if *exception* is raised, is an
966 error if another exception is raised, or fails if no exception is raised.
967 To catch any of a group of exceptions, a tuple containing the exception
968 classes may be passed as *exception*.
969
Ezio Melottib4dc2502011-05-06 15:01:41 +0300970 If only the *exception* and possibly the *msg* arguments are given,
971 return a context manager so that the code under test can be written
972 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000973
Michael Foord41531f22010-02-05 21:13:40 +0000974 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000975 do_something()
976
Ezio Melottib4dc2502011-05-06 15:01:41 +0300977 When used as a context manager, :meth:`assertRaises` accepts the
978 additional keyword argument *msg*.
979
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000980 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000981 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000982 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000983
Georg Brandl8a1caa22010-07-29 16:01:11 +0000984 with self.assertRaises(SomeException) as cm:
985 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000986
Georg Brandl8a1caa22010-07-29 16:01:11 +0000987 the_exception = cm.exception
988 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000989
Ezio Melotti49008232010-02-08 21:57:48 +0000990 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000991 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000992
Ezio Melotti49008232010-02-08 21:57:48 +0000993 .. versionchanged:: 3.2
994 Added the :attr:`exception` attribute.
995
Ezio Melottib4dc2502011-05-06 15:01:41 +0300996 .. versionchanged:: 3.3
997 Added the *msg* keyword argument when used as a context manager.
998
Benjamin Peterson52baa292009-03-24 00:56:30 +0000999
Ezio Melottied3a7d22010-12-01 02:32:32 +00001000 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Benjamin Petersone006b392018-10-02 21:38:39 -07001001 assertRaisesRegex(exception, regex, *, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001002
Ezio Melottied3a7d22010-12-01 02:32:32 +00001003 Like :meth:`assertRaises` but also tests that *regex* matches
1004 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001005 a regular expression object or a string containing a regular expression
1006 suitable for use by :func:`re.search`. Examples::
1007
Terry Jan Reedyc4565a92013-06-29 13:15:43 -04001008 self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
Ezio Melottied3a7d22010-12-01 02:32:32 +00001009 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001010
1011 or::
1012
Ezio Melottied3a7d22010-12-01 02:32:32 +00001013 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001014 int('XYZ')
1015
Georg Brandl419e3de2010-12-01 15:44:25 +00001016 .. versionadded:: 3.1
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001017 Added under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +03001018
Ezio Melottied3a7d22010-12-01 02:32:32 +00001019 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001020 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001021
Ezio Melottib4dc2502011-05-06 15:01:41 +03001022 .. versionchanged:: 3.3
1023 Added the *msg* keyword argument when used as a context manager.
1024
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001025
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001026 .. method:: assertWarns(warning, callable, *args, **kwds)
Benjamin Petersone006b392018-10-02 21:38:39 -07001027 assertWarns(warning, *, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001028
1029 Test that a warning is triggered when *callable* is called with any
1030 positional or keyword arguments that are also passed to
1031 :meth:`assertWarns`. The test passes if *warning* is triggered and
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001032 fails if it isn't. Any exception is an error.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001033 To catch any of a group of warnings, a tuple containing the warning
1034 classes may be passed as *warnings*.
1035
Ezio Melottib4dc2502011-05-06 15:01:41 +03001036 If only the *warning* and possibly the *msg* arguments are given,
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001037 return a context manager so that the code under test can be written
Ezio Melottib4dc2502011-05-06 15:01:41 +03001038 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001039
1040 with self.assertWarns(SomeWarning):
1041 do_something()
1042
Terry Jan Reedy9eda66d2013-07-27 16:15:29 -04001043 When used as a context manager, :meth:`assertWarns` accepts the
Ezio Melottib4dc2502011-05-06 15:01:41 +03001044 additional keyword argument *msg*.
1045
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001046 The context manager will store the caught warning object in its
1047 :attr:`warning` attribute, and the source line which triggered the
1048 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1049 This can be useful if the intention is to perform additional checks
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001050 on the warning caught::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001051
1052 with self.assertWarns(SomeWarning) as cm:
1053 do_something()
1054
1055 self.assertIn('myfile.py', cm.filename)
1056 self.assertEqual(320, cm.lineno)
1057
1058 This method works regardless of the warning filters in place when it
1059 is called.
1060
1061 .. versionadded:: 3.2
1062
Ezio Melottib4dc2502011-05-06 15:01:41 +03001063 .. versionchanged:: 3.3
1064 Added the *msg* keyword argument when used as a context manager.
1065
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001066
Ezio Melottied3a7d22010-12-01 02:32:32 +00001067 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Benjamin Petersone006b392018-10-02 21:38:39 -07001068 assertWarnsRegex(warning, regex, *, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001069
Ezio Melottied3a7d22010-12-01 02:32:32 +00001070 Like :meth:`assertWarns` but also tests that *regex* matches on the
1071 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001072 object or a string containing a regular expression suitable for use
1073 by :func:`re.search`. Example::
1074
Ezio Melottied3a7d22010-12-01 02:32:32 +00001075 self.assertWarnsRegex(DeprecationWarning,
1076 r'legacy_function\(\) is deprecated',
1077 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001078
1079 or::
1080
Ezio Melottied3a7d22010-12-01 02:32:32 +00001081 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001082 frobnicate('/etc/passwd')
1083
1084 .. versionadded:: 3.2
1085
Ezio Melottib4dc2502011-05-06 15:01:41 +03001086 .. versionchanged:: 3.3
1087 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001088
Antoine Pitrou0715b9f2013-09-14 19:45:47 +02001089 .. method:: assertLogs(logger=None, level=None)
1090
1091 A context manager to test that at least one message is logged on
1092 the *logger* or one of its children, with at least the given
1093 *level*.
1094
1095 If given, *logger* should be a :class:`logging.Logger` object or a
1096 :class:`str` giving the name of a logger. The default is the root
Irit Katriel1ed54432020-10-04 14:16:04 +01001097 logger, which will catch all messages that were not blocked by a
1098 non-propagating descendent logger.
Antoine Pitrou0715b9f2013-09-14 19:45:47 +02001099
1100 If given, *level* should be either a numeric logging level or
1101 its string equivalent (for example either ``"ERROR"`` or
1102 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`.
1103
1104 The test passes if at least one message emitted inside the ``with``
1105 block matches the *logger* and *level* conditions, otherwise it fails.
1106
1107 The object returned by the context manager is a recording helper
1108 which keeps tracks of the matching log messages. It has two
1109 attributes:
1110
1111 .. attribute:: records
1112
1113 A list of :class:`logging.LogRecord` objects of the matching
1114 log messages.
1115
1116 .. attribute:: output
1117
1118 A list of :class:`str` objects with the formatted output of
1119 matching messages.
1120
1121 Example::
1122
1123 with self.assertLogs('foo', level='INFO') as cm:
1124 logging.getLogger('foo').info('first message')
1125 logging.getLogger('foo.bar').error('second message')
1126 self.assertEqual(cm.output, ['INFO:foo:first message',
1127 'ERROR:foo.bar:second message'])
1128
1129 .. versionadded:: 3.4
1130
Kit Choi6b34d7b2020-07-01 22:08:38 +01001131 .. method:: assertNoLogs(logger=None, level=None)
1132
1133 A context manager to test that no messages are logged on
1134 the *logger* or one of its children, with at least the given
1135 *level*.
1136
1137 If given, *logger* should be a :class:`logging.Logger` object or a
1138 :class:`str` giving the name of a logger. The default is the root
1139 logger, which will catch all messages.
1140
1141 If given, *level* should be either a numeric logging level or
1142 its string equivalent (for example either ``"ERROR"`` or
1143 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`.
1144
1145 Unlike :meth:`assertLogs`, nothing will be returned by the context
1146 manager.
1147
1148 .. versionadded:: 3.10
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001149
Ezio Melotti4370b302010-11-03 20:39:14 +00001150 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001151
Ezio Melotti4370b302010-11-03 20:39:14 +00001152 +---------------------------------------+--------------------------------+--------------+
1153 | Method | Checks that | New in |
1154 +=======================================+================================+==============+
1155 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1156 | <TestCase.assertAlmostEqual>` | | |
1157 +---------------------------------------+--------------------------------+--------------+
1158 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1159 | <TestCase.assertNotAlmostEqual>` | | |
1160 +---------------------------------------+--------------------------------+--------------+
1161 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1162 | <TestCase.assertGreater>` | | |
1163 +---------------------------------------+--------------------------------+--------------+
1164 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1165 | <TestCase.assertGreaterEqual>` | | |
1166 +---------------------------------------+--------------------------------+--------------+
1167 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1168 | <TestCase.assertLess>` | | |
1169 +---------------------------------------+--------------------------------+--------------+
1170 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1171 | <TestCase.assertLessEqual>` | | |
1172 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001173 | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001174 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001175 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001176 | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001177 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001178 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001179 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001180 | <TestCase.assertCountEqual>` | elements in the same number, | |
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001181 | | regardless of their order. | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001182 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001183
1184
Michael Foorde180d392011-01-28 19:51:48 +00001185 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1186 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001187
Michael Foorde180d392011-01-28 19:51:48 +00001188 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001189 equal by computing the difference, rounding to the given number of
1190 decimal *places* (default 7), and comparing to zero. Note that these
1191 methods round the values to the given number of *decimal places* (i.e.
1192 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001193
Ezio Melotti4370b302010-11-03 20:39:14 +00001194 If *delta* is supplied instead of *places* then the difference
Ezio Melottid51914c2013-08-11 13:04:50 +03001195 between *first* and *second* must be less or equal to (or greater than) *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001196
Stéphane Wirtele483f022018-10-26 12:52:11 +02001197 Supplying both *delta* and *places* raises a :exc:`TypeError`.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001198
Ezio Melotti4370b302010-11-03 20:39:14 +00001199 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001200 :meth:`assertAlmostEqual` automatically considers almost equal objects
1201 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1202 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001203
Ezio Melotti4370b302010-11-03 20:39:14 +00001204
Michael Foorde180d392011-01-28 19:51:48 +00001205 .. method:: assertGreater(first, second, msg=None)
1206 assertGreaterEqual(first, second, msg=None)
1207 assertLess(first, second, msg=None)
1208 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001209
Michael Foorde180d392011-01-28 19:51:48 +00001210 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001211 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001212
1213 >>> self.assertGreaterEqual(3, 4)
1214 AssertionError: "3" unexpectedly not greater than or equal to "4"
1215
1216 .. versionadded:: 3.1
1217
1218
Ezio Melottied3a7d22010-12-01 02:32:32 +00001219 .. method:: assertRegex(text, regex, msg=None)
1220 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001221
Ezio Melottied3a7d22010-12-01 02:32:32 +00001222 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001223 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001224 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001225 may be a regular expression object or a string containing a regular
1226 expression suitable for use by :func:`re.search`.
1227
Georg Brandl419e3de2010-12-01 15:44:25 +00001228 .. versionadded:: 3.1
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001229 Added under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001230 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001231 The method ``assertRegexpMatches()`` has been renamed to
1232 :meth:`.assertRegex`.
1233 .. versionadded:: 3.2
1234 :meth:`.assertNotRegex`.
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001235 .. versionadded:: 3.5
1236 The name ``assertNotRegexpMatches`` is a deprecated alias
1237 for :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001238
1239
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001240 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001241
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001242 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001243 regardless of their order. When they don't, an error message listing the
1244 differences between the sequences will be generated.
1245
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001246 Duplicate elements are *not* ignored when comparing *first* and
1247 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001248 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001249 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001250 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001251
Ezio Melotti4370b302010-11-03 20:39:14 +00001252 .. versionadded:: 3.2
1253
Ezio Melotti4370b302010-11-03 20:39:14 +00001254
Ezio Melotti22170ed2010-11-20 09:57:27 +00001255 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001256
Ezio Melotti22170ed2010-11-20 09:57:27 +00001257 The :meth:`assertEqual` method dispatches the equality check for objects of
1258 the same type to different type-specific methods. These methods are already
1259 implemented for most of the built-in types, but it's also possible to
1260 register new methods using :meth:`addTypeEqualityFunc`:
1261
1262 .. method:: addTypeEqualityFunc(typeobj, function)
1263
1264 Registers a type-specific method called by :meth:`assertEqual` to check
1265 if two objects of exactly the same *typeobj* (not subclasses) compare
1266 equal. *function* must take two positional arguments and a third msg=None
1267 keyword argument just as :meth:`assertEqual` does. It must raise
1268 :data:`self.failureException(msg) <failureException>` when inequality
1269 between the first two parameters is detected -- possibly providing useful
1270 information and explaining the inequalities in details in the error
1271 message.
1272
1273 .. versionadded:: 3.1
1274
1275 The list of type-specific methods automatically used by
1276 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1277 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001278
1279 +-----------------------------------------+-----------------------------+--------------+
1280 | Method | Used to compare | New in |
1281 +=========================================+=============================+==============+
1282 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1283 | <TestCase.assertMultiLineEqual>` | | |
1284 +-----------------------------------------+-----------------------------+--------------+
1285 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1286 | <TestCase.assertSequenceEqual>` | | |
1287 +-----------------------------------------+-----------------------------+--------------+
1288 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1289 | <TestCase.assertListEqual>` | | |
1290 +-----------------------------------------+-----------------------------+--------------+
1291 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1292 | <TestCase.assertTupleEqual>` | | |
1293 +-----------------------------------------+-----------------------------+--------------+
1294 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1295 | <TestCase.assertSetEqual>` | | |
1296 +-----------------------------------------+-----------------------------+--------------+
1297 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1298 | <TestCase.assertDictEqual>` | | |
1299 +-----------------------------------------+-----------------------------+--------------+
1300
1301
1302
Michael Foorde180d392011-01-28 19:51:48 +00001303 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001304
Michael Foorde180d392011-01-28 19:51:48 +00001305 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001306 When not equal a diff of the two strings highlighting the differences
1307 will be included in the error message. This method is used by default
1308 when comparing strings with :meth:`assertEqual`.
1309
Ezio Melotti4370b302010-11-03 20:39:14 +00001310 .. versionadded:: 3.1
1311
1312
Michael Foorde180d392011-01-28 19:51:48 +00001313 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001314
1315 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001316 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001317 be raised. If the sequences are different an error message is
1318 constructed that shows the difference between the two.
1319
Ezio Melotti22170ed2010-11-20 09:57:27 +00001320 This method is not called directly by :meth:`assertEqual`, but
1321 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001322 :meth:`assertTupleEqual`.
1323
1324 .. versionadded:: 3.1
1325
1326
Michael Foorde180d392011-01-28 19:51:48 +00001327 .. method:: assertListEqual(first, second, msg=None)
1328 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001329
Ezio Melotti49ccd512012-08-29 17:50:42 +03001330 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001331 constructed that shows only the differences between the two. An error
1332 is also raised if either of the parameters are of the wrong type.
1333 These methods are used by default when comparing lists or tuples with
1334 :meth:`assertEqual`.
1335
Ezio Melotti4370b302010-11-03 20:39:14 +00001336 .. versionadded:: 3.1
1337
1338
Michael Foorde180d392011-01-28 19:51:48 +00001339 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001340
1341 Tests that two sets are equal. If not, an error message is constructed
1342 that lists the differences between the sets. This method is used by
1343 default when comparing sets or frozensets with :meth:`assertEqual`.
1344
Michael Foorde180d392011-01-28 19:51:48 +00001345 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001346 method.
1347
Ezio Melotti4370b302010-11-03 20:39:14 +00001348 .. versionadded:: 3.1
1349
1350
Michael Foorde180d392011-01-28 19:51:48 +00001351 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001352
1353 Test that two dictionaries are equal. If not, an error message is
1354 constructed that shows the differences in the dictionaries. This
1355 method will be used by default to compare dictionaries in
1356 calls to :meth:`assertEqual`.
1357
Ezio Melotti4370b302010-11-03 20:39:14 +00001358 .. versionadded:: 3.1
1359
1360
1361
Ezio Melotti22170ed2010-11-20 09:57:27 +00001362 .. _other-methods-and-attrs:
1363
Ezio Melotti4370b302010-11-03 20:39:14 +00001364 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001365
Benjamin Peterson52baa292009-03-24 00:56:30 +00001366
Georg Brandl7f01a132009-09-16 15:58:14 +00001367 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001368
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001369 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001370 the error message.
1371
1372
1373 .. attribute:: failureException
1374
1375 This class attribute gives the exception raised by the test method. If a
1376 test framework needs to use a specialized exception, possibly to carry
1377 additional information, it must subclass this exception in order to "play
1378 fair" with the framework. The initial value of this attribute is
1379 :exc:`AssertionError`.
1380
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001381
1382 .. attribute:: longMessage
1383
Guido van Rossum4a452352016-10-13 14:23:01 -07001384 This class attribute determines what happens when a custom failure message
1385 is passed as the msg argument to an assertXYY call that fails.
1386 ``True`` is the default value. In this case, the custom message is appended
1387 to the end of the standard failure message.
1388 When set to ``False``, the custom message replaces the standard message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001389
Guido van Rossum4a452352016-10-13 14:23:01 -07001390 The class setting can be overridden in individual test methods by assigning
1391 an instance attribute, self.longMessage, to ``True`` or ``False`` before
1392 calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001393
Guido van Rossum4a452352016-10-13 14:23:01 -07001394 The class setting gets reset before each test call.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001395
Raymond Hettinger35a88362009-04-09 00:08:24 +00001396 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001397
1398
Michael Foord98b3e762010-06-05 21:59:55 +00001399 .. attribute:: maxDiff
1400
1401 This attribute controls the maximum length of diffs output by assert
1402 methods that report diffs on failure. It defaults to 80*8 characters.
1403 Assert methods affected by this attribute are
1404 :meth:`assertSequenceEqual` (including all the sequence comparison
1405 methods that delegate to it), :meth:`assertDictEqual` and
1406 :meth:`assertMultiLineEqual`.
1407
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001408 Setting ``maxDiff`` to ``None`` means that there is no maximum length of
Michael Foord98b3e762010-06-05 21:59:55 +00001409 diffs.
1410
1411 .. versionadded:: 3.2
1412
1413
Benjamin Peterson52baa292009-03-24 00:56:30 +00001414 Testing frameworks can use the following methods to collect information on
1415 the test:
1416
1417
1418 .. method:: countTestCases()
1419
1420 Return the number of tests represented by this test object. For
1421 :class:`TestCase` instances, this will always be ``1``.
1422
1423
1424 .. method:: defaultTestResult()
1425
1426 Return an instance of the test result class that should be used for this
1427 test case class (if no other result instance is provided to the
1428 :meth:`run` method).
1429
1430 For :class:`TestCase` instances, this will always be an instance of
1431 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1432 as necessary.
1433
1434
1435 .. method:: id()
1436
1437 Return a string identifying the specific test case. This is usually the
1438 full name of the test method, including the module and class name.
1439
1440
1441 .. method:: shortDescription()
1442
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001443 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001444 has been provided. The default implementation of this method
1445 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001446 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001447
Georg Brandl419e3de2010-12-01 15:44:25 +00001448 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001449 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001450 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001451 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001452 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001453
Georg Brandl116aa622007-08-15 14:28:22 +00001454
Serhiy Storchaka142566c2019-06-05 18:22:31 +03001455 .. method:: addCleanup(function, /, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001456
1457 Add a function to be called after :meth:`tearDown` to cleanup resources
1458 used during the test. Functions will be called in reverse order to the
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +03001459 order they are added (:abbr:`LIFO (last-in, first-out)`). They
1460 are called with any arguments and keyword arguments passed into
1461 :meth:`addCleanup` when they are added.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001462
1463 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1464 then any cleanup functions added will still be called.
1465
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001466 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001467
1468
1469 .. method:: doCleanups()
1470
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001471 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001472 after :meth:`setUp` if :meth:`setUp` raises an exception.
1473
1474 It is responsible for calling all the cleanup functions added by
1475 :meth:`addCleanup`. If you need cleanup functions to be called
1476 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1477 yourself.
1478
1479 :meth:`doCleanups` pops methods off the stack of cleanup
1480 functions one at a time, so it can be called at any time.
1481
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001482 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001483
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001484 .. classmethod:: addClassCleanup(function, /, *args, **kwargs)
Lisa Roach0f221d02018-11-08 18:34:33 -08001485
1486 Add a function to be called after :meth:`tearDownClass` to cleanup
1487 resources used during the test class. Functions will be called in reverse
1488 order to the order they are added (:abbr:`LIFO (last-in, first-out)`).
1489 They are called with any arguments and keyword arguments passed into
1490 :meth:`addClassCleanup` when they are added.
1491
1492 If :meth:`setUpClass` fails, meaning that :meth:`tearDownClass` is not
1493 called, then any cleanup functions added will still be called.
1494
1495 .. versionadded:: 3.8
1496
1497
1498 .. classmethod:: doClassCleanups()
1499
1500 This method is called unconditionally after :meth:`tearDownClass`, or
1501 after :meth:`setUpClass` if :meth:`setUpClass` raises an exception.
1502
1503 It is responsible for calling all the cleanup functions added by
Conchylicultore0e398e2021-01-20 14:08:37 +01001504 :meth:`addClassCleanup`. If you need cleanup functions to be called
Lisa Roach0f221d02018-11-08 18:34:33 -08001505 *prior* to :meth:`tearDownClass` then you can call
Conchylicultore0e398e2021-01-20 14:08:37 +01001506 :meth:`doClassCleanups` yourself.
Lisa Roach0f221d02018-11-08 18:34:33 -08001507
Conchylicultore0e398e2021-01-20 14:08:37 +01001508 :meth:`doClassCleanups` pops methods off the stack of cleanup
Lisa Roach0f221d02018-11-08 18:34:33 -08001509 functions one at a time, so it can be called at any time.
1510
1511 .. versionadded:: 3.8
1512
1513
Xtreak6a9fd662019-09-11 12:02:14 +01001514.. class:: IsolatedAsyncioTestCase(methodName='runTest')
1515
1516 This class provides an API similar to :class:`TestCase` and also accepts
1517 coroutines as test functions.
1518
1519 .. versionadded:: 3.8
1520
1521 .. coroutinemethod:: asyncSetUp()
1522
1523 Method called to prepare the test fixture. This is called after :meth:`setUp`.
1524 This is called immediately before calling the test method; other than
1525 :exc:`AssertionError` or :exc:`SkipTest`, any exception raised by this method
1526 will be considered an error rather than a test failure. The default implementation
1527 does nothing.
1528
1529 .. coroutinemethod:: asyncTearDown()
1530
1531 Method called immediately after the test method has been called and the
1532 result recorded. This is called before :meth:`tearDown`. This is called even if
1533 the test method raised an exception, so the implementation in subclasses may need
1534 to be particularly careful about checking internal state. Any exception, other than
1535 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
1536 considered an additional error rather than a test failure (thus increasing
1537 the total number of reported errors). This method will only be called if
1538 the :meth:`asyncSetUp` succeeds, regardless of the outcome of the test method.
1539 The default implementation does nothing.
1540
1541 .. method:: addAsyncCleanup(function, /, *args, **kwargs)
1542
1543 This method accepts a coroutine that can be used as a cleanup function.
1544
1545 .. method:: run(result=None)
1546
1547 Sets up a new event loop to run the test, collecting the result into
1548 the :class:`TestResult` object passed as *result*. If *result* is
1549 omitted or ``None``, a temporary result object is created (by calling
1550 the :meth:`defaultTestResult` method) and used. The result object is
1551 returned to :meth:`run`'s caller. At the end of the test all the tasks
1552 in the event loop are cancelled.
Lisa Roach0f221d02018-11-08 18:34:33 -08001553
1554
Xtreak6a9fd662019-09-11 12:02:14 +01001555 An example illustrating the order::
1556
1557 from unittest import IsolatedAsyncioTestCase
1558
1559 events = []
1560
1561
1562 class Test(IsolatedAsyncioTestCase):
1563
1564
1565 def setUp(self):
1566 events.append("setUp")
1567
1568 async def asyncSetUp(self):
1569 self._async_connection = await AsyncConnection()
1570 events.append("asyncSetUp")
1571
1572 async def test_response(self):
1573 events.append("test_response")
1574 response = await self._async_connection.get("https://example.com")
1575 self.assertEqual(response.status_code, 200)
1576 self.addAsyncCleanup(self.on_cleanup)
1577
1578 def tearDown(self):
1579 events.append("tearDown")
1580
1581 async def asyncTearDown(self):
1582 await self._async_connection.close()
1583 events.append("asyncTearDown")
1584
1585 async def on_cleanup(self):
1586 events.append("cleanup")
1587
1588 if __name__ == "__main__":
1589 unittest.main()
1590
Jules Lasne (jlasne)b1f160a2019-11-19 13:05:45 +01001591 After running the test, ``events`` would contain ``["setUp", "asyncSetUp", "test_response", "asyncTearDown", "tearDown", "cleanup"]``.
Lisa Roach0f221d02018-11-08 18:34:33 -08001592
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001593
Georg Brandl7f01a132009-09-16 15:58:14 +00001594.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001595
1596 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001597 allows the test runner to drive the test, but does not provide the methods
1598 which test code can use to check and report errors. This is used to create
1599 test cases using legacy test code, allowing it to be integrated into a
1600 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001601
1602
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001603.. _deprecated-aliases:
1604
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001605Deprecated aliases
1606##################
1607
1608For historical reasons, some of the :class:`TestCase` methods had one or more
1609aliases that are now deprecated. The following table lists the correct names
1610along with their deprecated aliases:
1611
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001612 ============================== ====================== =======================
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001613 Method Name Deprecated alias Deprecated alias
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001614 ============================== ====================== =======================
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001615 :meth:`.assertEqual` failUnlessEqual assertEquals
1616 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1617 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001618 :meth:`.assertFalse` failIf
1619 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001620 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1621 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001622 :meth:`.assertRegex` assertRegexpMatches
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001623 :meth:`.assertNotRegex` assertNotRegexpMatches
Ezio Melottied3a7d22010-12-01 02:32:32 +00001624 :meth:`.assertRaisesRegex` assertRaisesRegexp
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001625 ============================== ====================== =======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001626
Ezio Melotti361467e2011-04-03 17:37:58 +03001627 .. deprecated:: 3.1
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001628 The fail* aliases listed in the second column have been deprecated.
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001629 .. deprecated:: 3.2
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001630 The assert* aliases listed in the third column have been deprecated.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001631 .. deprecated:: 3.2
1632 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001633 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`.
1634 .. deprecated:: 3.5
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001635 The ``assertNotRegexpMatches`` name is deprecated in favor of :meth:`.assertNotRegex`.
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001636
Benjamin Peterson52baa292009-03-24 00:56:30 +00001637.. _testsuite-objects:
1638
Benjamin Peterson52baa292009-03-24 00:56:30 +00001639Grouping tests
1640~~~~~~~~~~~~~~
1641
Georg Brandl7f01a132009-09-16 15:58:14 +00001642.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001643
Martin Panter37f183d2017-01-18 12:06:38 +00001644 This class represents an aggregation of individual test cases and test suites.
Georg Brandl116aa622007-08-15 14:28:22 +00001645 The class presents the interface needed by the test runner to allow it to be run
1646 as any other test case. Running a :class:`TestSuite` instance is the same as
1647 iterating over the suite, running each test individually.
1648
1649 If *tests* is given, it must be an iterable of individual test cases or other
1650 test suites that will be used to build the suite initially. Additional methods
1651 are provided to add test cases and suites to the collection later on.
1652
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001653 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1654 they do not actually implement a test. Instead, they are used to aggregate
1655 tests into groups of tests that should be run together. Some additional
1656 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001657
1658
1659 .. method:: TestSuite.addTest(test)
1660
1661 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1662
1663
1664 .. method:: TestSuite.addTests(tests)
1665
1666 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1667 instances to this test suite.
1668
Benjamin Petersond2397752009-06-27 23:45:02 +00001669 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1670 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001671
1672 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1673
1674
1675 .. method:: run(result)
1676
1677 Run the tests associated with this suite, collecting the result into the
1678 test result object passed as *result*. Note that unlike
1679 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1680 be passed in.
1681
1682
1683 .. method:: debug()
1684
1685 Run the tests associated with this suite without collecting the
1686 result. This allows exceptions raised by the test to be propagated to the
1687 caller and can be used to support running tests under a debugger.
1688
1689
1690 .. method:: countTestCases()
1691
1692 Return the number of tests represented by this test object, including all
1693 individual tests and sub-suites.
1694
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001695
1696 .. method:: __iter__()
1697
1698 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1699 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
Andrew Svetloveb973682013-08-28 21:28:38 +03001700 that this method may be called several times on a single suite (for
1701 example when counting tests or comparing for equality) so the tests
1702 returned by repeated iterations before :meth:`TestSuite.run` must be the
1703 same for each call iteration. After :meth:`TestSuite.run`, callers should
1704 not rely on the tests returned by this method unless the caller uses a
1705 subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
1706 test references.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001707
Georg Brandl853947a2010-01-31 18:53:23 +00001708 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001709 In earlier versions the :class:`TestSuite` accessed tests directly rather
1710 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1711 for providing tests.
1712
Andrew Svetloveb973682013-08-28 21:28:38 +03001713 .. versionchanged:: 3.4
1714 In earlier versions the :class:`TestSuite` held references to each
1715 :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
1716 that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
1717
Benjamin Peterson52baa292009-03-24 00:56:30 +00001718 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1719 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1720
1721
Benjamin Peterson52baa292009-03-24 00:56:30 +00001722Loading and running tests
1723~~~~~~~~~~~~~~~~~~~~~~~~~
1724
Georg Brandl116aa622007-08-15 14:28:22 +00001725.. class:: TestLoader()
1726
Benjamin Peterson52baa292009-03-24 00:56:30 +00001727 The :class:`TestLoader` class is used to create test suites from classes and
1728 modules. Normally, there is no need to create an instance of this class; the
1729 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001730 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1731 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001732
Robert Collinsf920c212014-10-20 13:24:05 +13001733 :class:`TestLoader` objects have the following attributes:
1734
1735
1736 .. attribute:: errors
1737
1738 A list of the non-fatal errors encountered while loading tests. Not reset
1739 by the loader at any point. Fatal errors are signalled by the relevant
1740 a method raising an exception to the caller. Non-fatal errors are also
1741 indicated by a synthetic test that will raise the original error when
1742 run.
1743
1744 .. versionadded:: 3.5
1745
1746
Benjamin Peterson52baa292009-03-24 00:56:30 +00001747 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001748
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001749
Benjamin Peterson52baa292009-03-24 00:56:30 +00001750 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001751
Martin Panter37f183d2017-01-18 12:06:38 +00001752 Return a suite of all test cases contained in the :class:`TestCase`\ -derived
Benjamin Peterson52baa292009-03-24 00:56:30 +00001753 :class:`testCaseClass`.
1754
Robert Collinse02f6c22015-07-23 06:37:26 +12001755 A test case instance is created for each method named by
1756 :meth:`getTestCaseNames`. By default these are the method names
1757 beginning with ``test``. If :meth:`getTestCaseNames` returns no
1758 methods, but the :meth:`runTest` method is implemented, a single test
1759 case is created for that method instead.
1760
Benjamin Peterson52baa292009-03-24 00:56:30 +00001761
Barry Warsawd78742a2014-09-08 14:21:37 -04001762 .. method:: loadTestsFromModule(module, pattern=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001763
Martin Panter37f183d2017-01-18 12:06:38 +00001764 Return a suite of all test cases contained in the given module. This
Benjamin Peterson52baa292009-03-24 00:56:30 +00001765 method searches *module* for classes derived from :class:`TestCase` and
1766 creates an instance of the class for each test method defined for the
1767 class.
1768
Georg Brandle720c0a2009-04-27 16:20:50 +00001769 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001770
1771 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1772 convenient in sharing fixtures and helper functions, defining test
1773 methods on base classes that are not intended to be instantiated
1774 directly does not play well with this method. Doing so, however, can
1775 be useful when the fixtures are different and defined in subclasses.
1776
Benjamin Petersond2397752009-06-27 23:45:02 +00001777 If a module provides a ``load_tests`` function it will be called to
1778 load the tests. This allows modules to customize test loading.
Barry Warsawd78742a2014-09-08 14:21:37 -04001779 This is the `load_tests protocol`_. The *pattern* argument is passed as
1780 the third argument to ``load_tests``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001781
Georg Brandl853947a2010-01-31 18:53:23 +00001782 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001783 Support for ``load_tests`` added.
1784
Barry Warsawd78742a2014-09-08 14:21:37 -04001785 .. versionchanged:: 3.5
1786 The undocumented and unofficial *use_load_tests* default argument is
1787 deprecated and ignored, although it is still accepted for backward
1788 compatibility. The method also now accepts a keyword-only argument
1789 *pattern* which is passed to ``load_tests`` as the third argument.
1790
Benjamin Peterson52baa292009-03-24 00:56:30 +00001791
Georg Brandl7f01a132009-09-16 15:58:14 +00001792 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001793
Martin Panter37f183d2017-01-18 12:06:38 +00001794 Return a suite of all test cases given a string specifier.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001795
1796 The specifier *name* is a "dotted name" that may resolve either to a
1797 module, a test case class, a test method within a test case class, a
1798 :class:`TestSuite` instance, or a callable object which returns a
1799 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1800 applied in the order listed here; that is, a method on a possible test
1801 case class will be picked up as "a test method within a test case class",
1802 rather than "a callable object".
1803
1804 For example, if you have a module :mod:`SampleTests` containing a
1805 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1806 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001807 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1808 return a suite which will run all three test methods. Using the specifier
1809 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1810 suite which will run only the :meth:`test_two` test method. The specifier
1811 can refer to modules and packages which have not been imported; they will
1812 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001813
1814 The method optionally resolves *name* relative to the given *module*.
1815
Martin Panter536d70e2017-01-14 08:23:08 +00001816 .. versionchanged:: 3.5
1817 If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing
1818 *name* then a synthetic test that raises that error when run will be
1819 returned. These errors are included in the errors accumulated by
1820 self.errors.
Robert Collins659dd622014-10-30 08:27:27 +13001821
Benjamin Peterson52baa292009-03-24 00:56:30 +00001822
Georg Brandl7f01a132009-09-16 15:58:14 +00001823 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001824
1825 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1826 than a single name. The return value is a test suite which supports all
1827 the tests defined for each name.
1828
1829
1830 .. method:: getTestCaseNames(testCaseClass)
1831
1832 Return a sorted sequence of method names found within *testCaseClass*;
1833 this should be a subclass of :class:`TestCase`.
1834
Benjamin Petersond2397752009-06-27 23:45:02 +00001835
1836 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1837
Larry Hastings3732ed22014-03-15 21:13:56 -07001838 Find all the test modules by recursing into subdirectories from the
1839 specified start directory, and return a TestSuite object containing them.
1840 Only test files that match *pattern* will be loaded. (Using shell style
1841 pattern matching.) Only module names that are importable (i.e. are valid
1842 Python identifiers) will be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001843
1844 All test modules must be importable from the top level of the project. If
1845 the start directory is not the top level directory then the top level
1846 directory must be specified separately.
1847
Barry Warsawd78742a2014-09-08 14:21:37 -04001848 If importing a module fails, for example due to a syntax error, then
1849 this will be recorded as a single error and discovery will continue. If
1850 the import failure is due to :exc:`SkipTest` being raised, it will be
1851 recorded as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001852
Barry Warsawd78742a2014-09-08 14:21:37 -04001853 If a package (a directory containing a file named :file:`__init__.py`) is
1854 found, the package will be checked for a ``load_tests`` function. If this
Robert Collinsbf2bda32014-11-05 03:09:01 +13001855 exists then it will be called
1856 ``package.load_tests(loader, tests, pattern)``. Test discovery takes care
1857 to ensure that a package is only checked for tests once during an
1858 invocation, even if the load_tests function itself calls
1859 ``loader.discover``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001860
Barry Warsawd78742a2014-09-08 14:21:37 -04001861 If ``load_tests`` exists then discovery does *not* recurse into the
1862 package, ``load_tests`` is responsible for loading all tests in the
1863 package.
Benjamin Petersond2397752009-06-27 23:45:02 +00001864
1865 The pattern is deliberately not stored as a loader attribute so that
1866 packages can continue discovery themselves. *top_level_dir* is stored so
1867 ``load_tests`` does not need to pass this argument in to
1868 ``loader.discover()``.
1869
Benjamin Petersonb48af542010-04-11 20:43:16 +00001870 *start_dir* can be a dotted module name as well as a directory.
1871
Georg Brandl853947a2010-01-31 18:53:23 +00001872 .. versionadded:: 3.2
1873
Ezio Melottieae2b382013-03-01 14:47:50 +02001874 .. versionchanged:: 3.4
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001875 Modules that raise :exc:`SkipTest` on import are recorded as skips,
Inada Naoki5a4aa4c2021-02-22 15:14:26 +09001876 not errors.
1877
1878 .. versionchanged:: 3.4
1879 *start_dir* can be a :term:`namespace packages <namespace package>`.
1880
1881 .. versionchanged:: 3.4
1882 Paths are sorted before being imported so that execution order is the
1883 same even if the underlying file system's ordering is not dependent
1884 on file name.
Michael Foord80cbc9e2013-03-18 17:50:12 -07001885
Barry Warsawd78742a2014-09-08 14:21:37 -04001886 .. versionchanged:: 3.5
1887 Found packages are now checked for ``load_tests`` regardless of
1888 whether their path matches *pattern*, because it is impossible for
1889 a package name to match the default pattern.
1890
Benjamin Petersond2397752009-06-27 23:45:02 +00001891
Benjamin Peterson52baa292009-03-24 00:56:30 +00001892 The following attributes of a :class:`TestLoader` can be configured either by
1893 subclassing or assignment on an instance:
1894
1895
1896 .. attribute:: testMethodPrefix
1897
1898 String giving the prefix of method names which will be interpreted as test
1899 methods. The default value is ``'test'``.
1900
1901 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1902 methods.
1903
1904
1905 .. attribute:: sortTestMethodsUsing
1906
1907 Function to be used to compare method names when sorting them in
1908 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1909
1910
1911 .. attribute:: suiteClass
1912
1913 Callable object that constructs a test suite from a list of tests. No
1914 methods on the resulting object are needed. The default value is the
1915 :class:`TestSuite` class.
1916
1917 This affects all the :meth:`loadTestsFrom\*` methods.
1918
Jonas Haag5b48dc62017-11-25 16:23:52 +01001919 .. attribute:: testNamePatterns
1920
1921 List of Unix shell-style wildcard test name patterns that test methods
1922 have to match to be included in test suites (see ``-v`` option).
1923
1924 If this attribute is not ``None`` (the default), all test methods to be
1925 included in test suites must match one of the patterns in this list.
1926 Note that matches are always performed using :meth:`fnmatch.fnmatchcase`,
1927 so unlike patterns passed to the ``-v`` option, simple substring patterns
1928 will have to be converted using ``*`` wildcards.
1929
1930 This affects all the :meth:`loadTestsFrom\*` methods.
1931
1932 .. versionadded:: 3.7
1933
Benjamin Peterson52baa292009-03-24 00:56:30 +00001934
Benjamin Peterson52baa292009-03-24 00:56:30 +00001935.. class:: TestResult
1936
1937 This class is used to compile information about which tests have succeeded
1938 and which have failed.
1939
1940 A :class:`TestResult` object stores the results of a set of tests. The
1941 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1942 properly recorded; test authors do not need to worry about recording the
1943 outcome of tests.
1944
1945 Testing frameworks built on top of :mod:`unittest` may want access to the
1946 :class:`TestResult` object generated by running a set of tests for reporting
1947 purposes; a :class:`TestResult` instance is returned by the
1948 :meth:`TestRunner.run` method for this purpose.
1949
1950 :class:`TestResult` instances have the following attributes that will be of
1951 interest when inspecting the results of running a set of tests:
1952
1953
1954 .. attribute:: errors
1955
1956 A list containing 2-tuples of :class:`TestCase` instances and strings
1957 holding formatted tracebacks. Each tuple represents a test which raised an
1958 unexpected exception.
1959
Benjamin Peterson52baa292009-03-24 00:56:30 +00001960 .. attribute:: failures
1961
1962 A list containing 2-tuples of :class:`TestCase` instances and strings
1963 holding formatted tracebacks. Each tuple represents a test where a failure
Ezio Melottie2202362013-09-07 15:19:30 +03001964 was explicitly signalled using the :meth:`TestCase.assert\*` methods.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001965
Benjamin Peterson52baa292009-03-24 00:56:30 +00001966 .. attribute:: skipped
1967
1968 A list containing 2-tuples of :class:`TestCase` instances and strings
1969 holding the reason for skipping the test.
1970
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001971 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001972
1973 .. attribute:: expectedFailures
1974
Georg Brandl6faee4e2010-09-21 14:48:28 +00001975 A list containing 2-tuples of :class:`TestCase` instances and strings
1976 holding formatted tracebacks. Each tuple represents an expected failure
Irit Katrielfa874822020-10-19 22:27:16 +01001977 or error of the test case.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001978
1979 .. attribute:: unexpectedSuccesses
1980
1981 A list containing :class:`TestCase` instances that were marked as expected
1982 failures, but succeeded.
1983
1984 .. attribute:: shouldStop
1985
1986 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1987
Benjamin Peterson52baa292009-03-24 00:56:30 +00001988 .. attribute:: testsRun
1989
1990 The total number of tests run so far.
1991
Georg Brandl12037202010-12-02 22:35:25 +00001992 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001993
1994 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1995 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1996 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1997 fails or errors. Any output is also attached to the failure / error message.
1998
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001999 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00002000
Benjamin Petersonb48af542010-04-11 20:43:16 +00002001 .. attribute:: failfast
2002
2003 If set to true :meth:`stop` will be called on the first failure or error,
2004 halting the test run.
2005
Ezio Melotti7afd3f52010-04-20 09:32:54 +00002006 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00002007
Robert Collinsf0c819a2015-03-06 13:46:35 +13002008 .. attribute:: tb_locals
2009
2010 If set to true then local variables will be shown in tracebacks.
2011
2012 .. versionadded:: 3.5
Benjamin Petersonb48af542010-04-11 20:43:16 +00002013
Benjamin Peterson52baa292009-03-24 00:56:30 +00002014 .. method:: wasSuccessful()
2015
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00002016 Return ``True`` if all tests run so far have passed, otherwise returns
2017 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00002018
Gregory P. Smith5a6d4bf2014-01-20 01:11:18 -08002019 .. versionchanged:: 3.4
2020 Returns ``False`` if there were any :attr:`unexpectedSuccesses`
2021 from tests marked with the :func:`expectedFailure` decorator.
2022
Benjamin Peterson52baa292009-03-24 00:56:30 +00002023 .. method:: stop()
2024
2025 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00002026 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00002027 :class:`TestRunner` objects should respect this flag and return without
2028 running any additional tests.
2029
2030 For example, this feature is used by the :class:`TextTestRunner` class to
2031 stop the test framework when the user signals an interrupt from the
2032 keyboard. Interactive tools which provide :class:`TestRunner`
2033 implementations can use this in a similar manner.
2034
2035 The following methods of the :class:`TestResult` class are used to maintain
2036 the internal data structures, and may be extended in subclasses to support
2037 additional reporting requirements. This is particularly useful in building
2038 tools which support interactive reporting while tests are being run.
2039
2040
2041 .. method:: startTest(test)
2042
2043 Called when the test case *test* is about to be run.
2044
Benjamin Peterson52baa292009-03-24 00:56:30 +00002045 .. method:: stopTest(test)
2046
2047 Called after the test case *test* has been executed, regardless of the
2048 outcome.
2049
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04002050 .. method:: startTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002051
2052 Called once before any tests are executed.
2053
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02002054 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002055
2056
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04002057 .. method:: stopTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002058
Ezio Melotti176d6c42010-01-27 20:58:07 +00002059 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002060
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02002061 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002062
2063
Benjamin Peterson52baa292009-03-24 00:56:30 +00002064 .. method:: addError(test, err)
2065
Ezio Melottie64a91a2013-09-07 15:23:36 +03002066 Called when the test case *test* raises an unexpected exception. *err* is a
Benjamin Peterson52baa292009-03-24 00:56:30 +00002067 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
2068 traceback)``.
2069
2070 The default implementation appends a tuple ``(test, formatted_err)`` to
2071 the instance's :attr:`errors` attribute, where *formatted_err* is a
2072 formatted traceback derived from *err*.
2073
2074
2075 .. method:: addFailure(test, err)
2076
Benjamin Petersond2397752009-06-27 23:45:02 +00002077 Called when the test case *test* signals a failure. *err* is a tuple of
2078 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00002079
2080 The default implementation appends a tuple ``(test, formatted_err)`` to
2081 the instance's :attr:`failures` attribute, where *formatted_err* is a
2082 formatted traceback derived from *err*.
2083
2084
2085 .. method:: addSuccess(test)
2086
2087 Called when the test case *test* succeeds.
2088
2089 The default implementation does nothing.
2090
2091
2092 .. method:: addSkip(test, reason)
2093
2094 Called when the test case *test* is skipped. *reason* is the reason the
2095 test gave for skipping.
2096
2097 The default implementation appends a tuple ``(test, reason)`` to the
2098 instance's :attr:`skipped` attribute.
2099
2100
2101 .. method:: addExpectedFailure(test, err)
2102
Irit Katrielfa874822020-10-19 22:27:16 +01002103 Called when the test case *test* fails or errors, but was marked with
2104 the :func:`expectedFailure` decorator.
Benjamin Peterson52baa292009-03-24 00:56:30 +00002105
2106 The default implementation appends a tuple ``(test, formatted_err)`` to
2107 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
2108 is a formatted traceback derived from *err*.
2109
2110
2111 .. method:: addUnexpectedSuccess(test)
2112
2113 Called when the test case *test* was marked with the
2114 :func:`expectedFailure` decorator, but succeeded.
2115
2116 The default implementation appends the test to the instance's
2117 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002118
Georg Brandl67b21b72010-08-17 15:07:14 +00002119
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01002120 .. method:: addSubTest(test, subtest, outcome)
2121
2122 Called when a subtest finishes. *test* is the test case
2123 corresponding to the test method. *subtest* is a custom
2124 :class:`TestCase` instance describing the subtest.
2125
2126 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
2127 it failed with an exception where *outcome* is a tuple of the form
2128 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
2129
2130 The default implementation does nothing when the outcome is a
2131 success, and records subtest failures as normal failures.
2132
2133 .. versionadded:: 3.4
2134
2135
Michael Foord34c94622010-02-10 15:51:42 +00002136.. class:: TextTestResult(stream, descriptions, verbosity)
2137
Georg Brandl67b21b72010-08-17 15:07:14 +00002138 A concrete implementation of :class:`TestResult` used by the
2139 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00002140
Georg Brandl67b21b72010-08-17 15:07:14 +00002141 .. versionadded:: 3.2
2142 This class was previously named ``_TextTestResult``. The old name still
2143 exists as an alias but is deprecated.
2144
Georg Brandl116aa622007-08-15 14:28:22 +00002145
2146.. data:: defaultTestLoader
2147
2148 Instance of the :class:`TestLoader` class intended to be shared. If no
2149 customization of the :class:`TestLoader` is needed, this instance can be used
2150 instead of repeatedly creating new instances.
2151
2152
Ezio Melotti9c939bc2013-05-07 09:46:30 +03002153.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \
Robert Collinsf0c819a2015-03-06 13:46:35 +13002154 buffer=False, resultclass=None, warnings=None, *, tb_locals=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002155
Michael Foordd218e952011-01-03 12:55:11 +00002156 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02002157 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00002158 has a few configurable parameters, but is essentially very simple. Graphical
Robert Collinsf0c819a2015-03-06 13:46:35 +13002159 applications which run test suites should provide alternate implementations. Such
2160 implementations should accept ``**kwargs`` as the interface to construct runners
2161 changes when features are added to unittest.
Georg Brandl116aa622007-08-15 14:28:22 +00002162
Ezio Melotti60901872010-12-01 00:56:10 +00002163 By default this runner shows :exc:`DeprecationWarning`,
Senthil Kumaran409ea5d2014-02-08 14:28:03 -08002164 :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and
Larry Hastingsad88d7a2014-02-10 04:26:10 -08002165 :exc:`ImportWarning` even if they are :ref:`ignored by default
2166 <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest
2167 methods <deprecated-aliases>` are also special-cased and, when the warning
2168 filters are ``'default'`` or ``'always'``, they will appear only once
2169 per-module, in order to avoid too many warning messages. This behavior can
Martin Panterb8c5f542016-10-30 04:20:23 +00002170 be overridden using Python's :option:`!-Wd` or :option:`!-Wa` options
2171 (see :ref:`Warning control <using-on-warnings>`) and leaving
Larry Hastingsad88d7a2014-02-10 04:26:10 -08002172 *warnings* to ``None``.
Ezio Melotti60901872010-12-01 00:56:10 +00002173
Michael Foordd218e952011-01-03 12:55:11 +00002174 .. versionchanged:: 3.2
2175 Added the ``warnings`` argument.
2176
2177 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02002178 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00002179 than import time.
2180
Robert Collinsf0c819a2015-03-06 13:46:35 +13002181 .. versionchanged:: 3.5
2182 Added the tb_locals parameter.
2183
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002184 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00002185
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002186 This method returns the instance of ``TestResult`` used by :meth:`run`.
2187 It is not intended to be called directly, but can be overridden in
2188 subclasses to provide a custom ``TestResult``.
2189
Michael Foord34c94622010-02-10 15:51:42 +00002190 ``_makeResult()`` instantiates the class or callable passed in the
2191 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00002192 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00002193 The result class is instantiated with the following arguments::
2194
2195 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002196
Michael Foord4d1639f2013-12-29 23:38:55 +00002197 .. method:: run(test)
2198
Julien Palard6e240dd2019-02-22 09:22:27 +01002199 This method is the main public interface to the ``TextTestRunner``. This
Michael Foord4d1639f2013-12-29 23:38:55 +00002200 method takes a :class:`TestSuite` or :class:`TestCase` instance. A
2201 :class:`TestResult` is created by calling
2202 :func:`_makeResult` and the test(s) are run and the
2203 results printed to stdout.
2204
Ezio Melotti60901872010-12-01 00:56:10 +00002205
Georg Brandl419e3de2010-12-01 15:44:25 +00002206.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02002207 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00002208 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002209
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002210 A command-line program that loads a set of tests from *module* and runs them;
2211 this is primarily for making test modules conveniently executable.
2212 The simplest use for this function is to include the following line at the
2213 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00002214
2215 if __name__ == '__main__':
2216 unittest.main()
2217
Benjamin Petersond2397752009-06-27 23:45:02 +00002218 You can run tests with more detailed information by passing in the verbosity
2219 argument::
2220
2221 if __name__ == '__main__':
2222 unittest.main(verbosity=2)
2223
R David Murray6e731b02014-01-02 13:43:02 -05002224 The *defaultTest* argument is either the name of a single test or an
2225 iterable of test names to run if no test names are specified via *argv*. If
2226 not specified or ``None`` and no test names are provided via *argv*, all
2227 tests found in *module* are run.
R David Murray12e930f2014-01-02 13:37:26 -05002228
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002229 The *argv* argument can be a list of options passed to the program, with the
2230 first element being the program name. If not specified or ``None``,
2231 the values of :data:`sys.argv` are used.
2232
Georg Brandl116aa622007-08-15 14:28:22 +00002233 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002234 created instance of it. By default ``main`` calls :func:`sys.exit` with
2235 an exit code indicating success or failure of the tests run.
2236
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002237 The *testLoader* argument has to be a :class:`TestLoader` instance,
2238 and defaults to :data:`defaultTestLoader`.
2239
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002240 ``main`` supports being used from the interactive interpreter by passing in the
2241 argument ``exit=False``. This displays the result on standard output without
2242 calling :func:`sys.exit`::
2243
2244 >>> from unittest import main
2245 >>> main(module='test_module', exit=False)
2246
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002247 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00002248 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002249
Zachary Waref0a71cf2016-08-30 00:16:13 -05002250 The *warnings* argument specifies the :ref:`warning filter <warning-filter>`
Ezio Melotti60901872010-12-01 00:56:10 +00002251 that should be used while running the tests. If it's not specified, it will
Martin Panterb8c5f542016-10-30 04:20:23 +00002252 remain ``None`` if a :option:`!-W` option is passed to :program:`python`
2253 (see :ref:`Warning control <using-on-warnings>`),
Ezio Melotti60901872010-12-01 00:56:10 +00002254 otherwise it will be set to ``'default'``.
2255
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002256 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
2257 This stores the result of the tests run as the ``result`` attribute.
2258
Éric Araujo971dc012010-12-16 03:13:05 +00002259 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002260 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00002261
Georg Brandl853947a2010-01-31 18:53:23 +00002262 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002263 The *verbosity*, *failfast*, *catchbreak*, *buffer*
2264 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00002265
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08002266 .. versionchanged:: 3.4
2267 The *defaultTest* parameter was changed to also accept an iterable of
2268 test names.
2269
Benjamin Petersond2397752009-06-27 23:45:02 +00002270
2271load_tests Protocol
2272###################
2273
Georg Brandl853947a2010-01-31 18:53:23 +00002274.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002275
Benjamin Petersond2397752009-06-27 23:45:02 +00002276Modules or packages can customize how tests are loaded from them during normal
2277test runs or test discovery by implementing a function called ``load_tests``.
2278
2279If a test module defines ``load_tests`` it will be called by
2280:meth:`TestLoader.loadTestsFromModule` with the following arguments::
2281
Barry Warsawd78742a2014-09-08 14:21:37 -04002282 load_tests(loader, standard_tests, pattern)
2283
2284where *pattern* is passed straight through from ``loadTestsFromModule``. It
2285defaults to ``None``.
Benjamin Petersond2397752009-06-27 23:45:02 +00002286
2287It should return a :class:`TestSuite`.
2288
2289*loader* is the instance of :class:`TestLoader` doing the loading.
2290*standard_tests* are the tests that would be loaded by default from the
2291module. It is common for test modules to only want to add or remove tests
2292from the standard set of tests.
2293The third argument is used when loading packages as part of test discovery.
2294
2295A typical ``load_tests`` function that loads tests from a specific set of
2296:class:`TestCase` classes may look like::
2297
2298 test_cases = (TestCase1, TestCase2, TestCase3)
2299
2300 def load_tests(loader, tests, pattern):
2301 suite = TestSuite()
2302 for test_class in test_cases:
2303 tests = loader.loadTestsFromTestCase(test_class)
2304 suite.addTests(tests)
2305 return suite
2306
Barry Warsawd78742a2014-09-08 14:21:37 -04002307If discovery is started in a directory containing a package, either from the
2308command line or by calling :meth:`TestLoader.discover`, then the package
2309:file:`__init__.py` will be checked for ``load_tests``. If that function does
2310not exist, discovery will recurse into the package as though it were just
2311another directory. Otherwise, discovery of the package's tests will be left up
2312to ``load_tests`` which is called with the following arguments::
Benjamin Petersond2397752009-06-27 23:45:02 +00002313
2314 load_tests(loader, standard_tests, pattern)
2315
2316This should return a :class:`TestSuite` representing all the tests
2317from the package. (``standard_tests`` will only contain tests
2318collected from :file:`__init__.py`.)
2319
2320Because the pattern is passed into ``load_tests`` the package is free to
2321continue (and potentially modify) test discovery. A 'do nothing'
2322``load_tests`` function for a test package would look like::
2323
2324 def load_tests(loader, standard_tests, pattern):
2325 # top level directory cached on loader instance
2326 this_dir = os.path.dirname(__file__)
2327 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2328 standard_tests.addTests(package_tests)
2329 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002330
Barry Warsawd78742a2014-09-08 14:21:37 -04002331.. versionchanged:: 3.5
2332 Discovery no longer checks package names for matching *pattern* due to the
2333 impossibility of package names matching the default pattern.
2334
2335
Benjamin Petersonb48af542010-04-11 20:43:16 +00002336
2337Class and Module Fixtures
2338-------------------------
2339
2340Class and module level fixtures are implemented in :class:`TestSuite`. When
2341the test suite encounters a test from a new class then :meth:`tearDownClass`
2342from the previous class (if there is one) is called, followed by
2343:meth:`setUpClass` from the new class.
2344
2345Similarly if a test is from a different module from the previous test then
2346``tearDownModule`` from the previous module is run, followed by
2347``setUpModule`` from the new module.
2348
2349After all the tests have run the final ``tearDownClass`` and
2350``tearDownModule`` are run.
2351
2352Note that shared fixtures do not play well with [potential] features like test
2353parallelization and they break test isolation. They should be used with care.
2354
2355The default ordering of tests created by the unittest test loaders is to group
2356all tests from the same modules and classes together. This will lead to
2357``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2358module. If you randomize the order, so that tests from different modules and
2359classes are adjacent to each other, then these shared fixture functions may be
2360called multiple times in a single test run.
2361
2362Shared fixtures are not intended to work with suites with non-standard
2363ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2364support shared fixtures.
2365
2366If there are any exceptions raised during one of the shared fixture functions
2367the test is reported as an error. Because there is no corresponding test
2368instance an ``_ErrorHolder`` object (that has the same interface as a
2369:class:`TestCase`) is created to represent the error. If you are just using
2370the standard unittest test runner then this detail doesn't matter, but if you
2371are a framework author it may be relevant.
2372
2373
2374setUpClass and tearDownClass
2375~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2376
2377These must be implemented as class methods::
2378
2379 import unittest
2380
2381 class Test(unittest.TestCase):
2382 @classmethod
2383 def setUpClass(cls):
2384 cls._connection = createExpensiveConnectionObject()
2385
2386 @classmethod
2387 def tearDownClass(cls):
2388 cls._connection.destroy()
2389
2390If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2391then you must call up to them yourself. The implementations in
2392:class:`TestCase` are empty.
2393
2394If an exception is raised during a ``setUpClass`` then the tests in the class
2395are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002396have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002397:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002398instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002399
2400
2401setUpModule and tearDownModule
2402~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2403
2404These should be implemented as functions::
2405
2406 def setUpModule():
2407 createConnection()
2408
2409 def tearDownModule():
2410 closeConnection()
2411
2412If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002413module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002414:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002415instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002416
Lisa Roach0f221d02018-11-08 18:34:33 -08002417To add cleanup code that must be run even in the case of an exception, use
2418``addModuleCleanup``:
2419
2420
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002421.. function:: addModuleCleanup(function, /, *args, **kwargs)
Lisa Roach0f221d02018-11-08 18:34:33 -08002422
2423 Add a function to be called after :func:`tearDownModule` to cleanup
2424 resources used during the test class. Functions will be called in reverse
2425 order to the order they are added (:abbr:`LIFO (last-in, first-out)`).
2426 They are called with any arguments and keyword arguments passed into
2427 :meth:`addModuleCleanup` when they are added.
2428
2429 If :meth:`setUpModule` fails, meaning that :func:`tearDownModule` is not
2430 called, then any cleanup functions added will still be called.
2431
2432 .. versionadded:: 3.8
2433
2434
2435.. function:: doModuleCleanups()
2436
2437 This function is called unconditionally after :func:`tearDownModule`, or
2438 after :func:`setUpModule` if :func:`setUpModule` raises an exception.
2439
2440 It is responsible for calling all the cleanup functions added by
2441 :func:`addCleanupModule`. If you need cleanup functions to be called
2442 *prior* to :func:`tearDownModule` then you can call
2443 :func:`doModuleCleanups` yourself.
2444
2445 :func:`doModuleCleanups` pops methods off the stack of cleanup
2446 functions one at a time, so it can be called at any time.
2447
2448 .. versionadded:: 3.8
Benjamin Petersonb48af542010-04-11 20:43:16 +00002449
2450Signal Handling
2451---------------
2452
Georg Brandl419e3de2010-12-01 15:44:25 +00002453.. versionadded:: 3.2
2454
Éric Araujo8acb67c2010-11-26 23:31:07 +00002455The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002456along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2457more friendly handling of control-C during a test run. With catch break
2458behavior enabled control-C will allow the currently running test to complete,
2459and the test run will then end and report all the results so far. A second
2460control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002461
Michael Foordde4ceab2010-04-25 19:53:49 +00002462The control-c handling signal handler attempts to remain compatible with code or
2463tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2464handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2465i.e. it has been replaced by the system under test and delegated to, then it
2466calls the default handler. This will normally be the expected behavior by code
2467that replaces an installed handler and delegates to it. For individual tests
2468that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2469decorator can be used.
2470
2471There are a few utility functions for framework authors to enable control-c
2472handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002473
2474.. function:: installHandler()
2475
2476 Install the control-c handler. When a :const:`signal.SIGINT` is received
2477 (usually in response to the user pressing control-c) all registered results
2478 have :meth:`~TestResult.stop` called.
2479
Michael Foord469b1f02010-04-26 23:41:26 +00002480
Benjamin Petersonb48af542010-04-11 20:43:16 +00002481.. function:: registerResult(result)
2482
2483 Register a :class:`TestResult` object for control-c handling. Registering a
2484 result stores a weak reference to it, so it doesn't prevent the result from
2485 being garbage collected.
2486
Michael Foordde4ceab2010-04-25 19:53:49 +00002487 Registering a :class:`TestResult` object has no side-effects if control-c
2488 handling is not enabled, so test frameworks can unconditionally register
2489 all results they create independently of whether or not handling is enabled.
2490
Michael Foord469b1f02010-04-26 23:41:26 +00002491
Benjamin Petersonb48af542010-04-11 20:43:16 +00002492.. function:: removeResult(result)
2493
2494 Remove a registered result. Once a result has been removed then
2495 :meth:`~TestResult.stop` will no longer be called on that result object in
2496 response to a control-c.
2497
Michael Foord469b1f02010-04-26 23:41:26 +00002498
Michael Foordde4ceab2010-04-25 19:53:49 +00002499.. function:: removeHandler(function=None)
2500
2501 When called without arguments this function removes the control-c handler
2502 if it has been installed. This function can also be used as a test decorator
Mariatta98f42aa2018-02-23 09:51:11 -08002503 to temporarily remove the handler while the test is being executed::
Michael Foordde4ceab2010-04-25 19:53:49 +00002504
2505 @unittest.removeHandler
2506 def test_signal_handling(self):
2507 ...