blob: 0dddbd25d991b5500132f5c4f453221014da19f0 [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/>`_
Senthil Kumaran847c33c2012-10-27 11:04:55 -070076 or `Hudson <http://hudson-ci.org/>`_.
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
333 Test discovery supports :term:`namespace packages <namespace package>`.
334
Benjamin Petersonb48af542010-04-11 20:43:16 +0000335
Georg Brandl116aa622007-08-15 14:28:22 +0000336.. _organizing-tests:
337
338Organizing test code
339--------------------
340
341The basic building blocks of unit testing are :dfn:`test cases` --- single
342scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000343test cases are represented by :class:`unittest.TestCase` instances.
344To make your own test cases you must write subclasses of
345:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
Georg Brandl116aa622007-08-15 14:28:22 +0000347The testing code of a :class:`TestCase` instance should be entirely self
348contained, such that it can be run either in isolation or in arbitrary
349combination with any number of other test cases.
350
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100351The simplest :class:`TestCase` subclass will simply implement a test method
352(i.e. a method whose name starts with ``test``) in order to perform specific
353testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355 import unittest
356
357 class DefaultWidgetSizeTestCase(unittest.TestCase):
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100358 def test_default_widget_size(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000359 widget = Widget('The widget')
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100360 self.assertEqual(widget.size(), (50, 50))
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Sandro Tosi41b24042012-01-21 10:59:37 +0100362Note that in order to test something, we use one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000363methods provided by the :class:`TestCase` base class. If the test fails, an
Gregory P. Smithdff46752018-05-17 10:08:45 -0500364exception will be raised with an explanatory message, and :mod:`unittest`
365will identify the test case as a :dfn:`failure`. Any other exceptions will be
366treated as :dfn:`errors`.
Georg Brandl116aa622007-08-15 14:28:22 +0000367
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100368Tests can be numerous, and their set-up can be repetitive. Luckily, we
369can factor out set-up code by implementing a method called
370:meth:`~TestCase.setUp`, which the testing framework will automatically
371call for every single test we run::
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373 import unittest
374
Berker Peksagab75e022016-08-06 03:00:03 +0300375 class WidgetTestCase(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000376 def setUp(self):
377 self.widget = Widget('The widget')
378
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100379 def test_default_widget_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000380 self.assertEqual(self.widget.size(), (50,50),
381 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000382
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100383 def test_widget_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000384 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000385 self.assertEqual(self.widget.size(), (100,150),
386 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100388.. note::
389 The order in which the various tests will be run is determined
390 by sorting the test method names with respect to the built-in
391 ordering for strings.
392
Benjamin Peterson52baa292009-03-24 00:56:30 +0000393If the :meth:`~TestCase.setUp` method raises an exception while the test is
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100394running, the framework will consider the test to have suffered an error, and
395the test method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000396
Benjamin Peterson52baa292009-03-24 00:56:30 +0000397Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100398after the test method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400 import unittest
401
Berker Peksagab75e022016-08-06 03:00:03 +0300402 class WidgetTestCase(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000403 def setUp(self):
404 self.widget = Widget('The widget')
405
406 def tearDown(self):
407 self.widget.dispose()
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100409If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be
410run whether the test method succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000411
Gregory P. Smithdff46752018-05-17 10:08:45 -0500412Such a working environment for the testing code is called a
413:dfn:`test fixture`. A new TestCase instance is created as a unique
414test fixture used to execute each individual test method. Thus
Berker Peksag2e5566d2018-08-04 00:56:55 +0300415:meth:`~TestCase.setUp`, :meth:`~TestCase.tearDown`, and :meth:`~TestCase.__init__`
Gregory P. Smithdff46752018-05-17 10:08:45 -0500416will be called once per test.
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Gregory P. Smithdff46752018-05-17 10:08:45 -0500418It is recommended that you use TestCase implementations to group tests together
419according to the features they test. :mod:`unittest` provides a mechanism for
420this: the :dfn:`test suite`, represented by :mod:`unittest`'s
421:class:`TestSuite` class. In most cases, calling :func:`unittest.main` will do
422the right thing and collect all the module's test cases for you and execute
423them.
Georg Brandl116aa622007-08-15 14:28:22 +0000424
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100425However, should you want to customize the building of your test suite,
426you can do it yourself::
Georg Brandl116aa622007-08-15 14:28:22 +0000427
428 def suite():
429 suite = unittest.TestSuite()
Berker Peksag92551042017-10-13 06:41:57 +0300430 suite.addTest(WidgetTestCase('test_default_widget_size'))
431 suite.addTest(WidgetTestCase('test_widget_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000432 return suite
433
Berker Peksag92551042017-10-13 06:41:57 +0300434 if __name__ == '__main__':
435 runner = unittest.TextTestRunner()
436 runner.run(suite())
437
Georg Brandl116aa622007-08-15 14:28:22 +0000438You can place the definitions of test cases and test suites in the same modules
439as the code they are to test (such as :file:`widget.py`), but there are several
440advantages to placing the test code in a separate module, such as
441:file:`test_widget.py`:
442
443* The test module can be run standalone from the command line.
444
445* The test code can more easily be separated from shipped code.
446
447* There is less temptation to change test code to fit the code it tests without
448 a good reason.
449
450* Test code should be modified much less frequently than the code it tests.
451
452* Tested code can be refactored more easily.
453
454* Tests for modules written in C must be in separate modules anyway, so why not
455 be consistent?
456
457* If the testing strategy changes, there is no need to change the source code.
458
459
460.. _legacy-unit-tests:
461
462Re-using old test code
463----------------------
464
465Some users will find that they have existing test code that they would like to
466run from :mod:`unittest`, without converting every old test function to a
467:class:`TestCase` subclass.
468
469For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
470This subclass of :class:`TestCase` can be used to wrap an existing test
471function. Set-up and tear-down functions can also be provided.
472
473Given the following test function::
474
475 def testSomething():
476 something = makeSomething()
477 assert something.name is not None
478 # ...
479
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100480one can create an equivalent test case instance as follows, with optional
481set-up and tear-down methods::
Georg Brandl116aa622007-08-15 14:28:22 +0000482
483 testcase = unittest.FunctionTestCase(testSomething,
484 setUp=makeSomethingDB,
485 tearDown=deleteSomethingDB)
486
Georg Brandl116aa622007-08-15 14:28:22 +0000487.. note::
488
Benjamin Petersond2397752009-06-27 23:45:02 +0000489 Even though :class:`FunctionTestCase` can be used to quickly convert an
490 existing test base over to a :mod:`unittest`\ -based system, this approach is
491 not recommended. Taking the time to set up proper :class:`TestCase`
492 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000493
Benjamin Peterson52baa292009-03-24 00:56:30 +0000494In some cases, the existing tests may have been written using the :mod:`doctest`
495module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
496automatically build :class:`unittest.TestSuite` instances from the existing
497:mod:`doctest`\ -based tests.
498
Georg Brandl116aa622007-08-15 14:28:22 +0000499
Benjamin Peterson5254c042009-03-23 22:25:03 +0000500.. _unittest-skipping:
501
502Skipping tests and expected failures
503------------------------------------
504
Michael Foordf5c851a2010-02-05 21:48:03 +0000505.. versionadded:: 3.1
506
Benjamin Peterson5254c042009-03-23 22:25:03 +0000507Unittest supports skipping individual test methods and even whole classes of
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200508tests. In addition, it supports marking a test as an "expected failure," a test
Benjamin Peterson5254c042009-03-23 22:25:03 +0000509that is broken and will fail, but shouldn't be counted as a failure on a
510:class:`TestResult`.
511
512Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
Makdonffed76b2019-06-01 00:19:12 +0800513or one of its conditional variants, calling :meth:`TestCase.skipTest` within a
514:meth:`~TestCase.setUp` or test method, or raising :exc:`SkipTest` directly.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000515
Ezio Melottifed69ba2013-03-01 21:26:04 +0200516Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000517
518 class MyTestCase(unittest.TestCase):
519
520 @unittest.skip("demonstrating skipping")
521 def test_nothing(self):
522 self.fail("shouldn't happen")
523
Benjamin Petersond2397752009-06-27 23:45:02 +0000524 @unittest.skipIf(mylib.__version__ < (1, 3),
525 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000526 def test_format(self):
527 # Tests that work for only a certain version of the library.
528 pass
529
530 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
531 def test_windows_support(self):
532 # windows specific testing code
533 pass
534
Makdonffed76b2019-06-01 00:19:12 +0800535 def test_maybe_skipped(self):
536 if not external_resource_available():
537 self.skipTest("external resource not available")
538 # test code that depends on the external resource
539 pass
540
Ezio Melottifed69ba2013-03-01 21:26:04 +0200541This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000542
Benjamin Petersonded31c42009-03-30 15:04:16 +0000543 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000544 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Makdonffed76b2019-06-01 00:19:12 +0800545 test_maybe_skipped (__main__.MyTestCase) ... skipped 'external resource not available'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000546 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000547
548 ----------------------------------------------------------------------
Makdonffed76b2019-06-01 00:19:12 +0800549 Ran 4 tests in 0.005s
Benjamin Petersonded31c42009-03-30 15:04:16 +0000550
Makdonffed76b2019-06-01 00:19:12 +0800551 OK (skipped=4)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000552
Ezio Melottifed69ba2013-03-01 21:26:04 +0200553Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000554
Sandro Tosi317075d2012-03-31 18:34:59 +0200555 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000556 class MySkippedTestCase(unittest.TestCase):
557 def test_not_run(self):
558 pass
559
Benjamin Peterson52baa292009-03-24 00:56:30 +0000560:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
561that needs to be set up is not available.
562
Benjamin Peterson5254c042009-03-23 22:25:03 +0000563Expected failures use the :func:`expectedFailure` decorator. ::
564
565 class ExpectedFailureTestCase(unittest.TestCase):
566 @unittest.expectedFailure
567 def test_fail(self):
568 self.assertEqual(1, 0, "broken")
569
570It's easy to roll your own skipping decorators by making a decorator that calls
571:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottifed69ba2013-03-01 21:26:04 +0200572the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000573
574 def skipUnlessHasattr(obj, attr):
575 if hasattr(obj, attr):
576 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200577 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000578
Makdonffed76b2019-06-01 00:19:12 +0800579The following decorators and exception implement test skipping and expected failures:
Benjamin Peterson5254c042009-03-23 22:25:03 +0000580
Georg Brandl8a1caa22010-07-29 16:01:11 +0000581.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000582
583 Unconditionally skip the decorated test. *reason* should describe why the
584 test is being skipped.
585
Georg Brandl8a1caa22010-07-29 16:01:11 +0000586.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000587
588 Skip the decorated test if *condition* is true.
589
Georg Brandl8a1caa22010-07-29 16:01:11 +0000590.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000591
Georg Brandl6faee4e2010-09-21 14:48:28 +0000592 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000593
Georg Brandl8a1caa22010-07-29 16:01:11 +0000594.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000595
Gregory P. Smith91f259b2018-12-06 12:56:24 -0800596 Mark the test as an expected failure. If the test fails it will be
597 considered a success. If the test passes, it will be considered a failure.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000598
Ezio Melotti265281a2013-03-27 20:11:55 +0200599.. exception:: SkipTest(reason)
600
601 This exception is raised to skip a test.
602
603 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
604 decorators instead of raising this directly.
605
R David Murray42fa1102014-01-03 13:03:36 -0500606Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them.
607Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run.
608Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000609
Benjamin Peterson5254c042009-03-23 22:25:03 +0000610
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100611.. _subtests:
612
613Distinguishing test iterations using subtests
614---------------------------------------------
615
616.. versionadded:: 3.4
617
Géry Ogam009b2f02018-11-09 20:34:54 +0100618When there are very small differences among your tests, for
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100619instance some parameters, unittest allows you to distinguish them inside
620the body of a test method using the :meth:`~TestCase.subTest` context manager.
621
622For example, the following test::
623
624 class NumbersTest(unittest.TestCase):
625
626 def test_even(self):
627 """
628 Test that numbers between 0 and 5 are all even.
629 """
630 for i in range(0, 6):
631 with self.subTest(i=i):
632 self.assertEqual(i % 2, 0)
633
634will produce the following output::
635
636 ======================================================================
637 FAIL: test_even (__main__.NumbersTest) (i=1)
638 ----------------------------------------------------------------------
639 Traceback (most recent call last):
640 File "subtests.py", line 32, in test_even
641 self.assertEqual(i % 2, 0)
642 AssertionError: 1 != 0
643
644 ======================================================================
645 FAIL: test_even (__main__.NumbersTest) (i=3)
646 ----------------------------------------------------------------------
647 Traceback (most recent call last):
648 File "subtests.py", line 32, in test_even
649 self.assertEqual(i % 2, 0)
650 AssertionError: 1 != 0
651
652 ======================================================================
653 FAIL: test_even (__main__.NumbersTest) (i=5)
654 ----------------------------------------------------------------------
655 Traceback (most recent call last):
656 File "subtests.py", line 32, in test_even
657 self.assertEqual(i % 2, 0)
658 AssertionError: 1 != 0
659
660Without using a subtest, execution would stop after the first failure,
661and the error would be less easy to diagnose because the value of ``i``
662wouldn't be displayed::
663
664 ======================================================================
665 FAIL: test_even (__main__.NumbersTest)
666 ----------------------------------------------------------------------
667 Traceback (most recent call last):
668 File "subtests.py", line 32, in test_even
669 self.assertEqual(i % 2, 0)
670 AssertionError: 1 != 0
671
672
Georg Brandl116aa622007-08-15 14:28:22 +0000673.. _unittest-contents:
674
675Classes and functions
676---------------------
677
Benjamin Peterson52baa292009-03-24 00:56:30 +0000678This section describes in depth the API of :mod:`unittest`.
679
680
681.. _testcase-objects:
682
683Test cases
684~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Georg Brandl7f01a132009-09-16 15:58:14 +0000686.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000687
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100688 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000689 in the :mod:`unittest` universe. This class is intended to be used as a base
690 class, with specific tests being implemented by concrete subclasses. This class
691 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100692 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000693 kinds of failure.
694
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100695 Each instance of :class:`TestCase` will run a single base method: the method
Robert Collinse02f6c22015-07-23 06:37:26 +1200696 named *methodName*.
697 In most uses of :class:`TestCase`, you will neither change
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100698 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000699
Michael Foord1341bb02011-03-14 19:01:46 -0400700 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100701 :class:`TestCase` can be instantiated successfully without providing a
702 *methodName*. This makes it easier to experiment with :class:`TestCase`
703 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000704
705 :class:`TestCase` instances provide three groups of methods: one group used
706 to run the test, another used by the test implementation to check conditions
707 and report failures, and some inquiry methods allowing information about the
708 test itself to be gathered.
709
710 Methods in the first group (running the test) are:
711
Benjamin Peterson52baa292009-03-24 00:56:30 +0000712 .. method:: setUp()
713
714 Method called to prepare the test fixture. This is called immediately
Terry Jan Reedy7f84d1e2014-04-15 23:44:14 -0400715 before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`,
716 any exception raised by this method will be considered an error rather than
Terry Jan Reedy6ac42402014-04-15 23:38:18 -0400717 a test failure. The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000718
719
720 .. method:: tearDown()
721
722 Method called immediately after the test method has been called and the
723 result recorded. This is called even if the test method raised an
724 exception, so the implementation in subclasses may need to be particularly
Ezio Melotti8dea74f2016-03-13 09:40:09 +0200725 careful about checking internal state. Any exception, other than
726 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
727 considered an additional error rather than a test failure (thus increasing
728 the total number of reported errors). This method will only be called if
729 the :meth:`setUp` succeeds, regardless of the outcome of the test method.
730 The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000731
732
Benjamin Petersonb48af542010-04-11 20:43:16 +0000733 .. method:: setUpClass()
734
Ville Skyttäc33bb5d2018-08-23 17:49:18 +0300735 A class method called before tests in an individual class are run.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000736 ``setUpClass`` is called with the class as the only argument
737 and must be decorated as a :func:`classmethod`::
738
739 @classmethod
740 def setUpClass(cls):
741 ...
742
743 See `Class and Module Fixtures`_ for more details.
744
745 .. versionadded:: 3.2
746
747
748 .. method:: tearDownClass()
749
750 A class method called after tests in an individual class have run.
751 ``tearDownClass`` is called with the class as the only argument
752 and must be decorated as a :meth:`classmethod`::
753
754 @classmethod
755 def tearDownClass(cls):
756 ...
757
758 See `Class and Module Fixtures`_ for more details.
759
760 .. versionadded:: 3.2
761
762
Georg Brandl7f01a132009-09-16 15:58:14 +0000763 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000764
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100765 Run the test, collecting the result into the :class:`TestResult` object
766 passed as *result*. If *result* is omitted or ``None``, a temporary
767 result object is created (by calling the :meth:`defaultTestResult`
768 method) and used. The result object is returned to :meth:`run`'s
769 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000770
771 The same effect may be had by simply calling the :class:`TestCase`
772 instance.
773
Michael Foord1341bb02011-03-14 19:01:46 -0400774 .. versionchanged:: 3.3
775 Previous versions of ``run`` did not return the result. Neither did
776 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000777
Benjamin Petersone549ead2009-03-28 21:42:05 +0000778 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000779
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000780 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000781 test. See :ref:`unittest-skipping` for more information.
782
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000783 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000784
Benjamin Peterson52baa292009-03-24 00:56:30 +0000785
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100786 .. method:: subTest(msg=None, **params)
787
788 Return a context manager which executes the enclosed code block as a
789 subtest. *msg* and *params* are optional, arbitrary values which are
790 displayed whenever a subtest fails, allowing you to identify them
791 clearly.
792
793 A test case can contain any number of subtest declarations, and
794 they can be arbitrarily nested.
795
796 See :ref:`subtests` for more information.
797
798 .. versionadded:: 3.4
799
800
Benjamin Peterson52baa292009-03-24 00:56:30 +0000801 .. method:: debug()
802
803 Run the test without collecting the result. This allows exceptions raised
804 by the test to be propagated to the caller, and can be used to support
805 running tests under a debugger.
806
Ezio Melotti22170ed2010-11-20 09:57:27 +0000807 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000808
Ezio Melottif418db22016-01-12 11:03:31 +0200809 The :class:`TestCase` class provides several assert methods to check for and
810 report failures. The following table lists the most commonly used methods
811 (see the tables below for more assert methods):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000812
Ezio Melotti4370b302010-11-03 20:39:14 +0000813 +-----------------------------------------+-----------------------------+---------------+
814 | Method | Checks that | New in |
815 +=========================================+=============================+===============+
816 | :meth:`assertEqual(a, b) | ``a == b`` | |
817 | <TestCase.assertEqual>` | | |
818 +-----------------------------------------+-----------------------------+---------------+
819 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
820 | <TestCase.assertNotEqual>` | | |
821 +-----------------------------------------+-----------------------------+---------------+
822 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
823 | <TestCase.assertTrue>` | | |
824 +-----------------------------------------+-----------------------------+---------------+
825 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
826 | <TestCase.assertFalse>` | | |
827 +-----------------------------------------+-----------------------------+---------------+
828 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
829 | <TestCase.assertIs>` | | |
830 +-----------------------------------------+-----------------------------+---------------+
831 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
832 | <TestCase.assertIsNot>` | | |
833 +-----------------------------------------+-----------------------------+---------------+
834 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
835 | <TestCase.assertIsNone>` | | |
836 +-----------------------------------------+-----------------------------+---------------+
837 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
838 | <TestCase.assertIsNotNone>` | | |
839 +-----------------------------------------+-----------------------------+---------------+
840 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
841 | <TestCase.assertIn>` | | |
842 +-----------------------------------------+-----------------------------+---------------+
843 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
844 | <TestCase.assertNotIn>` | | |
845 +-----------------------------------------+-----------------------------+---------------+
846 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
847 | <TestCase.assertIsInstance>` | | |
848 +-----------------------------------------+-----------------------------+---------------+
849 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
850 | <TestCase.assertNotIsInstance>` | | |
851 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000852
Ezio Melottib4dc2502011-05-06 15:01:41 +0300853 All the assert methods accept a *msg* argument that, if specified, is used
854 as the error message on failure (see also :data:`longMessage`).
855 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
856 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
857 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000858
Michael Foorde180d392011-01-28 19:51:48 +0000859 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000860
Michael Foorde180d392011-01-28 19:51:48 +0000861 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000862 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000863
Michael Foorde180d392011-01-28 19:51:48 +0000864 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000865 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200866 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000867 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000868 error message (see also the :ref:`list of type-specific methods
869 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000870
Raymond Hettinger35a88362009-04-09 00:08:24 +0000871 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200872 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000873
Michael Foord28a817e2010-02-09 00:03:57 +0000874 .. versionchanged:: 3.2
875 :meth:`assertMultiLineEqual` added as the default type equality
876 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000877
Benjamin Peterson52baa292009-03-24 00:56:30 +0000878
Michael Foorde180d392011-01-28 19:51:48 +0000879 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000880
Michael Foorde180d392011-01-28 19:51:48 +0000881 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000882 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000883
Ezio Melotti4370b302010-11-03 20:39:14 +0000884 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000885 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000886
Ezio Melotti4841fd62010-11-05 15:43:40 +0000887 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000888
Ezio Melotti4841fd62010-11-05 15:43:40 +0000889 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
890 is True`` (use ``assertIs(expr, True)`` for the latter). This method
891 should also be avoided when more specific methods are available (e.g.
892 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
893 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000894
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000895
Michael Foorde180d392011-01-28 19:51:48 +0000896 .. method:: assertIs(first, second, msg=None)
897 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000898
Michael Foorde180d392011-01-28 19:51:48 +0000899 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000900 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000901
Raymond Hettinger35a88362009-04-09 00:08:24 +0000902 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000903
904
Ezio Melotti4370b302010-11-03 20:39:14 +0000905 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000906 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000907
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300908 Test that *expr* is (or is not) ``None``.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000909
Ezio Melotti4370b302010-11-03 20:39:14 +0000910 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000911
912
Christoph Zwerschkea388bbd2020-04-17 03:54:53 +0200913 .. method:: assertIn(member, container, msg=None)
914 assertNotIn(member, container, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000915
Christoph Zwerschkea388bbd2020-04-17 03:54:53 +0200916 Test that *member* is (or is not) in *container*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000917
Raymond Hettinger35a88362009-04-09 00:08:24 +0000918 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000919
920
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000921 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000922 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000923
Ezio Melotti9794a262010-11-04 14:52:13 +0000924 Test that *obj* is (or is not) an instance of *cls* (which can be a
925 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200926 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000927
Ezio Melotti4370b302010-11-03 20:39:14 +0000928 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000929
930
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000931
Ezio Melottif418db22016-01-12 11:03:31 +0200932 It is also possible to check the production of exceptions, warnings, and
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200933 log messages using the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000934
Ezio Melotti4370b302010-11-03 20:39:14 +0000935 +---------------------------------------------------------+--------------------------------------+------------+
936 | Method | Checks that | New in |
937 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200938 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000939 | <TestCase.assertRaises>` | | |
940 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300941 | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
942 | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000943 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200944 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000945 | <TestCase.assertWarns>` | | |
946 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300947 | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
948 | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000949 +---------------------------------------------------------+--------------------------------------+------------+
Georg Brandled007d52013-11-24 16:09:26 +0100950 | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 |
951 | <TestCase.assertLogs>` | with minimum *level* | |
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200952 +---------------------------------------------------------+--------------------------------------+------------+
Kit Choi6b34d7b2020-07-01 22:08:38 +0100953 | :meth:`assertNoLogs(logger, level) | The ``with`` block does not log on | 3.10 |
954 | <TestCase.assertNoLogs>` | *logger* with minimum *level* | |
955 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000956
Georg Brandl7f01a132009-09-16 15:58:14 +0000957 .. method:: assertRaises(exception, callable, *args, **kwds)
Benjamin Petersonbe4e5b82018-10-01 22:18:44 -0700958 assertRaises(exception, *, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000959
960 Test that an exception is raised when *callable* is called with any
961 positional or keyword arguments that are also passed to
962 :meth:`assertRaises`. The test passes if *exception* is raised, is an
963 error if another exception is raised, or fails if no exception is raised.
964 To catch any of a group of exceptions, a tuple containing the exception
965 classes may be passed as *exception*.
966
Ezio Melottib4dc2502011-05-06 15:01:41 +0300967 If only the *exception* and possibly the *msg* arguments are given,
968 return a context manager so that the code under test can be written
969 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000970
Michael Foord41531f22010-02-05 21:13:40 +0000971 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000972 do_something()
973
Ezio Melottib4dc2502011-05-06 15:01:41 +0300974 When used as a context manager, :meth:`assertRaises` accepts the
975 additional keyword argument *msg*.
976
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000977 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000978 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000979 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000980
Georg Brandl8a1caa22010-07-29 16:01:11 +0000981 with self.assertRaises(SomeException) as cm:
982 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000983
Georg Brandl8a1caa22010-07-29 16:01:11 +0000984 the_exception = cm.exception
985 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000986
Ezio Melotti49008232010-02-08 21:57:48 +0000987 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000988 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000989
Ezio Melotti49008232010-02-08 21:57:48 +0000990 .. versionchanged:: 3.2
991 Added the :attr:`exception` attribute.
992
Ezio Melottib4dc2502011-05-06 15:01:41 +0300993 .. versionchanged:: 3.3
994 Added the *msg* keyword argument when used as a context manager.
995
Benjamin Peterson52baa292009-03-24 00:56:30 +0000996
Ezio Melottied3a7d22010-12-01 02:32:32 +0000997 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Benjamin Petersone006b392018-10-02 21:38:39 -0700998 assertRaisesRegex(exception, regex, *, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000999
Ezio Melottied3a7d22010-12-01 02:32:32 +00001000 Like :meth:`assertRaises` but also tests that *regex* matches
1001 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001002 a regular expression object or a string containing a regular expression
1003 suitable for use by :func:`re.search`. Examples::
1004
Terry Jan Reedyc4565a92013-06-29 13:15:43 -04001005 self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
Ezio Melottied3a7d22010-12-01 02:32:32 +00001006 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001007
1008 or::
1009
Ezio Melottied3a7d22010-12-01 02:32:32 +00001010 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001011 int('XYZ')
1012
Georg Brandl419e3de2010-12-01 15:44:25 +00001013 .. versionadded:: 3.1
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001014 Added under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +03001015
Ezio Melottied3a7d22010-12-01 02:32:32 +00001016 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001017 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001018
Ezio Melottib4dc2502011-05-06 15:01:41 +03001019 .. versionchanged:: 3.3
1020 Added the *msg* keyword argument when used as a context manager.
1021
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001022
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001023 .. method:: assertWarns(warning, callable, *args, **kwds)
Benjamin Petersone006b392018-10-02 21:38:39 -07001024 assertWarns(warning, *, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001025
1026 Test that a warning is triggered when *callable* is called with any
1027 positional or keyword arguments that are also passed to
1028 :meth:`assertWarns`. The test passes if *warning* is triggered and
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001029 fails if it isn't. Any exception is an error.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001030 To catch any of a group of warnings, a tuple containing the warning
1031 classes may be passed as *warnings*.
1032
Ezio Melottib4dc2502011-05-06 15:01:41 +03001033 If only the *warning* and possibly the *msg* arguments are given,
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001034 return a context manager so that the code under test can be written
Ezio Melottib4dc2502011-05-06 15:01:41 +03001035 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001036
1037 with self.assertWarns(SomeWarning):
1038 do_something()
1039
Terry Jan Reedy9eda66d2013-07-27 16:15:29 -04001040 When used as a context manager, :meth:`assertWarns` accepts the
Ezio Melottib4dc2502011-05-06 15:01:41 +03001041 additional keyword argument *msg*.
1042
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001043 The context manager will store the caught warning object in its
1044 :attr:`warning` attribute, and the source line which triggered the
1045 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1046 This can be useful if the intention is to perform additional checks
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001047 on the warning caught::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001048
1049 with self.assertWarns(SomeWarning) as cm:
1050 do_something()
1051
1052 self.assertIn('myfile.py', cm.filename)
1053 self.assertEqual(320, cm.lineno)
1054
1055 This method works regardless of the warning filters in place when it
1056 is called.
1057
1058 .. versionadded:: 3.2
1059
Ezio Melottib4dc2502011-05-06 15:01:41 +03001060 .. versionchanged:: 3.3
1061 Added the *msg* keyword argument when used as a context manager.
1062
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001063
Ezio Melottied3a7d22010-12-01 02:32:32 +00001064 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Benjamin Petersone006b392018-10-02 21:38:39 -07001065 assertWarnsRegex(warning, regex, *, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001066
Ezio Melottied3a7d22010-12-01 02:32:32 +00001067 Like :meth:`assertWarns` but also tests that *regex* matches on the
1068 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001069 object or a string containing a regular expression suitable for use
1070 by :func:`re.search`. Example::
1071
Ezio Melottied3a7d22010-12-01 02:32:32 +00001072 self.assertWarnsRegex(DeprecationWarning,
1073 r'legacy_function\(\) is deprecated',
1074 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001075
1076 or::
1077
Ezio Melottied3a7d22010-12-01 02:32:32 +00001078 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001079 frobnicate('/etc/passwd')
1080
1081 .. versionadded:: 3.2
1082
Ezio Melottib4dc2502011-05-06 15:01:41 +03001083 .. versionchanged:: 3.3
1084 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001085
Antoine Pitrou0715b9f2013-09-14 19:45:47 +02001086 .. method:: assertLogs(logger=None, level=None)
1087
1088 A context manager to test that at least one message is logged on
1089 the *logger* or one of its children, with at least the given
1090 *level*.
1091
1092 If given, *logger* should be a :class:`logging.Logger` object or a
1093 :class:`str` giving the name of a logger. The default is the root
1094 logger, which will catch all messages.
1095
1096 If given, *level* should be either a numeric logging level or
1097 its string equivalent (for example either ``"ERROR"`` or
1098 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`.
1099
1100 The test passes if at least one message emitted inside the ``with``
1101 block matches the *logger* and *level* conditions, otherwise it fails.
1102
1103 The object returned by the context manager is a recording helper
1104 which keeps tracks of the matching log messages. It has two
1105 attributes:
1106
1107 .. attribute:: records
1108
1109 A list of :class:`logging.LogRecord` objects of the matching
1110 log messages.
1111
1112 .. attribute:: output
1113
1114 A list of :class:`str` objects with the formatted output of
1115 matching messages.
1116
1117 Example::
1118
1119 with self.assertLogs('foo', level='INFO') as cm:
1120 logging.getLogger('foo').info('first message')
1121 logging.getLogger('foo.bar').error('second message')
1122 self.assertEqual(cm.output, ['INFO:foo:first message',
1123 'ERROR:foo.bar:second message'])
1124
1125 .. versionadded:: 3.4
1126
Kit Choi6b34d7b2020-07-01 22:08:38 +01001127 .. method:: assertNoLogs(logger=None, level=None)
1128
1129 A context manager to test that no messages are logged on
1130 the *logger* or one of its children, with at least the given
1131 *level*.
1132
1133 If given, *logger* should be a :class:`logging.Logger` object or a
1134 :class:`str` giving the name of a logger. The default is the root
1135 logger, which will catch all messages.
1136
1137 If given, *level* should be either a numeric logging level or
1138 its string equivalent (for example either ``"ERROR"`` or
1139 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`.
1140
1141 Unlike :meth:`assertLogs`, nothing will be returned by the context
1142 manager.
1143
1144 .. versionadded:: 3.10
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001145
Ezio Melotti4370b302010-11-03 20:39:14 +00001146 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001147
Ezio Melotti4370b302010-11-03 20:39:14 +00001148 +---------------------------------------+--------------------------------+--------------+
1149 | Method | Checks that | New in |
1150 +=======================================+================================+==============+
1151 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1152 | <TestCase.assertAlmostEqual>` | | |
1153 +---------------------------------------+--------------------------------+--------------+
1154 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1155 | <TestCase.assertNotAlmostEqual>` | | |
1156 +---------------------------------------+--------------------------------+--------------+
1157 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1158 | <TestCase.assertGreater>` | | |
1159 +---------------------------------------+--------------------------------+--------------+
1160 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1161 | <TestCase.assertGreaterEqual>` | | |
1162 +---------------------------------------+--------------------------------+--------------+
1163 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1164 | <TestCase.assertLess>` | | |
1165 +---------------------------------------+--------------------------------+--------------+
1166 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1167 | <TestCase.assertLessEqual>` | | |
1168 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001169 | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001170 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001171 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001172 | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001173 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001174 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001175 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001176 | <TestCase.assertCountEqual>` | elements in the same number, | |
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001177 | | regardless of their order. | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001178 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001179
1180
Michael Foorde180d392011-01-28 19:51:48 +00001181 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1182 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001183
Michael Foorde180d392011-01-28 19:51:48 +00001184 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001185 equal by computing the difference, rounding to the given number of
1186 decimal *places* (default 7), and comparing to zero. Note that these
1187 methods round the values to the given number of *decimal places* (i.e.
1188 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001189
Ezio Melotti4370b302010-11-03 20:39:14 +00001190 If *delta* is supplied instead of *places* then the difference
Ezio Melottid51914c2013-08-11 13:04:50 +03001191 between *first* and *second* must be less or equal to (or greater than) *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001192
Stéphane Wirtele483f022018-10-26 12:52:11 +02001193 Supplying both *delta* and *places* raises a :exc:`TypeError`.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001194
Ezio Melotti4370b302010-11-03 20:39:14 +00001195 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001196 :meth:`assertAlmostEqual` automatically considers almost equal objects
1197 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1198 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001199
Ezio Melotti4370b302010-11-03 20:39:14 +00001200
Michael Foorde180d392011-01-28 19:51:48 +00001201 .. method:: assertGreater(first, second, msg=None)
1202 assertGreaterEqual(first, second, msg=None)
1203 assertLess(first, second, msg=None)
1204 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001205
Michael Foorde180d392011-01-28 19:51:48 +00001206 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001207 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001208
1209 >>> self.assertGreaterEqual(3, 4)
1210 AssertionError: "3" unexpectedly not greater than or equal to "4"
1211
1212 .. versionadded:: 3.1
1213
1214
Ezio Melottied3a7d22010-12-01 02:32:32 +00001215 .. method:: assertRegex(text, regex, msg=None)
1216 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001217
Ezio Melottied3a7d22010-12-01 02:32:32 +00001218 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001219 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001220 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001221 may be a regular expression object or a string containing a regular
1222 expression suitable for use by :func:`re.search`.
1223
Georg Brandl419e3de2010-12-01 15:44:25 +00001224 .. versionadded:: 3.1
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001225 Added under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001226 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001227 The method ``assertRegexpMatches()`` has been renamed to
1228 :meth:`.assertRegex`.
1229 .. versionadded:: 3.2
1230 :meth:`.assertNotRegex`.
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001231 .. versionadded:: 3.5
1232 The name ``assertNotRegexpMatches`` is a deprecated alias
1233 for :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001234
1235
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001236 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001237
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001238 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001239 regardless of their order. When they don't, an error message listing the
1240 differences between the sequences will be generated.
1241
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001242 Duplicate elements are *not* ignored when comparing *first* and
1243 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001244 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001245 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001246 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001247
Ezio Melotti4370b302010-11-03 20:39:14 +00001248 .. versionadded:: 3.2
1249
Ezio Melotti4370b302010-11-03 20:39:14 +00001250
Ezio Melotti22170ed2010-11-20 09:57:27 +00001251 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001252
Ezio Melotti22170ed2010-11-20 09:57:27 +00001253 The :meth:`assertEqual` method dispatches the equality check for objects of
1254 the same type to different type-specific methods. These methods are already
1255 implemented for most of the built-in types, but it's also possible to
1256 register new methods using :meth:`addTypeEqualityFunc`:
1257
1258 .. method:: addTypeEqualityFunc(typeobj, function)
1259
1260 Registers a type-specific method called by :meth:`assertEqual` to check
1261 if two objects of exactly the same *typeobj* (not subclasses) compare
1262 equal. *function* must take two positional arguments and a third msg=None
1263 keyword argument just as :meth:`assertEqual` does. It must raise
1264 :data:`self.failureException(msg) <failureException>` when inequality
1265 between the first two parameters is detected -- possibly providing useful
1266 information and explaining the inequalities in details in the error
1267 message.
1268
1269 .. versionadded:: 3.1
1270
1271 The list of type-specific methods automatically used by
1272 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1273 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001274
1275 +-----------------------------------------+-----------------------------+--------------+
1276 | Method | Used to compare | New in |
1277 +=========================================+=============================+==============+
1278 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1279 | <TestCase.assertMultiLineEqual>` | | |
1280 +-----------------------------------------+-----------------------------+--------------+
1281 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1282 | <TestCase.assertSequenceEqual>` | | |
1283 +-----------------------------------------+-----------------------------+--------------+
1284 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1285 | <TestCase.assertListEqual>` | | |
1286 +-----------------------------------------+-----------------------------+--------------+
1287 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1288 | <TestCase.assertTupleEqual>` | | |
1289 +-----------------------------------------+-----------------------------+--------------+
1290 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1291 | <TestCase.assertSetEqual>` | | |
1292 +-----------------------------------------+-----------------------------+--------------+
1293 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1294 | <TestCase.assertDictEqual>` | | |
1295 +-----------------------------------------+-----------------------------+--------------+
1296
1297
1298
Michael Foorde180d392011-01-28 19:51:48 +00001299 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001300
Michael Foorde180d392011-01-28 19:51:48 +00001301 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001302 When not equal a diff of the two strings highlighting the differences
1303 will be included in the error message. This method is used by default
1304 when comparing strings with :meth:`assertEqual`.
1305
Ezio Melotti4370b302010-11-03 20:39:14 +00001306 .. versionadded:: 3.1
1307
1308
Michael Foorde180d392011-01-28 19:51:48 +00001309 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001310
1311 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001312 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001313 be raised. If the sequences are different an error message is
1314 constructed that shows the difference between the two.
1315
Ezio Melotti22170ed2010-11-20 09:57:27 +00001316 This method is not called directly by :meth:`assertEqual`, but
1317 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001318 :meth:`assertTupleEqual`.
1319
1320 .. versionadded:: 3.1
1321
1322
Michael Foorde180d392011-01-28 19:51:48 +00001323 .. method:: assertListEqual(first, second, msg=None)
1324 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001325
Ezio Melotti49ccd512012-08-29 17:50:42 +03001326 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001327 constructed that shows only the differences between the two. An error
1328 is also raised if either of the parameters are of the wrong type.
1329 These methods are used by default when comparing lists or tuples with
1330 :meth:`assertEqual`.
1331
Ezio Melotti4370b302010-11-03 20:39:14 +00001332 .. versionadded:: 3.1
1333
1334
Michael Foorde180d392011-01-28 19:51:48 +00001335 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001336
1337 Tests that two sets are equal. If not, an error message is constructed
1338 that lists the differences between the sets. This method is used by
1339 default when comparing sets or frozensets with :meth:`assertEqual`.
1340
Michael Foorde180d392011-01-28 19:51:48 +00001341 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001342 method.
1343
Ezio Melotti4370b302010-11-03 20:39:14 +00001344 .. versionadded:: 3.1
1345
1346
Michael Foorde180d392011-01-28 19:51:48 +00001347 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001348
1349 Test that two dictionaries are equal. If not, an error message is
1350 constructed that shows the differences in the dictionaries. This
1351 method will be used by default to compare dictionaries in
1352 calls to :meth:`assertEqual`.
1353
Ezio Melotti4370b302010-11-03 20:39:14 +00001354 .. versionadded:: 3.1
1355
1356
1357
Ezio Melotti22170ed2010-11-20 09:57:27 +00001358 .. _other-methods-and-attrs:
1359
Ezio Melotti4370b302010-11-03 20:39:14 +00001360 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001361
Benjamin Peterson52baa292009-03-24 00:56:30 +00001362
Georg Brandl7f01a132009-09-16 15:58:14 +00001363 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001364
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001365 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001366 the error message.
1367
1368
1369 .. attribute:: failureException
1370
1371 This class attribute gives the exception raised by the test method. If a
1372 test framework needs to use a specialized exception, possibly to carry
1373 additional information, it must subclass this exception in order to "play
1374 fair" with the framework. The initial value of this attribute is
1375 :exc:`AssertionError`.
1376
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001377
1378 .. attribute:: longMessage
1379
Guido van Rossum4a452352016-10-13 14:23:01 -07001380 This class attribute determines what happens when a custom failure message
1381 is passed as the msg argument to an assertXYY call that fails.
1382 ``True`` is the default value. In this case, the custom message is appended
1383 to the end of the standard failure message.
1384 When set to ``False``, the custom message replaces the standard message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001385
Guido van Rossum4a452352016-10-13 14:23:01 -07001386 The class setting can be overridden in individual test methods by assigning
1387 an instance attribute, self.longMessage, to ``True`` or ``False`` before
1388 calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001389
Guido van Rossum4a452352016-10-13 14:23:01 -07001390 The class setting gets reset before each test call.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001391
Raymond Hettinger35a88362009-04-09 00:08:24 +00001392 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001393
1394
Michael Foord98b3e762010-06-05 21:59:55 +00001395 .. attribute:: maxDiff
1396
1397 This attribute controls the maximum length of diffs output by assert
1398 methods that report diffs on failure. It defaults to 80*8 characters.
1399 Assert methods affected by this attribute are
1400 :meth:`assertSequenceEqual` (including all the sequence comparison
1401 methods that delegate to it), :meth:`assertDictEqual` and
1402 :meth:`assertMultiLineEqual`.
1403
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001404 Setting ``maxDiff`` to ``None`` means that there is no maximum length of
Michael Foord98b3e762010-06-05 21:59:55 +00001405 diffs.
1406
1407 .. versionadded:: 3.2
1408
1409
Benjamin Peterson52baa292009-03-24 00:56:30 +00001410 Testing frameworks can use the following methods to collect information on
1411 the test:
1412
1413
1414 .. method:: countTestCases()
1415
1416 Return the number of tests represented by this test object. For
1417 :class:`TestCase` instances, this will always be ``1``.
1418
1419
1420 .. method:: defaultTestResult()
1421
1422 Return an instance of the test result class that should be used for this
1423 test case class (if no other result instance is provided to the
1424 :meth:`run` method).
1425
1426 For :class:`TestCase` instances, this will always be an instance of
1427 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1428 as necessary.
1429
1430
1431 .. method:: id()
1432
1433 Return a string identifying the specific test case. This is usually the
1434 full name of the test method, including the module and class name.
1435
1436
1437 .. method:: shortDescription()
1438
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001439 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001440 has been provided. The default implementation of this method
1441 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001442 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001443
Georg Brandl419e3de2010-12-01 15:44:25 +00001444 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001445 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001446 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001447 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001448 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001449
Georg Brandl116aa622007-08-15 14:28:22 +00001450
Serhiy Storchaka142566c2019-06-05 18:22:31 +03001451 .. method:: addCleanup(function, /, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001452
1453 Add a function to be called after :meth:`tearDown` to cleanup resources
1454 used during the test. Functions will be called in reverse order to the
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +03001455 order they are added (:abbr:`LIFO (last-in, first-out)`). They
1456 are called with any arguments and keyword arguments passed into
1457 :meth:`addCleanup` when they are added.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001458
1459 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1460 then any cleanup functions added will still be called.
1461
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001462 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001463
1464
1465 .. method:: doCleanups()
1466
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001467 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001468 after :meth:`setUp` if :meth:`setUp` raises an exception.
1469
1470 It is responsible for calling all the cleanup functions added by
1471 :meth:`addCleanup`. If you need cleanup functions to be called
1472 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1473 yourself.
1474
1475 :meth:`doCleanups` pops methods off the stack of cleanup
1476 functions one at a time, so it can be called at any time.
1477
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001478 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001479
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001480 .. classmethod:: addClassCleanup(function, /, *args, **kwargs)
Lisa Roach0f221d02018-11-08 18:34:33 -08001481
1482 Add a function to be called after :meth:`tearDownClass` to cleanup
1483 resources used during the test class. Functions will be called in reverse
1484 order to the order they are added (:abbr:`LIFO (last-in, first-out)`).
1485 They are called with any arguments and keyword arguments passed into
1486 :meth:`addClassCleanup` when they are added.
1487
1488 If :meth:`setUpClass` fails, meaning that :meth:`tearDownClass` is not
1489 called, then any cleanup functions added will still be called.
1490
1491 .. versionadded:: 3.8
1492
1493
1494 .. classmethod:: doClassCleanups()
1495
1496 This method is called unconditionally after :meth:`tearDownClass`, or
1497 after :meth:`setUpClass` if :meth:`setUpClass` raises an exception.
1498
1499 It is responsible for calling all the cleanup functions added by
1500 :meth:`addCleanupClass`. If you need cleanup functions to be called
1501 *prior* to :meth:`tearDownClass` then you can call
1502 :meth:`doCleanupsClass` yourself.
1503
1504 :meth:`doCleanupsClass` pops methods off the stack of cleanup
1505 functions one at a time, so it can be called at any time.
1506
1507 .. versionadded:: 3.8
1508
1509
Xtreak6a9fd662019-09-11 12:02:14 +01001510.. class:: IsolatedAsyncioTestCase(methodName='runTest')
1511
1512 This class provides an API similar to :class:`TestCase` and also accepts
1513 coroutines as test functions.
1514
1515 .. versionadded:: 3.8
1516
1517 .. coroutinemethod:: asyncSetUp()
1518
1519 Method called to prepare the test fixture. This is called after :meth:`setUp`.
1520 This is called immediately before calling the test method; other than
1521 :exc:`AssertionError` or :exc:`SkipTest`, any exception raised by this method
1522 will be considered an error rather than a test failure. The default implementation
1523 does nothing.
1524
1525 .. coroutinemethod:: asyncTearDown()
1526
1527 Method called immediately after the test method has been called and the
1528 result recorded. This is called before :meth:`tearDown`. This is called even if
1529 the test method raised an exception, so the implementation in subclasses may need
1530 to be particularly careful about checking internal state. Any exception, other than
1531 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
1532 considered an additional error rather than a test failure (thus increasing
1533 the total number of reported errors). This method will only be called if
1534 the :meth:`asyncSetUp` succeeds, regardless of the outcome of the test method.
1535 The default implementation does nothing.
1536
1537 .. method:: addAsyncCleanup(function, /, *args, **kwargs)
1538
1539 This method accepts a coroutine that can be used as a cleanup function.
1540
1541 .. method:: run(result=None)
1542
1543 Sets up a new event loop to run the test, collecting the result into
1544 the :class:`TestResult` object passed as *result*. If *result* is
1545 omitted or ``None``, a temporary result object is created (by calling
1546 the :meth:`defaultTestResult` method) and used. The result object is
1547 returned to :meth:`run`'s caller. At the end of the test all the tasks
1548 in the event loop are cancelled.
Lisa Roach0f221d02018-11-08 18:34:33 -08001549
1550
Xtreak6a9fd662019-09-11 12:02:14 +01001551 An example illustrating the order::
1552
1553 from unittest import IsolatedAsyncioTestCase
1554
1555 events = []
1556
1557
1558 class Test(IsolatedAsyncioTestCase):
1559
1560
1561 def setUp(self):
1562 events.append("setUp")
1563
1564 async def asyncSetUp(self):
1565 self._async_connection = await AsyncConnection()
1566 events.append("asyncSetUp")
1567
1568 async def test_response(self):
1569 events.append("test_response")
1570 response = await self._async_connection.get("https://example.com")
1571 self.assertEqual(response.status_code, 200)
1572 self.addAsyncCleanup(self.on_cleanup)
1573
1574 def tearDown(self):
1575 events.append("tearDown")
1576
1577 async def asyncTearDown(self):
1578 await self._async_connection.close()
1579 events.append("asyncTearDown")
1580
1581 async def on_cleanup(self):
1582 events.append("cleanup")
1583
1584 if __name__ == "__main__":
1585 unittest.main()
1586
Jules Lasne (jlasne)b1f160a2019-11-19 13:05:45 +01001587 After running the test, ``events`` would contain ``["setUp", "asyncSetUp", "test_response", "asyncTearDown", "tearDown", "cleanup"]``.
Lisa Roach0f221d02018-11-08 18:34:33 -08001588
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001589
Georg Brandl7f01a132009-09-16 15:58:14 +00001590.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001591
1592 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001593 allows the test runner to drive the test, but does not provide the methods
1594 which test code can use to check and report errors. This is used to create
1595 test cases using legacy test code, allowing it to be integrated into a
1596 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001597
1598
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001599.. _deprecated-aliases:
1600
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001601Deprecated aliases
1602##################
1603
1604For historical reasons, some of the :class:`TestCase` methods had one or more
1605aliases that are now deprecated. The following table lists the correct names
1606along with their deprecated aliases:
1607
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001608 ============================== ====================== =======================
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001609 Method Name Deprecated alias Deprecated alias
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001610 ============================== ====================== =======================
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001611 :meth:`.assertEqual` failUnlessEqual assertEquals
1612 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1613 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001614 :meth:`.assertFalse` failIf
1615 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001616 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1617 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001618 :meth:`.assertRegex` assertRegexpMatches
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001619 :meth:`.assertNotRegex` assertNotRegexpMatches
Ezio Melottied3a7d22010-12-01 02:32:32 +00001620 :meth:`.assertRaisesRegex` assertRaisesRegexp
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001621 ============================== ====================== =======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001622
Ezio Melotti361467e2011-04-03 17:37:58 +03001623 .. deprecated:: 3.1
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001624 The fail* aliases listed in the second column have been deprecated.
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001625 .. deprecated:: 3.2
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001626 The assert* aliases listed in the third column have been deprecated.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001627 .. deprecated:: 3.2
1628 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001629 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`.
1630 .. deprecated:: 3.5
Jules Lasne (jlasne)3d78c4a2019-03-28 22:06:27 +01001631 The ``assertNotRegexpMatches`` name is deprecated in favor of :meth:`.assertNotRegex`.
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001632
Benjamin Peterson52baa292009-03-24 00:56:30 +00001633.. _testsuite-objects:
1634
Benjamin Peterson52baa292009-03-24 00:56:30 +00001635Grouping tests
1636~~~~~~~~~~~~~~
1637
Georg Brandl7f01a132009-09-16 15:58:14 +00001638.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001639
Martin Panter37f183d2017-01-18 12:06:38 +00001640 This class represents an aggregation of individual test cases and test suites.
Georg Brandl116aa622007-08-15 14:28:22 +00001641 The class presents the interface needed by the test runner to allow it to be run
1642 as any other test case. Running a :class:`TestSuite` instance is the same as
1643 iterating over the suite, running each test individually.
1644
1645 If *tests* is given, it must be an iterable of individual test cases or other
1646 test suites that will be used to build the suite initially. Additional methods
1647 are provided to add test cases and suites to the collection later on.
1648
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001649 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1650 they do not actually implement a test. Instead, they are used to aggregate
1651 tests into groups of tests that should be run together. Some additional
1652 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001653
1654
1655 .. method:: TestSuite.addTest(test)
1656
1657 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1658
1659
1660 .. method:: TestSuite.addTests(tests)
1661
1662 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1663 instances to this test suite.
1664
Benjamin Petersond2397752009-06-27 23:45:02 +00001665 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1666 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001667
1668 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1669
1670
1671 .. method:: run(result)
1672
1673 Run the tests associated with this suite, collecting the result into the
1674 test result object passed as *result*. Note that unlike
1675 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1676 be passed in.
1677
1678
1679 .. method:: debug()
1680
1681 Run the tests associated with this suite without collecting the
1682 result. This allows exceptions raised by the test to be propagated to the
1683 caller and can be used to support running tests under a debugger.
1684
1685
1686 .. method:: countTestCases()
1687
1688 Return the number of tests represented by this test object, including all
1689 individual tests and sub-suites.
1690
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001691
1692 .. method:: __iter__()
1693
1694 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1695 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
Andrew Svetloveb973682013-08-28 21:28:38 +03001696 that this method may be called several times on a single suite (for
1697 example when counting tests or comparing for equality) so the tests
1698 returned by repeated iterations before :meth:`TestSuite.run` must be the
1699 same for each call iteration. After :meth:`TestSuite.run`, callers should
1700 not rely on the tests returned by this method unless the caller uses a
1701 subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
1702 test references.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001703
Georg Brandl853947a2010-01-31 18:53:23 +00001704 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001705 In earlier versions the :class:`TestSuite` accessed tests directly rather
1706 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1707 for providing tests.
1708
Andrew Svetloveb973682013-08-28 21:28:38 +03001709 .. versionchanged:: 3.4
1710 In earlier versions the :class:`TestSuite` held references to each
1711 :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
1712 that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
1713
Benjamin Peterson52baa292009-03-24 00:56:30 +00001714 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1715 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1716
1717
Benjamin Peterson52baa292009-03-24 00:56:30 +00001718Loading and running tests
1719~~~~~~~~~~~~~~~~~~~~~~~~~
1720
Georg Brandl116aa622007-08-15 14:28:22 +00001721.. class:: TestLoader()
1722
Benjamin Peterson52baa292009-03-24 00:56:30 +00001723 The :class:`TestLoader` class is used to create test suites from classes and
1724 modules. Normally, there is no need to create an instance of this class; the
1725 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001726 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1727 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001728
Robert Collinsf920c212014-10-20 13:24:05 +13001729 :class:`TestLoader` objects have the following attributes:
1730
1731
1732 .. attribute:: errors
1733
1734 A list of the non-fatal errors encountered while loading tests. Not reset
1735 by the loader at any point. Fatal errors are signalled by the relevant
1736 a method raising an exception to the caller. Non-fatal errors are also
1737 indicated by a synthetic test that will raise the original error when
1738 run.
1739
1740 .. versionadded:: 3.5
1741
1742
Benjamin Peterson52baa292009-03-24 00:56:30 +00001743 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001744
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001745
Benjamin Peterson52baa292009-03-24 00:56:30 +00001746 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001747
Martin Panter37f183d2017-01-18 12:06:38 +00001748 Return a suite of all test cases contained in the :class:`TestCase`\ -derived
Benjamin Peterson52baa292009-03-24 00:56:30 +00001749 :class:`testCaseClass`.
1750
Robert Collinse02f6c22015-07-23 06:37:26 +12001751 A test case instance is created for each method named by
1752 :meth:`getTestCaseNames`. By default these are the method names
1753 beginning with ``test``. If :meth:`getTestCaseNames` returns no
1754 methods, but the :meth:`runTest` method is implemented, a single test
1755 case is created for that method instead.
1756
Benjamin Peterson52baa292009-03-24 00:56:30 +00001757
Barry Warsawd78742a2014-09-08 14:21:37 -04001758 .. method:: loadTestsFromModule(module, pattern=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001759
Martin Panter37f183d2017-01-18 12:06:38 +00001760 Return a suite of all test cases contained in the given module. This
Benjamin Peterson52baa292009-03-24 00:56:30 +00001761 method searches *module* for classes derived from :class:`TestCase` and
1762 creates an instance of the class for each test method defined for the
1763 class.
1764
Georg Brandle720c0a2009-04-27 16:20:50 +00001765 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001766
1767 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1768 convenient in sharing fixtures and helper functions, defining test
1769 methods on base classes that are not intended to be instantiated
1770 directly does not play well with this method. Doing so, however, can
1771 be useful when the fixtures are different and defined in subclasses.
1772
Benjamin Petersond2397752009-06-27 23:45:02 +00001773 If a module provides a ``load_tests`` function it will be called to
1774 load the tests. This allows modules to customize test loading.
Barry Warsawd78742a2014-09-08 14:21:37 -04001775 This is the `load_tests protocol`_. The *pattern* argument is passed as
1776 the third argument to ``load_tests``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001777
Georg Brandl853947a2010-01-31 18:53:23 +00001778 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001779 Support for ``load_tests`` added.
1780
Barry Warsawd78742a2014-09-08 14:21:37 -04001781 .. versionchanged:: 3.5
1782 The undocumented and unofficial *use_load_tests* default argument is
1783 deprecated and ignored, although it is still accepted for backward
1784 compatibility. The method also now accepts a keyword-only argument
1785 *pattern* which is passed to ``load_tests`` as the third argument.
1786
Benjamin Peterson52baa292009-03-24 00:56:30 +00001787
Georg Brandl7f01a132009-09-16 15:58:14 +00001788 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001789
Martin Panter37f183d2017-01-18 12:06:38 +00001790 Return a suite of all test cases given a string specifier.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001791
1792 The specifier *name* is a "dotted name" that may resolve either to a
1793 module, a test case class, a test method within a test case class, a
1794 :class:`TestSuite` instance, or a callable object which returns a
1795 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1796 applied in the order listed here; that is, a method on a possible test
1797 case class will be picked up as "a test method within a test case class",
1798 rather than "a callable object".
1799
1800 For example, if you have a module :mod:`SampleTests` containing a
1801 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1802 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001803 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1804 return a suite which will run all three test methods. Using the specifier
1805 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1806 suite which will run only the :meth:`test_two` test method. The specifier
1807 can refer to modules and packages which have not been imported; they will
1808 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001809
1810 The method optionally resolves *name* relative to the given *module*.
1811
Martin Panter536d70e2017-01-14 08:23:08 +00001812 .. versionchanged:: 3.5
1813 If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing
1814 *name* then a synthetic test that raises that error when run will be
1815 returned. These errors are included in the errors accumulated by
1816 self.errors.
Robert Collins659dd622014-10-30 08:27:27 +13001817
Benjamin Peterson52baa292009-03-24 00:56:30 +00001818
Georg Brandl7f01a132009-09-16 15:58:14 +00001819 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001820
1821 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1822 than a single name. The return value is a test suite which supports all
1823 the tests defined for each name.
1824
1825
1826 .. method:: getTestCaseNames(testCaseClass)
1827
1828 Return a sorted sequence of method names found within *testCaseClass*;
1829 this should be a subclass of :class:`TestCase`.
1830
Benjamin Petersond2397752009-06-27 23:45:02 +00001831
1832 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1833
Larry Hastings3732ed22014-03-15 21:13:56 -07001834 Find all the test modules by recursing into subdirectories from the
1835 specified start directory, and return a TestSuite object containing them.
1836 Only test files that match *pattern* will be loaded. (Using shell style
1837 pattern matching.) Only module names that are importable (i.e. are valid
1838 Python identifiers) will be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001839
1840 All test modules must be importable from the top level of the project. If
1841 the start directory is not the top level directory then the top level
1842 directory must be specified separately.
1843
Barry Warsawd78742a2014-09-08 14:21:37 -04001844 If importing a module fails, for example due to a syntax error, then
1845 this will be recorded as a single error and discovery will continue. If
1846 the import failure is due to :exc:`SkipTest` being raised, it will be
1847 recorded as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001848
Barry Warsawd78742a2014-09-08 14:21:37 -04001849 If a package (a directory containing a file named :file:`__init__.py`) is
1850 found, the package will be checked for a ``load_tests`` function. If this
Robert Collinsbf2bda32014-11-05 03:09:01 +13001851 exists then it will be called
1852 ``package.load_tests(loader, tests, pattern)``. Test discovery takes care
1853 to ensure that a package is only checked for tests once during an
1854 invocation, even if the load_tests function itself calls
1855 ``loader.discover``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001856
Barry Warsawd78742a2014-09-08 14:21:37 -04001857 If ``load_tests`` exists then discovery does *not* recurse into the
1858 package, ``load_tests`` is responsible for loading all tests in the
1859 package.
Benjamin Petersond2397752009-06-27 23:45:02 +00001860
1861 The pattern is deliberately not stored as a loader attribute so that
1862 packages can continue discovery themselves. *top_level_dir* is stored so
1863 ``load_tests`` does not need to pass this argument in to
1864 ``loader.discover()``.
1865
Benjamin Petersonb48af542010-04-11 20:43:16 +00001866 *start_dir* can be a dotted module name as well as a directory.
1867
Georg Brandl853947a2010-01-31 18:53:23 +00001868 .. versionadded:: 3.2
1869
Ezio Melottieae2b382013-03-01 14:47:50 +02001870 .. versionchanged:: 3.4
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001871 Modules that raise :exc:`SkipTest` on import are recorded as skips,
Larry Hastings3732ed22014-03-15 21:13:56 -07001872 not errors.
1873 Discovery works for :term:`namespace packages <namespace package>`.
1874 Paths are sorted before being imported so that execution order is
1875 the same even if the underlying file system's ordering is not
1876 dependent on file name.
Michael Foord80cbc9e2013-03-18 17:50:12 -07001877
Barry Warsawd78742a2014-09-08 14:21:37 -04001878 .. versionchanged:: 3.5
1879 Found packages are now checked for ``load_tests`` regardless of
1880 whether their path matches *pattern*, because it is impossible for
1881 a package name to match the default pattern.
1882
Benjamin Petersond2397752009-06-27 23:45:02 +00001883
Benjamin Peterson52baa292009-03-24 00:56:30 +00001884 The following attributes of a :class:`TestLoader` can be configured either by
1885 subclassing or assignment on an instance:
1886
1887
1888 .. attribute:: testMethodPrefix
1889
1890 String giving the prefix of method names which will be interpreted as test
1891 methods. The default value is ``'test'``.
1892
1893 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1894 methods.
1895
1896
1897 .. attribute:: sortTestMethodsUsing
1898
1899 Function to be used to compare method names when sorting them in
1900 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1901
1902
1903 .. attribute:: suiteClass
1904
1905 Callable object that constructs a test suite from a list of tests. No
1906 methods on the resulting object are needed. The default value is the
1907 :class:`TestSuite` class.
1908
1909 This affects all the :meth:`loadTestsFrom\*` methods.
1910
Jonas Haag5b48dc62017-11-25 16:23:52 +01001911 .. attribute:: testNamePatterns
1912
1913 List of Unix shell-style wildcard test name patterns that test methods
1914 have to match to be included in test suites (see ``-v`` option).
1915
1916 If this attribute is not ``None`` (the default), all test methods to be
1917 included in test suites must match one of the patterns in this list.
1918 Note that matches are always performed using :meth:`fnmatch.fnmatchcase`,
1919 so unlike patterns passed to the ``-v`` option, simple substring patterns
1920 will have to be converted using ``*`` wildcards.
1921
1922 This affects all the :meth:`loadTestsFrom\*` methods.
1923
1924 .. versionadded:: 3.7
1925
Benjamin Peterson52baa292009-03-24 00:56:30 +00001926
Benjamin Peterson52baa292009-03-24 00:56:30 +00001927.. class:: TestResult
1928
1929 This class is used to compile information about which tests have succeeded
1930 and which have failed.
1931
1932 A :class:`TestResult` object stores the results of a set of tests. The
1933 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1934 properly recorded; test authors do not need to worry about recording the
1935 outcome of tests.
1936
1937 Testing frameworks built on top of :mod:`unittest` may want access to the
1938 :class:`TestResult` object generated by running a set of tests for reporting
1939 purposes; a :class:`TestResult` instance is returned by the
1940 :meth:`TestRunner.run` method for this purpose.
1941
1942 :class:`TestResult` instances have the following attributes that will be of
1943 interest when inspecting the results of running a set of tests:
1944
1945
1946 .. attribute:: errors
1947
1948 A list containing 2-tuples of :class:`TestCase` instances and strings
1949 holding formatted tracebacks. Each tuple represents a test which raised an
1950 unexpected exception.
1951
Benjamin Peterson52baa292009-03-24 00:56:30 +00001952 .. attribute:: failures
1953
1954 A list containing 2-tuples of :class:`TestCase` instances and strings
1955 holding formatted tracebacks. Each tuple represents a test where a failure
Ezio Melottie2202362013-09-07 15:19:30 +03001956 was explicitly signalled using the :meth:`TestCase.assert\*` methods.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001957
Benjamin Peterson52baa292009-03-24 00:56:30 +00001958 .. attribute:: skipped
1959
1960 A list containing 2-tuples of :class:`TestCase` instances and strings
1961 holding the reason for skipping the test.
1962
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001963 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001964
1965 .. attribute:: expectedFailures
1966
Georg Brandl6faee4e2010-09-21 14:48:28 +00001967 A list containing 2-tuples of :class:`TestCase` instances and strings
1968 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001969 of the test case.
1970
1971 .. attribute:: unexpectedSuccesses
1972
1973 A list containing :class:`TestCase` instances that were marked as expected
1974 failures, but succeeded.
1975
1976 .. attribute:: shouldStop
1977
1978 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1979
Benjamin Peterson52baa292009-03-24 00:56:30 +00001980 .. attribute:: testsRun
1981
1982 The total number of tests run so far.
1983
Georg Brandl12037202010-12-02 22:35:25 +00001984 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001985
1986 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1987 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1988 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1989 fails or errors. Any output is also attached to the failure / error message.
1990
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001991 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001992
Benjamin Petersonb48af542010-04-11 20:43:16 +00001993 .. attribute:: failfast
1994
1995 If set to true :meth:`stop` will be called on the first failure or error,
1996 halting the test run.
1997
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001998 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001999
Robert Collinsf0c819a2015-03-06 13:46:35 +13002000 .. attribute:: tb_locals
2001
2002 If set to true then local variables will be shown in tracebacks.
2003
2004 .. versionadded:: 3.5
Benjamin Petersonb48af542010-04-11 20:43:16 +00002005
Benjamin Peterson52baa292009-03-24 00:56:30 +00002006 .. method:: wasSuccessful()
2007
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00002008 Return ``True`` if all tests run so far have passed, otherwise returns
2009 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00002010
Gregory P. Smith5a6d4bf2014-01-20 01:11:18 -08002011 .. versionchanged:: 3.4
2012 Returns ``False`` if there were any :attr:`unexpectedSuccesses`
2013 from tests marked with the :func:`expectedFailure` decorator.
2014
Benjamin Peterson52baa292009-03-24 00:56:30 +00002015 .. method:: stop()
2016
2017 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00002018 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00002019 :class:`TestRunner` objects should respect this flag and return without
2020 running any additional tests.
2021
2022 For example, this feature is used by the :class:`TextTestRunner` class to
2023 stop the test framework when the user signals an interrupt from the
2024 keyboard. Interactive tools which provide :class:`TestRunner`
2025 implementations can use this in a similar manner.
2026
2027 The following methods of the :class:`TestResult` class are used to maintain
2028 the internal data structures, and may be extended in subclasses to support
2029 additional reporting requirements. This is particularly useful in building
2030 tools which support interactive reporting while tests are being run.
2031
2032
2033 .. method:: startTest(test)
2034
2035 Called when the test case *test* is about to be run.
2036
Benjamin Peterson52baa292009-03-24 00:56:30 +00002037 .. method:: stopTest(test)
2038
2039 Called after the test case *test* has been executed, regardless of the
2040 outcome.
2041
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04002042 .. method:: startTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002043
2044 Called once before any tests are executed.
2045
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02002046 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002047
2048
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04002049 .. method:: stopTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002050
Ezio Melotti176d6c42010-01-27 20:58:07 +00002051 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002052
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02002053 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002054
2055
Benjamin Peterson52baa292009-03-24 00:56:30 +00002056 .. method:: addError(test, err)
2057
Ezio Melottie64a91a2013-09-07 15:23:36 +03002058 Called when the test case *test* raises an unexpected exception. *err* is a
Benjamin Peterson52baa292009-03-24 00:56:30 +00002059 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
2060 traceback)``.
2061
2062 The default implementation appends a tuple ``(test, formatted_err)`` to
2063 the instance's :attr:`errors` attribute, where *formatted_err* is a
2064 formatted traceback derived from *err*.
2065
2066
2067 .. method:: addFailure(test, err)
2068
Benjamin Petersond2397752009-06-27 23:45:02 +00002069 Called when the test case *test* signals a failure. *err* is a tuple of
2070 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00002071
2072 The default implementation appends a tuple ``(test, formatted_err)`` to
2073 the instance's :attr:`failures` attribute, where *formatted_err* is a
2074 formatted traceback derived from *err*.
2075
2076
2077 .. method:: addSuccess(test)
2078
2079 Called when the test case *test* succeeds.
2080
2081 The default implementation does nothing.
2082
2083
2084 .. method:: addSkip(test, reason)
2085
2086 Called when the test case *test* is skipped. *reason* is the reason the
2087 test gave for skipping.
2088
2089 The default implementation appends a tuple ``(test, reason)`` to the
2090 instance's :attr:`skipped` attribute.
2091
2092
2093 .. method:: addExpectedFailure(test, err)
2094
2095 Called when the test case *test* fails, but was marked with the
2096 :func:`expectedFailure` decorator.
2097
2098 The default implementation appends a tuple ``(test, formatted_err)`` to
2099 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
2100 is a formatted traceback derived from *err*.
2101
2102
2103 .. method:: addUnexpectedSuccess(test)
2104
2105 Called when the test case *test* was marked with the
2106 :func:`expectedFailure` decorator, but succeeded.
2107
2108 The default implementation appends the test to the instance's
2109 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00002110
Georg Brandl67b21b72010-08-17 15:07:14 +00002111
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01002112 .. method:: addSubTest(test, subtest, outcome)
2113
2114 Called when a subtest finishes. *test* is the test case
2115 corresponding to the test method. *subtest* is a custom
2116 :class:`TestCase` instance describing the subtest.
2117
2118 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
2119 it failed with an exception where *outcome* is a tuple of the form
2120 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
2121
2122 The default implementation does nothing when the outcome is a
2123 success, and records subtest failures as normal failures.
2124
2125 .. versionadded:: 3.4
2126
2127
Michael Foord34c94622010-02-10 15:51:42 +00002128.. class:: TextTestResult(stream, descriptions, verbosity)
2129
Georg Brandl67b21b72010-08-17 15:07:14 +00002130 A concrete implementation of :class:`TestResult` used by the
2131 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00002132
Georg Brandl67b21b72010-08-17 15:07:14 +00002133 .. versionadded:: 3.2
2134 This class was previously named ``_TextTestResult``. The old name still
2135 exists as an alias but is deprecated.
2136
Georg Brandl116aa622007-08-15 14:28:22 +00002137
2138.. data:: defaultTestLoader
2139
2140 Instance of the :class:`TestLoader` class intended to be shared. If no
2141 customization of the :class:`TestLoader` is needed, this instance can be used
2142 instead of repeatedly creating new instances.
2143
2144
Ezio Melotti9c939bc2013-05-07 09:46:30 +03002145.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \
Robert Collinsf0c819a2015-03-06 13:46:35 +13002146 buffer=False, resultclass=None, warnings=None, *, tb_locals=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002147
Michael Foordd218e952011-01-03 12:55:11 +00002148 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02002149 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00002150 has a few configurable parameters, but is essentially very simple. Graphical
Robert Collinsf0c819a2015-03-06 13:46:35 +13002151 applications which run test suites should provide alternate implementations. Such
2152 implementations should accept ``**kwargs`` as the interface to construct runners
2153 changes when features are added to unittest.
Georg Brandl116aa622007-08-15 14:28:22 +00002154
Ezio Melotti60901872010-12-01 00:56:10 +00002155 By default this runner shows :exc:`DeprecationWarning`,
Senthil Kumaran409ea5d2014-02-08 14:28:03 -08002156 :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and
Larry Hastingsad88d7a2014-02-10 04:26:10 -08002157 :exc:`ImportWarning` even if they are :ref:`ignored by default
2158 <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest
2159 methods <deprecated-aliases>` are also special-cased and, when the warning
2160 filters are ``'default'`` or ``'always'``, they will appear only once
2161 per-module, in order to avoid too many warning messages. This behavior can
Martin Panterb8c5f542016-10-30 04:20:23 +00002162 be overridden using Python's :option:`!-Wd` or :option:`!-Wa` options
2163 (see :ref:`Warning control <using-on-warnings>`) and leaving
Larry Hastingsad88d7a2014-02-10 04:26:10 -08002164 *warnings* to ``None``.
Ezio Melotti60901872010-12-01 00:56:10 +00002165
Michael Foordd218e952011-01-03 12:55:11 +00002166 .. versionchanged:: 3.2
2167 Added the ``warnings`` argument.
2168
2169 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02002170 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00002171 than import time.
2172
Robert Collinsf0c819a2015-03-06 13:46:35 +13002173 .. versionchanged:: 3.5
2174 Added the tb_locals parameter.
2175
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002176 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00002177
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002178 This method returns the instance of ``TestResult`` used by :meth:`run`.
2179 It is not intended to be called directly, but can be overridden in
2180 subclasses to provide a custom ``TestResult``.
2181
Michael Foord34c94622010-02-10 15:51:42 +00002182 ``_makeResult()`` instantiates the class or callable passed in the
2183 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00002184 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00002185 The result class is instantiated with the following arguments::
2186
2187 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002188
Michael Foord4d1639f2013-12-29 23:38:55 +00002189 .. method:: run(test)
2190
Julien Palard6e240dd2019-02-22 09:22:27 +01002191 This method is the main public interface to the ``TextTestRunner``. This
Michael Foord4d1639f2013-12-29 23:38:55 +00002192 method takes a :class:`TestSuite` or :class:`TestCase` instance. A
2193 :class:`TestResult` is created by calling
2194 :func:`_makeResult` and the test(s) are run and the
2195 results printed to stdout.
2196
Ezio Melotti60901872010-12-01 00:56:10 +00002197
Georg Brandl419e3de2010-12-01 15:44:25 +00002198.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02002199 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00002200 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002201
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002202 A command-line program that loads a set of tests from *module* and runs them;
2203 this is primarily for making test modules conveniently executable.
2204 The simplest use for this function is to include the following line at the
2205 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00002206
2207 if __name__ == '__main__':
2208 unittest.main()
2209
Benjamin Petersond2397752009-06-27 23:45:02 +00002210 You can run tests with more detailed information by passing in the verbosity
2211 argument::
2212
2213 if __name__ == '__main__':
2214 unittest.main(verbosity=2)
2215
R David Murray6e731b02014-01-02 13:43:02 -05002216 The *defaultTest* argument is either the name of a single test or an
2217 iterable of test names to run if no test names are specified via *argv*. If
2218 not specified or ``None`` and no test names are provided via *argv*, all
2219 tests found in *module* are run.
R David Murray12e930f2014-01-02 13:37:26 -05002220
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002221 The *argv* argument can be a list of options passed to the program, with the
2222 first element being the program name. If not specified or ``None``,
2223 the values of :data:`sys.argv` are used.
2224
Georg Brandl116aa622007-08-15 14:28:22 +00002225 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002226 created instance of it. By default ``main`` calls :func:`sys.exit` with
2227 an exit code indicating success or failure of the tests run.
2228
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002229 The *testLoader* argument has to be a :class:`TestLoader` instance,
2230 and defaults to :data:`defaultTestLoader`.
2231
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002232 ``main`` supports being used from the interactive interpreter by passing in the
2233 argument ``exit=False``. This displays the result on standard output without
2234 calling :func:`sys.exit`::
2235
2236 >>> from unittest import main
2237 >>> main(module='test_module', exit=False)
2238
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002239 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00002240 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002241
Zachary Waref0a71cf2016-08-30 00:16:13 -05002242 The *warnings* argument specifies the :ref:`warning filter <warning-filter>`
Ezio Melotti60901872010-12-01 00:56:10 +00002243 that should be used while running the tests. If it's not specified, it will
Martin Panterb8c5f542016-10-30 04:20:23 +00002244 remain ``None`` if a :option:`!-W` option is passed to :program:`python`
2245 (see :ref:`Warning control <using-on-warnings>`),
Ezio Melotti60901872010-12-01 00:56:10 +00002246 otherwise it will be set to ``'default'``.
2247
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002248 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
2249 This stores the result of the tests run as the ``result`` attribute.
2250
Éric Araujo971dc012010-12-16 03:13:05 +00002251 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002252 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00002253
Georg Brandl853947a2010-01-31 18:53:23 +00002254 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002255 The *verbosity*, *failfast*, *catchbreak*, *buffer*
2256 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00002257
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08002258 .. versionchanged:: 3.4
2259 The *defaultTest* parameter was changed to also accept an iterable of
2260 test names.
2261
Benjamin Petersond2397752009-06-27 23:45:02 +00002262
2263load_tests Protocol
2264###################
2265
Georg Brandl853947a2010-01-31 18:53:23 +00002266.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002267
Benjamin Petersond2397752009-06-27 23:45:02 +00002268Modules or packages can customize how tests are loaded from them during normal
2269test runs or test discovery by implementing a function called ``load_tests``.
2270
2271If a test module defines ``load_tests`` it will be called by
2272:meth:`TestLoader.loadTestsFromModule` with the following arguments::
2273
Barry Warsawd78742a2014-09-08 14:21:37 -04002274 load_tests(loader, standard_tests, pattern)
2275
2276where *pattern* is passed straight through from ``loadTestsFromModule``. It
2277defaults to ``None``.
Benjamin Petersond2397752009-06-27 23:45:02 +00002278
2279It should return a :class:`TestSuite`.
2280
2281*loader* is the instance of :class:`TestLoader` doing the loading.
2282*standard_tests* are the tests that would be loaded by default from the
2283module. It is common for test modules to only want to add or remove tests
2284from the standard set of tests.
2285The third argument is used when loading packages as part of test discovery.
2286
2287A typical ``load_tests`` function that loads tests from a specific set of
2288:class:`TestCase` classes may look like::
2289
2290 test_cases = (TestCase1, TestCase2, TestCase3)
2291
2292 def load_tests(loader, tests, pattern):
2293 suite = TestSuite()
2294 for test_class in test_cases:
2295 tests = loader.loadTestsFromTestCase(test_class)
2296 suite.addTests(tests)
2297 return suite
2298
Barry Warsawd78742a2014-09-08 14:21:37 -04002299If discovery is started in a directory containing a package, either from the
2300command line or by calling :meth:`TestLoader.discover`, then the package
2301:file:`__init__.py` will be checked for ``load_tests``. If that function does
2302not exist, discovery will recurse into the package as though it were just
2303another directory. Otherwise, discovery of the package's tests will be left up
2304to ``load_tests`` which is called with the following arguments::
Benjamin Petersond2397752009-06-27 23:45:02 +00002305
2306 load_tests(loader, standard_tests, pattern)
2307
2308This should return a :class:`TestSuite` representing all the tests
2309from the package. (``standard_tests`` will only contain tests
2310collected from :file:`__init__.py`.)
2311
2312Because the pattern is passed into ``load_tests`` the package is free to
2313continue (and potentially modify) test discovery. A 'do nothing'
2314``load_tests`` function for a test package would look like::
2315
2316 def load_tests(loader, standard_tests, pattern):
2317 # top level directory cached on loader instance
2318 this_dir = os.path.dirname(__file__)
2319 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2320 standard_tests.addTests(package_tests)
2321 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002322
Barry Warsawd78742a2014-09-08 14:21:37 -04002323.. versionchanged:: 3.5
2324 Discovery no longer checks package names for matching *pattern* due to the
2325 impossibility of package names matching the default pattern.
2326
2327
Benjamin Petersonb48af542010-04-11 20:43:16 +00002328
2329Class and Module Fixtures
2330-------------------------
2331
2332Class and module level fixtures are implemented in :class:`TestSuite`. When
2333the test suite encounters a test from a new class then :meth:`tearDownClass`
2334from the previous class (if there is one) is called, followed by
2335:meth:`setUpClass` from the new class.
2336
2337Similarly if a test is from a different module from the previous test then
2338``tearDownModule`` from the previous module is run, followed by
2339``setUpModule`` from the new module.
2340
2341After all the tests have run the final ``tearDownClass`` and
2342``tearDownModule`` are run.
2343
2344Note that shared fixtures do not play well with [potential] features like test
2345parallelization and they break test isolation. They should be used with care.
2346
2347The default ordering of tests created by the unittest test loaders is to group
2348all tests from the same modules and classes together. This will lead to
2349``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2350module. If you randomize the order, so that tests from different modules and
2351classes are adjacent to each other, then these shared fixture functions may be
2352called multiple times in a single test run.
2353
2354Shared fixtures are not intended to work with suites with non-standard
2355ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2356support shared fixtures.
2357
2358If there are any exceptions raised during one of the shared fixture functions
2359the test is reported as an error. Because there is no corresponding test
2360instance an ``_ErrorHolder`` object (that has the same interface as a
2361:class:`TestCase`) is created to represent the error. If you are just using
2362the standard unittest test runner then this detail doesn't matter, but if you
2363are a framework author it may be relevant.
2364
2365
2366setUpClass and tearDownClass
2367~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2368
2369These must be implemented as class methods::
2370
2371 import unittest
2372
2373 class Test(unittest.TestCase):
2374 @classmethod
2375 def setUpClass(cls):
2376 cls._connection = createExpensiveConnectionObject()
2377
2378 @classmethod
2379 def tearDownClass(cls):
2380 cls._connection.destroy()
2381
2382If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2383then you must call up to them yourself. The implementations in
2384:class:`TestCase` are empty.
2385
2386If an exception is raised during a ``setUpClass`` then the tests in the class
2387are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002388have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002389:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002390instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002391
2392
2393setUpModule and tearDownModule
2394~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2395
2396These should be implemented as functions::
2397
2398 def setUpModule():
2399 createConnection()
2400
2401 def tearDownModule():
2402 closeConnection()
2403
2404If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002405module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002406:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002407instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002408
Lisa Roach0f221d02018-11-08 18:34:33 -08002409To add cleanup code that must be run even in the case of an exception, use
2410``addModuleCleanup``:
2411
2412
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002413.. function:: addModuleCleanup(function, /, *args, **kwargs)
Lisa Roach0f221d02018-11-08 18:34:33 -08002414
2415 Add a function to be called after :func:`tearDownModule` to cleanup
2416 resources used during the test class. Functions will be called in reverse
2417 order to the order they are added (:abbr:`LIFO (last-in, first-out)`).
2418 They are called with any arguments and keyword arguments passed into
2419 :meth:`addModuleCleanup` when they are added.
2420
2421 If :meth:`setUpModule` fails, meaning that :func:`tearDownModule` is not
2422 called, then any cleanup functions added will still be called.
2423
2424 .. versionadded:: 3.8
2425
2426
2427.. function:: doModuleCleanups()
2428
2429 This function is called unconditionally after :func:`tearDownModule`, or
2430 after :func:`setUpModule` if :func:`setUpModule` raises an exception.
2431
2432 It is responsible for calling all the cleanup functions added by
2433 :func:`addCleanupModule`. If you need cleanup functions to be called
2434 *prior* to :func:`tearDownModule` then you can call
2435 :func:`doModuleCleanups` yourself.
2436
2437 :func:`doModuleCleanups` pops methods off the stack of cleanup
2438 functions one at a time, so it can be called at any time.
2439
2440 .. versionadded:: 3.8
Benjamin Petersonb48af542010-04-11 20:43:16 +00002441
2442Signal Handling
2443---------------
2444
Georg Brandl419e3de2010-12-01 15:44:25 +00002445.. versionadded:: 3.2
2446
Éric Araujo8acb67c2010-11-26 23:31:07 +00002447The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002448along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2449more friendly handling of control-C during a test run. With catch break
2450behavior enabled control-C will allow the currently running test to complete,
2451and the test run will then end and report all the results so far. A second
2452control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002453
Michael Foordde4ceab2010-04-25 19:53:49 +00002454The control-c handling signal handler attempts to remain compatible with code or
2455tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2456handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2457i.e. it has been replaced by the system under test and delegated to, then it
2458calls the default handler. This will normally be the expected behavior by code
2459that replaces an installed handler and delegates to it. For individual tests
2460that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2461decorator can be used.
2462
2463There are a few utility functions for framework authors to enable control-c
2464handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002465
2466.. function:: installHandler()
2467
2468 Install the control-c handler. When a :const:`signal.SIGINT` is received
2469 (usually in response to the user pressing control-c) all registered results
2470 have :meth:`~TestResult.stop` called.
2471
Michael Foord469b1f02010-04-26 23:41:26 +00002472
Benjamin Petersonb48af542010-04-11 20:43:16 +00002473.. function:: registerResult(result)
2474
2475 Register a :class:`TestResult` object for control-c handling. Registering a
2476 result stores a weak reference to it, so it doesn't prevent the result from
2477 being garbage collected.
2478
Michael Foordde4ceab2010-04-25 19:53:49 +00002479 Registering a :class:`TestResult` object has no side-effects if control-c
2480 handling is not enabled, so test frameworks can unconditionally register
2481 all results they create independently of whether or not handling is enabled.
2482
Michael Foord469b1f02010-04-26 23:41:26 +00002483
Benjamin Petersonb48af542010-04-11 20:43:16 +00002484.. function:: removeResult(result)
2485
2486 Remove a registered result. Once a result has been removed then
2487 :meth:`~TestResult.stop` will no longer be called on that result object in
2488 response to a control-c.
2489
Michael Foord469b1f02010-04-26 23:41:26 +00002490
Michael Foordde4ceab2010-04-25 19:53:49 +00002491.. function:: removeHandler(function=None)
2492
2493 When called without arguments this function removes the control-c handler
2494 if it has been installed. This function can also be used as a test decorator
Mariatta98f42aa2018-02-23 09:51:11 -08002495 to temporarily remove the handler while the test is being executed::
Michael Foordde4ceab2010-04-25 19:53:49 +00002496
2497 @unittest.removeHandler
2498 def test_signal_handling(self):
2499 ...