blob: e52f140029c57ab56ac683c68ab09cd60801f55f [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
30 tests, and any associate cleanup actions. This may involve, for example,
31 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
Berker Peksaga1a14092014-12-28 18:48:33 +020059 `Nose <https://nose.readthedocs.org/en/latest/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000060 Third-party unittest frameworks with a lighter-weight syntax for writing
61 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
Robert Collinsf0c819a2015-03-06 13:46:35 +1300222.. cmdoption:: --locals
223
224 Show local variables in tracebacks.
225
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000226.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000227 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000228
Robert Collinsf0c819a2015-03-06 13:46:35 +1300229.. versionadded:: 3.5
230 The command-line option ``--locals``.
231
Benjamin Petersonb48af542010-04-11 20:43:16 +0000232The command line can also be used for test discovery, for running all of the
233tests in a project or just a subset.
234
235
236.. _unittest-test-discovery:
237
238Test Discovery
239--------------
240
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000241.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000242
Ezio Melotti3d995842011-03-08 16:17:35 +0200243Unittest supports simple test discovery. In order to be compatible with test
244discovery, all of the test files must be :ref:`modules <tut-modules>` or
Larry Hastings3732ed22014-03-15 21:13:56 -0700245:ref:`packages <tut-packages>` (including :term:`namespace packages
246<namespace package>`) importable from the top-level directory of
247the project (this means that their filenames must be valid :ref:`identifiers
248<identifiers>`).
Benjamin Petersonb48af542010-04-11 20:43:16 +0000249
250Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000251used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000252
253 cd project_directory
254 python -m unittest discover
255
Michael Foord086f3082010-11-21 21:28:01 +0000256.. note::
257
258 As a shortcut, ``python -m unittest`` is the equivalent of
259 ``python -m unittest discover``. If you want to pass arguments to test
Éric Araujo941afed2011-09-01 02:47:34 +0200260 discovery the ``discover`` sub-command must be used explicitly.
Michael Foord086f3082010-11-21 21:28:01 +0000261
Benjamin Petersonb48af542010-04-11 20:43:16 +0000262The ``discover`` sub-command has the following options:
263
Éric Araujo713d3032010-11-18 16:38:46 +0000264.. program:: unittest discover
265
266.. cmdoption:: -v, --verbose
267
268 Verbose output
269
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800270.. cmdoption:: -s, --start-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000271
Éric Araujo941afed2011-09-01 02:47:34 +0200272 Directory to start discovery (``.`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000273
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800274.. cmdoption:: -p, --pattern pattern
Éric Araujo713d3032010-11-18 16:38:46 +0000275
Éric Araujo941afed2011-09-01 02:47:34 +0200276 Pattern to match test files (``test*.py`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000277
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800278.. cmdoption:: -t, --top-level-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000279
280 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000281
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000282The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
283as positional arguments in that order. The following two command lines
284are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000285
Robert Collinsa2b00552015-08-24 12:14:28 +1200286 python -m unittest discover -s project_directory -p "*_test.py"
287 python -m unittest discover project_directory "*_test.py"
Benjamin Petersonb48af542010-04-11 20:43:16 +0000288
Michael Foord16f3e902010-05-08 15:13:42 +0000289As well as being a path it is possible to pass a package name, for example
290``myproject.subpackage.test``, as the start directory. The package name you
291supply will then be imported and its location on the filesystem will be used
292as the start directory.
293
294.. caution::
295
Senthil Kumaran916bd382010-10-15 12:55:19 +0000296 Test discovery loads tests by importing them. Once test discovery has found
297 all the test files from the start directory you specify it turns the paths
298 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000299 imported as ``foo.bar.baz``.
300
301 If you have a package installed globally and attempt test discovery on
302 a different copy of the package then the import *could* happen from the
303 wrong place. If this happens test discovery will warn you and exit.
304
305 If you supply the start directory as a package name rather than a
306 path to a directory then discover assumes that whichever location it
307 imports from is the location you intended, so you will not get the
308 warning.
309
Benjamin Petersonb48af542010-04-11 20:43:16 +0000310Test modules and packages can customize test loading and discovery by through
311the `load_tests protocol`_.
312
Larry Hastings3732ed22014-03-15 21:13:56 -0700313.. versionchanged:: 3.4
314 Test discovery supports :term:`namespace packages <namespace package>`.
315
Benjamin Petersonb48af542010-04-11 20:43:16 +0000316
Georg Brandl116aa622007-08-15 14:28:22 +0000317.. _organizing-tests:
318
319Organizing test code
320--------------------
321
322The basic building blocks of unit testing are :dfn:`test cases` --- single
323scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000324test cases are represented by :class:`unittest.TestCase` instances.
325To make your own test cases you must write subclasses of
326:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000327
Georg Brandl116aa622007-08-15 14:28:22 +0000328The testing code of a :class:`TestCase` instance should be entirely self
329contained, such that it can be run either in isolation or in arbitrary
330combination with any number of other test cases.
331
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100332The simplest :class:`TestCase` subclass will simply implement a test method
333(i.e. a method whose name starts with ``test``) in order to perform specific
334testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336 import unittest
337
338 class DefaultWidgetSizeTestCase(unittest.TestCase):
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100339 def test_default_widget_size(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000340 widget = Widget('The widget')
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100341 self.assertEqual(widget.size(), (50, 50))
Georg Brandl116aa622007-08-15 14:28:22 +0000342
Sandro Tosi41b24042012-01-21 10:59:37 +0100343Note that in order to test something, we use one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000344methods provided by the :class:`TestCase` base class. If the test fails, an
345exception will be raised, and :mod:`unittest` will identify the test case as a
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100346:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100348Tests can be numerous, and their set-up can be repetitive. Luckily, we
349can factor out set-up code by implementing a method called
350:meth:`~TestCase.setUp`, which the testing framework will automatically
351call for every single test we run::
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353 import unittest
354
Berker Peksagab75e022016-08-06 03:00:03 +0300355 class WidgetTestCase(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000356 def setUp(self):
357 self.widget = Widget('The widget')
358
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100359 def test_default_widget_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000360 self.assertEqual(self.widget.size(), (50,50),
361 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100363 def test_widget_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000364 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000365 self.assertEqual(self.widget.size(), (100,150),
366 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000367
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100368.. note::
369 The order in which the various tests will be run is determined
370 by sorting the test method names with respect to the built-in
371 ordering for strings.
372
Benjamin Peterson52baa292009-03-24 00:56:30 +0000373If the :meth:`~TestCase.setUp` method raises an exception while the test is
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100374running, the framework will consider the test to have suffered an error, and
375the test method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Benjamin Peterson52baa292009-03-24 00:56:30 +0000377Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100378after the test method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380 import unittest
381
Berker Peksagab75e022016-08-06 03:00:03 +0300382 class WidgetTestCase(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000383 def setUp(self):
384 self.widget = Widget('The widget')
385
386 def tearDown(self):
387 self.widget.dispose()
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100389If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be
390run whether the test method succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000391
392Such a working environment for the testing code is called a :dfn:`fixture`.
393
Georg Brandl116aa622007-08-15 14:28:22 +0000394Test case instances are grouped together according to the features they test.
395:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100396represented by :mod:`unittest`'s :class:`TestSuite` class. In most cases,
397calling :func:`unittest.main` will do the right thing and collect all the
398module's test cases for you, and then execute them.
Georg Brandl116aa622007-08-15 14:28:22 +0000399
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100400However, should you want to customize the building of your test suite,
401you can do it yourself::
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403 def suite():
404 suite = unittest.TestSuite()
Berker Peksag92551042017-10-13 06:41:57 +0300405 suite.addTest(WidgetTestCase('test_default_widget_size'))
406 suite.addTest(WidgetTestCase('test_widget_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000407 return suite
408
Berker Peksag92551042017-10-13 06:41:57 +0300409 if __name__ == '__main__':
410 runner = unittest.TextTestRunner()
411 runner.run(suite())
412
Georg Brandl116aa622007-08-15 14:28:22 +0000413You can place the definitions of test cases and test suites in the same modules
414as the code they are to test (such as :file:`widget.py`), but there are several
415advantages to placing the test code in a separate module, such as
416:file:`test_widget.py`:
417
418* The test module can be run standalone from the command line.
419
420* The test code can more easily be separated from shipped code.
421
422* There is less temptation to change test code to fit the code it tests without
423 a good reason.
424
425* Test code should be modified much less frequently than the code it tests.
426
427* Tested code can be refactored more easily.
428
429* Tests for modules written in C must be in separate modules anyway, so why not
430 be consistent?
431
432* If the testing strategy changes, there is no need to change the source code.
433
434
435.. _legacy-unit-tests:
436
437Re-using old test code
438----------------------
439
440Some users will find that they have existing test code that they would like to
441run from :mod:`unittest`, without converting every old test function to a
442:class:`TestCase` subclass.
443
444For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
445This subclass of :class:`TestCase` can be used to wrap an existing test
446function. Set-up and tear-down functions can also be provided.
447
448Given the following test function::
449
450 def testSomething():
451 something = makeSomething()
452 assert something.name is not None
453 # ...
454
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100455one can create an equivalent test case instance as follows, with optional
456set-up and tear-down methods::
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458 testcase = unittest.FunctionTestCase(testSomething,
459 setUp=makeSomethingDB,
460 tearDown=deleteSomethingDB)
461
Georg Brandl116aa622007-08-15 14:28:22 +0000462.. note::
463
Benjamin Petersond2397752009-06-27 23:45:02 +0000464 Even though :class:`FunctionTestCase` can be used to quickly convert an
465 existing test base over to a :mod:`unittest`\ -based system, this approach is
466 not recommended. Taking the time to set up proper :class:`TestCase`
467 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000468
Benjamin Peterson52baa292009-03-24 00:56:30 +0000469In some cases, the existing tests may have been written using the :mod:`doctest`
470module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
471automatically build :class:`unittest.TestSuite` instances from the existing
472:mod:`doctest`\ -based tests.
473
Georg Brandl116aa622007-08-15 14:28:22 +0000474
Benjamin Peterson5254c042009-03-23 22:25:03 +0000475.. _unittest-skipping:
476
477Skipping tests and expected failures
478------------------------------------
479
Michael Foordf5c851a2010-02-05 21:48:03 +0000480.. versionadded:: 3.1
481
Benjamin Peterson5254c042009-03-23 22:25:03 +0000482Unittest supports skipping individual test methods and even whole classes of
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200483tests. In addition, it supports marking a test as an "expected failure," a test
Benjamin Peterson5254c042009-03-23 22:25:03 +0000484that is broken and will fail, but shouldn't be counted as a failure on a
485:class:`TestResult`.
486
487Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
488or one of its conditional variants.
489
Ezio Melottifed69ba2013-03-01 21:26:04 +0200490Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000491
492 class MyTestCase(unittest.TestCase):
493
494 @unittest.skip("demonstrating skipping")
495 def test_nothing(self):
496 self.fail("shouldn't happen")
497
Benjamin Petersond2397752009-06-27 23:45:02 +0000498 @unittest.skipIf(mylib.__version__ < (1, 3),
499 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000500 def test_format(self):
501 # Tests that work for only a certain version of the library.
502 pass
503
504 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
505 def test_windows_support(self):
506 # windows specific testing code
507 pass
508
Ezio Melottifed69ba2013-03-01 21:26:04 +0200509This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000510
Benjamin Petersonded31c42009-03-30 15:04:16 +0000511 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000512 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000513 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000514
515 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000516 Ran 3 tests in 0.005s
517
518 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000519
Ezio Melottifed69ba2013-03-01 21:26:04 +0200520Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000521
Sandro Tosi317075d2012-03-31 18:34:59 +0200522 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000523 class MySkippedTestCase(unittest.TestCase):
524 def test_not_run(self):
525 pass
526
Benjamin Peterson52baa292009-03-24 00:56:30 +0000527:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
528that needs to be set up is not available.
529
Benjamin Peterson5254c042009-03-23 22:25:03 +0000530Expected failures use the :func:`expectedFailure` decorator. ::
531
532 class ExpectedFailureTestCase(unittest.TestCase):
533 @unittest.expectedFailure
534 def test_fail(self):
535 self.assertEqual(1, 0, "broken")
536
537It's easy to roll your own skipping decorators by making a decorator that calls
538:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottifed69ba2013-03-01 21:26:04 +0200539the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000540
541 def skipUnlessHasattr(obj, attr):
542 if hasattr(obj, attr):
543 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200544 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000545
546The following decorators implement test skipping and expected failures:
547
Georg Brandl8a1caa22010-07-29 16:01:11 +0000548.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000549
550 Unconditionally skip the decorated test. *reason* should describe why the
551 test is being skipped.
552
Georg Brandl8a1caa22010-07-29 16:01:11 +0000553.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000554
555 Skip the decorated test if *condition* is true.
556
Georg Brandl8a1caa22010-07-29 16:01:11 +0000557.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000558
Georg Brandl6faee4e2010-09-21 14:48:28 +0000559 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000560
Georg Brandl8a1caa22010-07-29 16:01:11 +0000561.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000562
563 Mark the test as an expected failure. If the test fails when run, the test
564 is not counted as a failure.
565
Ezio Melotti265281a2013-03-27 20:11:55 +0200566.. exception:: SkipTest(reason)
567
568 This exception is raised to skip a test.
569
570 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
571 decorators instead of raising this directly.
572
R David Murray42fa1102014-01-03 13:03:36 -0500573Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them.
574Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run.
575Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000576
Benjamin Peterson5254c042009-03-23 22:25:03 +0000577
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100578.. _subtests:
579
580Distinguishing test iterations using subtests
581---------------------------------------------
582
583.. versionadded:: 3.4
584
585When some of your tests differ only by a some very small differences, for
586instance some parameters, unittest allows you to distinguish them inside
587the body of a test method using the :meth:`~TestCase.subTest` context manager.
588
589For example, the following test::
590
591 class NumbersTest(unittest.TestCase):
592
593 def test_even(self):
594 """
595 Test that numbers between 0 and 5 are all even.
596 """
597 for i in range(0, 6):
598 with self.subTest(i=i):
599 self.assertEqual(i % 2, 0)
600
601will produce the following output::
602
603 ======================================================================
604 FAIL: test_even (__main__.NumbersTest) (i=1)
605 ----------------------------------------------------------------------
606 Traceback (most recent call last):
607 File "subtests.py", line 32, in test_even
608 self.assertEqual(i % 2, 0)
609 AssertionError: 1 != 0
610
611 ======================================================================
612 FAIL: test_even (__main__.NumbersTest) (i=3)
613 ----------------------------------------------------------------------
614 Traceback (most recent call last):
615 File "subtests.py", line 32, in test_even
616 self.assertEqual(i % 2, 0)
617 AssertionError: 1 != 0
618
619 ======================================================================
620 FAIL: test_even (__main__.NumbersTest) (i=5)
621 ----------------------------------------------------------------------
622 Traceback (most recent call last):
623 File "subtests.py", line 32, in test_even
624 self.assertEqual(i % 2, 0)
625 AssertionError: 1 != 0
626
627Without using a subtest, execution would stop after the first failure,
628and the error would be less easy to diagnose because the value of ``i``
629wouldn't be displayed::
630
631 ======================================================================
632 FAIL: test_even (__main__.NumbersTest)
633 ----------------------------------------------------------------------
634 Traceback (most recent call last):
635 File "subtests.py", line 32, in test_even
636 self.assertEqual(i % 2, 0)
637 AssertionError: 1 != 0
638
639
Georg Brandl116aa622007-08-15 14:28:22 +0000640.. _unittest-contents:
641
642Classes and functions
643---------------------
644
Benjamin Peterson52baa292009-03-24 00:56:30 +0000645This section describes in depth the API of :mod:`unittest`.
646
647
648.. _testcase-objects:
649
650Test cases
651~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Georg Brandl7f01a132009-09-16 15:58:14 +0000653.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000654
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100655 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000656 in the :mod:`unittest` universe. This class is intended to be used as a base
657 class, with specific tests being implemented by concrete subclasses. This class
658 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100659 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000660 kinds of failure.
661
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100662 Each instance of :class:`TestCase` will run a single base method: the method
Robert Collinse02f6c22015-07-23 06:37:26 +1200663 named *methodName*.
664 In most uses of :class:`TestCase`, you will neither change
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100665 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000666
Michael Foord1341bb02011-03-14 19:01:46 -0400667 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100668 :class:`TestCase` can be instantiated successfully without providing a
669 *methodName*. This makes it easier to experiment with :class:`TestCase`
670 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000671
672 :class:`TestCase` instances provide three groups of methods: one group used
673 to run the test, another used by the test implementation to check conditions
674 and report failures, and some inquiry methods allowing information about the
675 test itself to be gathered.
676
677 Methods in the first group (running the test) are:
678
Benjamin Peterson52baa292009-03-24 00:56:30 +0000679 .. method:: setUp()
680
681 Method called to prepare the test fixture. This is called immediately
Terry Jan Reedy7f84d1e2014-04-15 23:44:14 -0400682 before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`,
683 any exception raised by this method will be considered an error rather than
Terry Jan Reedy6ac42402014-04-15 23:38:18 -0400684 a test failure. The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000685
686
687 .. method:: tearDown()
688
689 Method called immediately after the test method has been called and the
690 result recorded. This is called even if the test method raised an
691 exception, so the implementation in subclasses may need to be particularly
Ezio Melotti8dea74f2016-03-13 09:40:09 +0200692 careful about checking internal state. Any exception, other than
693 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
694 considered an additional error rather than a test failure (thus increasing
695 the total number of reported errors). This method will only be called if
696 the :meth:`setUp` succeeds, regardless of the outcome of the test method.
697 The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000698
699
Benjamin Petersonb48af542010-04-11 20:43:16 +0000700 .. method:: setUpClass()
701
702 A class method called before tests in an individual class run.
703 ``setUpClass`` is called with the class as the only argument
704 and must be decorated as a :func:`classmethod`::
705
706 @classmethod
707 def setUpClass(cls):
708 ...
709
710 See `Class and Module Fixtures`_ for more details.
711
712 .. versionadded:: 3.2
713
714
715 .. method:: tearDownClass()
716
717 A class method called after tests in an individual class have run.
718 ``tearDownClass`` is called with the class as the only argument
719 and must be decorated as a :meth:`classmethod`::
720
721 @classmethod
722 def tearDownClass(cls):
723 ...
724
725 See `Class and Module Fixtures`_ for more details.
726
727 .. versionadded:: 3.2
728
729
Georg Brandl7f01a132009-09-16 15:58:14 +0000730 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000731
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100732 Run the test, collecting the result into the :class:`TestResult` object
733 passed as *result*. If *result* is omitted or ``None``, a temporary
734 result object is created (by calling the :meth:`defaultTestResult`
735 method) and used. The result object is returned to :meth:`run`'s
736 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000737
738 The same effect may be had by simply calling the :class:`TestCase`
739 instance.
740
Michael Foord1341bb02011-03-14 19:01:46 -0400741 .. versionchanged:: 3.3
742 Previous versions of ``run`` did not return the result. Neither did
743 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000744
Benjamin Petersone549ead2009-03-28 21:42:05 +0000745 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000746
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000747 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000748 test. See :ref:`unittest-skipping` for more information.
749
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000750 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000751
Benjamin Peterson52baa292009-03-24 00:56:30 +0000752
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100753 .. method:: subTest(msg=None, **params)
754
755 Return a context manager which executes the enclosed code block as a
756 subtest. *msg* and *params* are optional, arbitrary values which are
757 displayed whenever a subtest fails, allowing you to identify them
758 clearly.
759
760 A test case can contain any number of subtest declarations, and
761 they can be arbitrarily nested.
762
763 See :ref:`subtests` for more information.
764
765 .. versionadded:: 3.4
766
767
Benjamin Peterson52baa292009-03-24 00:56:30 +0000768 .. method:: debug()
769
770 Run the test without collecting the result. This allows exceptions raised
771 by the test to be propagated to the caller, and can be used to support
772 running tests under a debugger.
773
Ezio Melotti22170ed2010-11-20 09:57:27 +0000774 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000775
Ezio Melottif418db22016-01-12 11:03:31 +0200776 The :class:`TestCase` class provides several assert methods to check for and
777 report failures. The following table lists the most commonly used methods
778 (see the tables below for more assert methods):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000779
Ezio Melotti4370b302010-11-03 20:39:14 +0000780 +-----------------------------------------+-----------------------------+---------------+
781 | Method | Checks that | New in |
782 +=========================================+=============================+===============+
783 | :meth:`assertEqual(a, b) | ``a == b`` | |
784 | <TestCase.assertEqual>` | | |
785 +-----------------------------------------+-----------------------------+---------------+
786 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
787 | <TestCase.assertNotEqual>` | | |
788 +-----------------------------------------+-----------------------------+---------------+
789 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
790 | <TestCase.assertTrue>` | | |
791 +-----------------------------------------+-----------------------------+---------------+
792 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
793 | <TestCase.assertFalse>` | | |
794 +-----------------------------------------+-----------------------------+---------------+
795 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
796 | <TestCase.assertIs>` | | |
797 +-----------------------------------------+-----------------------------+---------------+
798 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
799 | <TestCase.assertIsNot>` | | |
800 +-----------------------------------------+-----------------------------+---------------+
801 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
802 | <TestCase.assertIsNone>` | | |
803 +-----------------------------------------+-----------------------------+---------------+
804 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
805 | <TestCase.assertIsNotNone>` | | |
806 +-----------------------------------------+-----------------------------+---------------+
807 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
808 | <TestCase.assertIn>` | | |
809 +-----------------------------------------+-----------------------------+---------------+
810 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
811 | <TestCase.assertNotIn>` | | |
812 +-----------------------------------------+-----------------------------+---------------+
813 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
814 | <TestCase.assertIsInstance>` | | |
815 +-----------------------------------------+-----------------------------+---------------+
816 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
817 | <TestCase.assertNotIsInstance>` | | |
818 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000819
Ezio Melottib4dc2502011-05-06 15:01:41 +0300820 All the assert methods accept a *msg* argument that, if specified, is used
821 as the error message on failure (see also :data:`longMessage`).
822 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
823 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
824 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000825
Michael Foorde180d392011-01-28 19:51:48 +0000826 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000827
Michael Foorde180d392011-01-28 19:51:48 +0000828 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000829 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000830
Michael Foorde180d392011-01-28 19:51:48 +0000831 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000832 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200833 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000834 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000835 error message (see also the :ref:`list of type-specific methods
836 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000837
Raymond Hettinger35a88362009-04-09 00:08:24 +0000838 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200839 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000840
Michael Foord28a817e2010-02-09 00:03:57 +0000841 .. versionchanged:: 3.2
842 :meth:`assertMultiLineEqual` added as the default type equality
843 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000844
Benjamin Peterson52baa292009-03-24 00:56:30 +0000845
Michael Foorde180d392011-01-28 19:51:48 +0000846 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000847
Michael Foorde180d392011-01-28 19:51:48 +0000848 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000849 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000850
Ezio Melotti4370b302010-11-03 20:39:14 +0000851 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000852 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000853
Ezio Melotti4841fd62010-11-05 15:43:40 +0000854 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000855
Ezio Melotti4841fd62010-11-05 15:43:40 +0000856 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
857 is True`` (use ``assertIs(expr, True)`` for the latter). This method
858 should also be avoided when more specific methods are available (e.g.
859 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
860 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000861
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000862
Michael Foorde180d392011-01-28 19:51:48 +0000863 .. method:: assertIs(first, second, msg=None)
864 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000865
Michael Foorde180d392011-01-28 19:51:48 +0000866 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000867 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000868
Raymond Hettinger35a88362009-04-09 00:08:24 +0000869 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000870
871
Ezio Melotti4370b302010-11-03 20:39:14 +0000872 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000873 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000874
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300875 Test that *expr* is (or is not) ``None``.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000876
Ezio Melotti4370b302010-11-03 20:39:14 +0000877 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000878
879
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000880 .. method:: assertIn(first, second, msg=None)
881 assertNotIn(first, second, msg=None)
882
Ezio Melotti4841fd62010-11-05 15:43:40 +0000883 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000884
Raymond Hettinger35a88362009-04-09 00:08:24 +0000885 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000886
887
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000888 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000889 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000890
Ezio Melotti9794a262010-11-04 14:52:13 +0000891 Test that *obj* is (or is not) an instance of *cls* (which can be a
892 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200893 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000894
Ezio Melotti4370b302010-11-03 20:39:14 +0000895 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000896
897
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000898
Ezio Melottif418db22016-01-12 11:03:31 +0200899 It is also possible to check the production of exceptions, warnings, and
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200900 log messages using the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000901
Ezio Melotti4370b302010-11-03 20:39:14 +0000902 +---------------------------------------------------------+--------------------------------------+------------+
903 | Method | Checks that | New in |
904 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200905 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000906 | <TestCase.assertRaises>` | | |
907 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300908 | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
909 | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000910 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200911 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000912 | <TestCase.assertWarns>` | | |
913 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300914 | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
915 | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000916 +---------------------------------------------------------+--------------------------------------+------------+
Georg Brandled007d52013-11-24 16:09:26 +0100917 | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 |
918 | <TestCase.assertLogs>` | with minimum *level* | |
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200919 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000920
Georg Brandl7f01a132009-09-16 15:58:14 +0000921 .. method:: assertRaises(exception, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300922 assertRaises(exception, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000923
924 Test that an exception is raised when *callable* is called with any
925 positional or keyword arguments that are also passed to
926 :meth:`assertRaises`. The test passes if *exception* is raised, is an
927 error if another exception is raised, or fails if no exception is raised.
928 To catch any of a group of exceptions, a tuple containing the exception
929 classes may be passed as *exception*.
930
Ezio Melottib4dc2502011-05-06 15:01:41 +0300931 If only the *exception* and possibly the *msg* arguments are given,
932 return a context manager so that the code under test can be written
933 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000934
Michael Foord41531f22010-02-05 21:13:40 +0000935 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000936 do_something()
937
Ezio Melottib4dc2502011-05-06 15:01:41 +0300938 When used as a context manager, :meth:`assertRaises` accepts the
939 additional keyword argument *msg*.
940
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000941 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000942 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000943 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000944
Georg Brandl8a1caa22010-07-29 16:01:11 +0000945 with self.assertRaises(SomeException) as cm:
946 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000947
Georg Brandl8a1caa22010-07-29 16:01:11 +0000948 the_exception = cm.exception
949 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000950
Ezio Melotti49008232010-02-08 21:57:48 +0000951 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000952 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000953
Ezio Melotti49008232010-02-08 21:57:48 +0000954 .. versionchanged:: 3.2
955 Added the :attr:`exception` attribute.
956
Ezio Melottib4dc2502011-05-06 15:01:41 +0300957 .. versionchanged:: 3.3
958 Added the *msg* keyword argument when used as a context manager.
959
Benjamin Peterson52baa292009-03-24 00:56:30 +0000960
Ezio Melottied3a7d22010-12-01 02:32:32 +0000961 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300962 assertRaisesRegex(exception, regex, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000963
Ezio Melottied3a7d22010-12-01 02:32:32 +0000964 Like :meth:`assertRaises` but also tests that *regex* matches
965 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000966 a regular expression object or a string containing a regular expression
967 suitable for use by :func:`re.search`. Examples::
968
Terry Jan Reedyc4565a92013-06-29 13:15:43 -0400969 self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
Ezio Melottied3a7d22010-12-01 02:32:32 +0000970 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000971
972 or::
973
Ezio Melottied3a7d22010-12-01 02:32:32 +0000974 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000975 int('XYZ')
976
Georg Brandl419e3de2010-12-01 15:44:25 +0000977 .. versionadded:: 3.1
978 under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +0300979
Ezio Melottied3a7d22010-12-01 02:32:32 +0000980 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +0000981 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000982
Ezio Melottib4dc2502011-05-06 15:01:41 +0300983 .. versionchanged:: 3.3
984 Added the *msg* keyword argument when used as a context manager.
985
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000986
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000987 .. method:: assertWarns(warning, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300988 assertWarns(warning, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000989
990 Test that a warning is triggered when *callable* is called with any
991 positional or keyword arguments that are also passed to
992 :meth:`assertWarns`. The test passes if *warning* is triggered and
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400993 fails if it isn't. Any exception is an error.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000994 To catch any of a group of warnings, a tuple containing the warning
995 classes may be passed as *warnings*.
996
Ezio Melottib4dc2502011-05-06 15:01:41 +0300997 If only the *warning* and possibly the *msg* arguments are given,
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400998 return a context manager so that the code under test can be written
Ezio Melottib4dc2502011-05-06 15:01:41 +0300999 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001000
1001 with self.assertWarns(SomeWarning):
1002 do_something()
1003
Terry Jan Reedy9eda66d2013-07-27 16:15:29 -04001004 When used as a context manager, :meth:`assertWarns` accepts the
Ezio Melottib4dc2502011-05-06 15:01:41 +03001005 additional keyword argument *msg*.
1006
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001007 The context manager will store the caught warning object in its
1008 :attr:`warning` attribute, and the source line which triggered the
1009 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1010 This can be useful if the intention is to perform additional checks
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001011 on the warning caught::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001012
1013 with self.assertWarns(SomeWarning) as cm:
1014 do_something()
1015
1016 self.assertIn('myfile.py', cm.filename)
1017 self.assertEqual(320, cm.lineno)
1018
1019 This method works regardless of the warning filters in place when it
1020 is called.
1021
1022 .. versionadded:: 3.2
1023
Ezio Melottib4dc2502011-05-06 15:01:41 +03001024 .. versionchanged:: 3.3
1025 Added the *msg* keyword argument when used as a context manager.
1026
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001027
Ezio Melottied3a7d22010-12-01 02:32:32 +00001028 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001029 assertWarnsRegex(warning, regex, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001030
Ezio Melottied3a7d22010-12-01 02:32:32 +00001031 Like :meth:`assertWarns` but also tests that *regex* matches on the
1032 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001033 object or a string containing a regular expression suitable for use
1034 by :func:`re.search`. Example::
1035
Ezio Melottied3a7d22010-12-01 02:32:32 +00001036 self.assertWarnsRegex(DeprecationWarning,
1037 r'legacy_function\(\) is deprecated',
1038 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001039
1040 or::
1041
Ezio Melottied3a7d22010-12-01 02:32:32 +00001042 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001043 frobnicate('/etc/passwd')
1044
1045 .. versionadded:: 3.2
1046
Ezio Melottib4dc2502011-05-06 15:01:41 +03001047 .. versionchanged:: 3.3
1048 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001049
Antoine Pitrou0715b9f2013-09-14 19:45:47 +02001050 .. method:: assertLogs(logger=None, level=None)
1051
1052 A context manager to test that at least one message is logged on
1053 the *logger* or one of its children, with at least the given
1054 *level*.
1055
1056 If given, *logger* should be a :class:`logging.Logger` object or a
1057 :class:`str` giving the name of a logger. The default is the root
1058 logger, which will catch all messages.
1059
1060 If given, *level* should be either a numeric logging level or
1061 its string equivalent (for example either ``"ERROR"`` or
1062 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`.
1063
1064 The test passes if at least one message emitted inside the ``with``
1065 block matches the *logger* and *level* conditions, otherwise it fails.
1066
1067 The object returned by the context manager is a recording helper
1068 which keeps tracks of the matching log messages. It has two
1069 attributes:
1070
1071 .. attribute:: records
1072
1073 A list of :class:`logging.LogRecord` objects of the matching
1074 log messages.
1075
1076 .. attribute:: output
1077
1078 A list of :class:`str` objects with the formatted output of
1079 matching messages.
1080
1081 Example::
1082
1083 with self.assertLogs('foo', level='INFO') as cm:
1084 logging.getLogger('foo').info('first message')
1085 logging.getLogger('foo.bar').error('second message')
1086 self.assertEqual(cm.output, ['INFO:foo:first message',
1087 'ERROR:foo.bar:second message'])
1088
1089 .. versionadded:: 3.4
1090
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001091
Ezio Melotti4370b302010-11-03 20:39:14 +00001092 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001093
Ezio Melotti4370b302010-11-03 20:39:14 +00001094 +---------------------------------------+--------------------------------+--------------+
1095 | Method | Checks that | New in |
1096 +=======================================+================================+==============+
1097 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1098 | <TestCase.assertAlmostEqual>` | | |
1099 +---------------------------------------+--------------------------------+--------------+
1100 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1101 | <TestCase.assertNotAlmostEqual>` | | |
1102 +---------------------------------------+--------------------------------+--------------+
1103 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1104 | <TestCase.assertGreater>` | | |
1105 +---------------------------------------+--------------------------------+--------------+
1106 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1107 | <TestCase.assertGreaterEqual>` | | |
1108 +---------------------------------------+--------------------------------+--------------+
1109 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1110 | <TestCase.assertLess>` | | |
1111 +---------------------------------------+--------------------------------+--------------+
1112 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1113 | <TestCase.assertLessEqual>` | | |
1114 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001115 | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001116 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001117 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001118 | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001119 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001120 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001121 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001122 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001123 | | regardless of their order | |
1124 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001125
1126
Michael Foorde180d392011-01-28 19:51:48 +00001127 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1128 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001129
Michael Foorde180d392011-01-28 19:51:48 +00001130 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001131 equal by computing the difference, rounding to the given number of
1132 decimal *places* (default 7), and comparing to zero. Note that these
1133 methods round the values to the given number of *decimal places* (i.e.
1134 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001135
Ezio Melotti4370b302010-11-03 20:39:14 +00001136 If *delta* is supplied instead of *places* then the difference
Ezio Melottid51914c2013-08-11 13:04:50 +03001137 between *first* and *second* must be less or equal to (or greater than) *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001138
Ezio Melotti4370b302010-11-03 20:39:14 +00001139 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001140
Ezio Melotti4370b302010-11-03 20:39:14 +00001141 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001142 :meth:`assertAlmostEqual` automatically considers almost equal objects
1143 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1144 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001145
Ezio Melotti4370b302010-11-03 20:39:14 +00001146
Michael Foorde180d392011-01-28 19:51:48 +00001147 .. method:: assertGreater(first, second, msg=None)
1148 assertGreaterEqual(first, second, msg=None)
1149 assertLess(first, second, msg=None)
1150 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001151
Michael Foorde180d392011-01-28 19:51:48 +00001152 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001153 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001154
1155 >>> self.assertGreaterEqual(3, 4)
1156 AssertionError: "3" unexpectedly not greater than or equal to "4"
1157
1158 .. versionadded:: 3.1
1159
1160
Ezio Melottied3a7d22010-12-01 02:32:32 +00001161 .. method:: assertRegex(text, regex, msg=None)
1162 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001163
Ezio Melottied3a7d22010-12-01 02:32:32 +00001164 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001165 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001166 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001167 may be a regular expression object or a string containing a regular
1168 expression suitable for use by :func:`re.search`.
1169
Georg Brandl419e3de2010-12-01 15:44:25 +00001170 .. versionadded:: 3.1
1171 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001172 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001173 The method ``assertRegexpMatches()`` has been renamed to
1174 :meth:`.assertRegex`.
1175 .. versionadded:: 3.2
1176 :meth:`.assertNotRegex`.
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001177 .. versionadded:: 3.5
1178 The name ``assertNotRegexpMatches`` is a deprecated alias
1179 for :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001180
1181
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001182 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001183
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001184 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001185 regardless of their order. When they don't, an error message listing the
1186 differences between the sequences will be generated.
1187
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001188 Duplicate elements are *not* ignored when comparing *first* and
1189 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001190 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001191 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001192 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001193
Ezio Melotti4370b302010-11-03 20:39:14 +00001194 .. versionadded:: 3.2
1195
Ezio Melotti4370b302010-11-03 20:39:14 +00001196
Ezio Melotti22170ed2010-11-20 09:57:27 +00001197 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001198
Ezio Melotti22170ed2010-11-20 09:57:27 +00001199 The :meth:`assertEqual` method dispatches the equality check for objects of
1200 the same type to different type-specific methods. These methods are already
1201 implemented for most of the built-in types, but it's also possible to
1202 register new methods using :meth:`addTypeEqualityFunc`:
1203
1204 .. method:: addTypeEqualityFunc(typeobj, function)
1205
1206 Registers a type-specific method called by :meth:`assertEqual` to check
1207 if two objects of exactly the same *typeobj* (not subclasses) compare
1208 equal. *function* must take two positional arguments and a third msg=None
1209 keyword argument just as :meth:`assertEqual` does. It must raise
1210 :data:`self.failureException(msg) <failureException>` when inequality
1211 between the first two parameters is detected -- possibly providing useful
1212 information and explaining the inequalities in details in the error
1213 message.
1214
1215 .. versionadded:: 3.1
1216
1217 The list of type-specific methods automatically used by
1218 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1219 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001220
1221 +-----------------------------------------+-----------------------------+--------------+
1222 | Method | Used to compare | New in |
1223 +=========================================+=============================+==============+
1224 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1225 | <TestCase.assertMultiLineEqual>` | | |
1226 +-----------------------------------------+-----------------------------+--------------+
1227 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1228 | <TestCase.assertSequenceEqual>` | | |
1229 +-----------------------------------------+-----------------------------+--------------+
1230 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1231 | <TestCase.assertListEqual>` | | |
1232 +-----------------------------------------+-----------------------------+--------------+
1233 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1234 | <TestCase.assertTupleEqual>` | | |
1235 +-----------------------------------------+-----------------------------+--------------+
1236 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1237 | <TestCase.assertSetEqual>` | | |
1238 +-----------------------------------------+-----------------------------+--------------+
1239 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1240 | <TestCase.assertDictEqual>` | | |
1241 +-----------------------------------------+-----------------------------+--------------+
1242
1243
1244
Michael Foorde180d392011-01-28 19:51:48 +00001245 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001246
Michael Foorde180d392011-01-28 19:51:48 +00001247 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001248 When not equal a diff of the two strings highlighting the differences
1249 will be included in the error message. This method is used by default
1250 when comparing strings with :meth:`assertEqual`.
1251
Ezio Melotti4370b302010-11-03 20:39:14 +00001252 .. versionadded:: 3.1
1253
1254
Michael Foorde180d392011-01-28 19:51:48 +00001255 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001256
1257 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001258 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001259 be raised. If the sequences are different an error message is
1260 constructed that shows the difference between the two.
1261
Ezio Melotti22170ed2010-11-20 09:57:27 +00001262 This method is not called directly by :meth:`assertEqual`, but
1263 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001264 :meth:`assertTupleEqual`.
1265
1266 .. versionadded:: 3.1
1267
1268
Michael Foorde180d392011-01-28 19:51:48 +00001269 .. method:: assertListEqual(first, second, msg=None)
1270 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001271
Ezio Melotti49ccd512012-08-29 17:50:42 +03001272 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001273 constructed that shows only the differences between the two. An error
1274 is also raised if either of the parameters are of the wrong type.
1275 These methods are used by default when comparing lists or tuples with
1276 :meth:`assertEqual`.
1277
Ezio Melotti4370b302010-11-03 20:39:14 +00001278 .. versionadded:: 3.1
1279
1280
Michael Foorde180d392011-01-28 19:51:48 +00001281 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001282
1283 Tests that two sets are equal. If not, an error message is constructed
1284 that lists the differences between the sets. This method is used by
1285 default when comparing sets or frozensets with :meth:`assertEqual`.
1286
Michael Foorde180d392011-01-28 19:51:48 +00001287 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001288 method.
1289
Ezio Melotti4370b302010-11-03 20:39:14 +00001290 .. versionadded:: 3.1
1291
1292
Michael Foorde180d392011-01-28 19:51:48 +00001293 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001294
1295 Test that two dictionaries are equal. If not, an error message is
1296 constructed that shows the differences in the dictionaries. This
1297 method will be used by default to compare dictionaries in
1298 calls to :meth:`assertEqual`.
1299
Ezio Melotti4370b302010-11-03 20:39:14 +00001300 .. versionadded:: 3.1
1301
1302
1303
Ezio Melotti22170ed2010-11-20 09:57:27 +00001304 .. _other-methods-and-attrs:
1305
Ezio Melotti4370b302010-11-03 20:39:14 +00001306 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001307
Benjamin Peterson52baa292009-03-24 00:56:30 +00001308
Georg Brandl7f01a132009-09-16 15:58:14 +00001309 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001310
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001311 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001312 the error message.
1313
1314
1315 .. attribute:: failureException
1316
1317 This class attribute gives the exception raised by the test method. If a
1318 test framework needs to use a specialized exception, possibly to carry
1319 additional information, it must subclass this exception in order to "play
1320 fair" with the framework. The initial value of this attribute is
1321 :exc:`AssertionError`.
1322
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001323
1324 .. attribute:: longMessage
1325
Guido van Rossum4a452352016-10-13 14:23:01 -07001326 This class attribute determines what happens when a custom failure message
1327 is passed as the msg argument to an assertXYY call that fails.
1328 ``True`` is the default value. In this case, the custom message is appended
1329 to the end of the standard failure message.
1330 When set to ``False``, the custom message replaces the standard message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001331
Guido van Rossum4a452352016-10-13 14:23:01 -07001332 The class setting can be overridden in individual test methods by assigning
1333 an instance attribute, self.longMessage, to ``True`` or ``False`` before
1334 calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001335
Guido van Rossum4a452352016-10-13 14:23:01 -07001336 The class setting gets reset before each test call.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001337
Raymond Hettinger35a88362009-04-09 00:08:24 +00001338 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001339
1340
Michael Foord98b3e762010-06-05 21:59:55 +00001341 .. attribute:: maxDiff
1342
1343 This attribute controls the maximum length of diffs output by assert
1344 methods that report diffs on failure. It defaults to 80*8 characters.
1345 Assert methods affected by this attribute are
1346 :meth:`assertSequenceEqual` (including all the sequence comparison
1347 methods that delegate to it), :meth:`assertDictEqual` and
1348 :meth:`assertMultiLineEqual`.
1349
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001350 Setting ``maxDiff`` to ``None`` means that there is no maximum length of
Michael Foord98b3e762010-06-05 21:59:55 +00001351 diffs.
1352
1353 .. versionadded:: 3.2
1354
1355
Benjamin Peterson52baa292009-03-24 00:56:30 +00001356 Testing frameworks can use the following methods to collect information on
1357 the test:
1358
1359
1360 .. method:: countTestCases()
1361
1362 Return the number of tests represented by this test object. For
1363 :class:`TestCase` instances, this will always be ``1``.
1364
1365
1366 .. method:: defaultTestResult()
1367
1368 Return an instance of the test result class that should be used for this
1369 test case class (if no other result instance is provided to the
1370 :meth:`run` method).
1371
1372 For :class:`TestCase` instances, this will always be an instance of
1373 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1374 as necessary.
1375
1376
1377 .. method:: id()
1378
1379 Return a string identifying the specific test case. This is usually the
1380 full name of the test method, including the module and class name.
1381
1382
1383 .. method:: shortDescription()
1384
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001385 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001386 has been provided. The default implementation of this method
1387 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001388 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001389
Georg Brandl419e3de2010-12-01 15:44:25 +00001390 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001391 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001392 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001393 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001394 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001395
Georg Brandl116aa622007-08-15 14:28:22 +00001396
Georg Brandl7f01a132009-09-16 15:58:14 +00001397 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001398
1399 Add a function to be called after :meth:`tearDown` to cleanup resources
1400 used during the test. Functions will be called in reverse order to the
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +03001401 order they are added (:abbr:`LIFO (last-in, first-out)`). They
1402 are called with any arguments and keyword arguments passed into
1403 :meth:`addCleanup` when they are added.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001404
1405 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1406 then any cleanup functions added will still be called.
1407
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001408 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001409
1410
1411 .. method:: doCleanups()
1412
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001413 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001414 after :meth:`setUp` if :meth:`setUp` raises an exception.
1415
1416 It is responsible for calling all the cleanup functions added by
1417 :meth:`addCleanup`. If you need cleanup functions to be called
1418 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1419 yourself.
1420
1421 :meth:`doCleanups` pops methods off the stack of cleanup
1422 functions one at a time, so it can be called at any time.
1423
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001424 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001425
1426
Georg Brandl7f01a132009-09-16 15:58:14 +00001427.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001428
1429 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001430 allows the test runner to drive the test, but does not provide the methods
1431 which test code can use to check and report errors. This is used to create
1432 test cases using legacy test code, allowing it to be integrated into a
1433 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001434
1435
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001436.. _deprecated-aliases:
1437
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001438Deprecated aliases
1439##################
1440
1441For historical reasons, some of the :class:`TestCase` methods had one or more
1442aliases that are now deprecated. The following table lists the correct names
1443along with their deprecated aliases:
1444
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001445 ============================== ====================== =======================
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001446 Method Name Deprecated alias Deprecated alias
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001447 ============================== ====================== =======================
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001448 :meth:`.assertEqual` failUnlessEqual assertEquals
1449 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1450 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001451 :meth:`.assertFalse` failIf
1452 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001453 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1454 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001455 :meth:`.assertRegex` assertRegexpMatches
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001456 :meth:`.assertNotRegex` assertNotRegexpMatches
Ezio Melottied3a7d22010-12-01 02:32:32 +00001457 :meth:`.assertRaisesRegex` assertRaisesRegexp
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001458 ============================== ====================== =======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001459
Ezio Melotti361467e2011-04-03 17:37:58 +03001460 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001461 the fail* aliases listed in the second column.
1462 .. deprecated:: 3.2
1463 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001464 .. deprecated:: 3.2
1465 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001466 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`.
1467 .. deprecated:: 3.5
1468 the ``assertNotRegexpMatches`` name in favor of :meth:`.assertNotRegex`.
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001469
Benjamin Peterson52baa292009-03-24 00:56:30 +00001470.. _testsuite-objects:
1471
Benjamin Peterson52baa292009-03-24 00:56:30 +00001472Grouping tests
1473~~~~~~~~~~~~~~
1474
Georg Brandl7f01a132009-09-16 15:58:14 +00001475.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001476
Martin Panter37f183d2017-01-18 12:06:38 +00001477 This class represents an aggregation of individual test cases and test suites.
Georg Brandl116aa622007-08-15 14:28:22 +00001478 The class presents the interface needed by the test runner to allow it to be run
1479 as any other test case. Running a :class:`TestSuite` instance is the same as
1480 iterating over the suite, running each test individually.
1481
1482 If *tests* is given, it must be an iterable of individual test cases or other
1483 test suites that will be used to build the suite initially. Additional methods
1484 are provided to add test cases and suites to the collection later on.
1485
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001486 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1487 they do not actually implement a test. Instead, they are used to aggregate
1488 tests into groups of tests that should be run together. Some additional
1489 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001490
1491
1492 .. method:: TestSuite.addTest(test)
1493
1494 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1495
1496
1497 .. method:: TestSuite.addTests(tests)
1498
1499 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1500 instances to this test suite.
1501
Benjamin Petersond2397752009-06-27 23:45:02 +00001502 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1503 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001504
1505 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1506
1507
1508 .. method:: run(result)
1509
1510 Run the tests associated with this suite, collecting the result into the
1511 test result object passed as *result*. Note that unlike
1512 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1513 be passed in.
1514
1515
1516 .. method:: debug()
1517
1518 Run the tests associated with this suite without collecting the
1519 result. This allows exceptions raised by the test to be propagated to the
1520 caller and can be used to support running tests under a debugger.
1521
1522
1523 .. method:: countTestCases()
1524
1525 Return the number of tests represented by this test object, including all
1526 individual tests and sub-suites.
1527
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001528
1529 .. method:: __iter__()
1530
1531 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1532 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
Andrew Svetloveb973682013-08-28 21:28:38 +03001533 that this method may be called several times on a single suite (for
1534 example when counting tests or comparing for equality) so the tests
1535 returned by repeated iterations before :meth:`TestSuite.run` must be the
1536 same for each call iteration. After :meth:`TestSuite.run`, callers should
1537 not rely on the tests returned by this method unless the caller uses a
1538 subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
1539 test references.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001540
Georg Brandl853947a2010-01-31 18:53:23 +00001541 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001542 In earlier versions the :class:`TestSuite` accessed tests directly rather
1543 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1544 for providing tests.
1545
Andrew Svetloveb973682013-08-28 21:28:38 +03001546 .. versionchanged:: 3.4
1547 In earlier versions the :class:`TestSuite` held references to each
1548 :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
1549 that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
1550
Benjamin Peterson52baa292009-03-24 00:56:30 +00001551 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1552 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1553
1554
Benjamin Peterson52baa292009-03-24 00:56:30 +00001555Loading and running tests
1556~~~~~~~~~~~~~~~~~~~~~~~~~
1557
Georg Brandl116aa622007-08-15 14:28:22 +00001558.. class:: TestLoader()
1559
Benjamin Peterson52baa292009-03-24 00:56:30 +00001560 The :class:`TestLoader` class is used to create test suites from classes and
1561 modules. Normally, there is no need to create an instance of this class; the
1562 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001563 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1564 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001565
Robert Collinsf920c212014-10-20 13:24:05 +13001566 :class:`TestLoader` objects have the following attributes:
1567
1568
1569 .. attribute:: errors
1570
1571 A list of the non-fatal errors encountered while loading tests. Not reset
1572 by the loader at any point. Fatal errors are signalled by the relevant
1573 a method raising an exception to the caller. Non-fatal errors are also
1574 indicated by a synthetic test that will raise the original error when
1575 run.
1576
1577 .. versionadded:: 3.5
1578
1579
Benjamin Peterson52baa292009-03-24 00:56:30 +00001580 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001581
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001582
Benjamin Peterson52baa292009-03-24 00:56:30 +00001583 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001584
Martin Panter37f183d2017-01-18 12:06:38 +00001585 Return a suite of all test cases contained in the :class:`TestCase`\ -derived
Benjamin Peterson52baa292009-03-24 00:56:30 +00001586 :class:`testCaseClass`.
1587
Robert Collinse02f6c22015-07-23 06:37:26 +12001588 A test case instance is created for each method named by
1589 :meth:`getTestCaseNames`. By default these are the method names
1590 beginning with ``test``. If :meth:`getTestCaseNames` returns no
1591 methods, but the :meth:`runTest` method is implemented, a single test
1592 case is created for that method instead.
1593
Benjamin Peterson52baa292009-03-24 00:56:30 +00001594
Barry Warsawd78742a2014-09-08 14:21:37 -04001595 .. method:: loadTestsFromModule(module, pattern=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001596
Martin Panter37f183d2017-01-18 12:06:38 +00001597 Return a suite of all test cases contained in the given module. This
Benjamin Peterson52baa292009-03-24 00:56:30 +00001598 method searches *module* for classes derived from :class:`TestCase` and
1599 creates an instance of the class for each test method defined for the
1600 class.
1601
Georg Brandle720c0a2009-04-27 16:20:50 +00001602 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001603
1604 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1605 convenient in sharing fixtures and helper functions, defining test
1606 methods on base classes that are not intended to be instantiated
1607 directly does not play well with this method. Doing so, however, can
1608 be useful when the fixtures are different and defined in subclasses.
1609
Benjamin Petersond2397752009-06-27 23:45:02 +00001610 If a module provides a ``load_tests`` function it will be called to
1611 load the tests. This allows modules to customize test loading.
Barry Warsawd78742a2014-09-08 14:21:37 -04001612 This is the `load_tests protocol`_. The *pattern* argument is passed as
1613 the third argument to ``load_tests``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001614
Georg Brandl853947a2010-01-31 18:53:23 +00001615 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001616 Support for ``load_tests`` added.
1617
Barry Warsawd78742a2014-09-08 14:21:37 -04001618 .. versionchanged:: 3.5
1619 The undocumented and unofficial *use_load_tests* default argument is
1620 deprecated and ignored, although it is still accepted for backward
1621 compatibility. The method also now accepts a keyword-only argument
1622 *pattern* which is passed to ``load_tests`` as the third argument.
1623
Benjamin Peterson52baa292009-03-24 00:56:30 +00001624
Georg Brandl7f01a132009-09-16 15:58:14 +00001625 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001626
Martin Panter37f183d2017-01-18 12:06:38 +00001627 Return a suite of all test cases given a string specifier.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001628
1629 The specifier *name* is a "dotted name" that may resolve either to a
1630 module, a test case class, a test method within a test case class, a
1631 :class:`TestSuite` instance, or a callable object which returns a
1632 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1633 applied in the order listed here; that is, a method on a possible test
1634 case class will be picked up as "a test method within a test case class",
1635 rather than "a callable object".
1636
1637 For example, if you have a module :mod:`SampleTests` containing a
1638 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1639 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001640 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1641 return a suite which will run all three test methods. Using the specifier
1642 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1643 suite which will run only the :meth:`test_two` test method. The specifier
1644 can refer to modules and packages which have not been imported; they will
1645 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001646
1647 The method optionally resolves *name* relative to the given *module*.
1648
Martin Panter536d70e2017-01-14 08:23:08 +00001649 .. versionchanged:: 3.5
1650 If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing
1651 *name* then a synthetic test that raises that error when run will be
1652 returned. These errors are included in the errors accumulated by
1653 self.errors.
Robert Collins659dd622014-10-30 08:27:27 +13001654
Benjamin Peterson52baa292009-03-24 00:56:30 +00001655
Georg Brandl7f01a132009-09-16 15:58:14 +00001656 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001657
1658 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1659 than a single name. The return value is a test suite which supports all
1660 the tests defined for each name.
1661
1662
1663 .. method:: getTestCaseNames(testCaseClass)
1664
1665 Return a sorted sequence of method names found within *testCaseClass*;
1666 this should be a subclass of :class:`TestCase`.
1667
Benjamin Petersond2397752009-06-27 23:45:02 +00001668
1669 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1670
Larry Hastings3732ed22014-03-15 21:13:56 -07001671 Find all the test modules by recursing into subdirectories from the
1672 specified start directory, and return a TestSuite object containing them.
1673 Only test files that match *pattern* will be loaded. (Using shell style
1674 pattern matching.) Only module names that are importable (i.e. are valid
1675 Python identifiers) will be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001676
1677 All test modules must be importable from the top level of the project. If
1678 the start directory is not the top level directory then the top level
1679 directory must be specified separately.
1680
Barry Warsawd78742a2014-09-08 14:21:37 -04001681 If importing a module fails, for example due to a syntax error, then
1682 this will be recorded as a single error and discovery will continue. If
1683 the import failure is due to :exc:`SkipTest` being raised, it will be
1684 recorded as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001685
Barry Warsawd78742a2014-09-08 14:21:37 -04001686 If a package (a directory containing a file named :file:`__init__.py`) is
1687 found, the package will be checked for a ``load_tests`` function. If this
Robert Collinsbf2bda32014-11-05 03:09:01 +13001688 exists then it will be called
1689 ``package.load_tests(loader, tests, pattern)``. Test discovery takes care
1690 to ensure that a package is only checked for tests once during an
1691 invocation, even if the load_tests function itself calls
1692 ``loader.discover``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001693
Barry Warsawd78742a2014-09-08 14:21:37 -04001694 If ``load_tests`` exists then discovery does *not* recurse into the
1695 package, ``load_tests`` is responsible for loading all tests in the
1696 package.
Benjamin Petersond2397752009-06-27 23:45:02 +00001697
1698 The pattern is deliberately not stored as a loader attribute so that
1699 packages can continue discovery themselves. *top_level_dir* is stored so
1700 ``load_tests`` does not need to pass this argument in to
1701 ``loader.discover()``.
1702
Benjamin Petersonb48af542010-04-11 20:43:16 +00001703 *start_dir* can be a dotted module name as well as a directory.
1704
Georg Brandl853947a2010-01-31 18:53:23 +00001705 .. versionadded:: 3.2
1706
Ezio Melottieae2b382013-03-01 14:47:50 +02001707 .. versionchanged:: 3.4
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001708 Modules that raise :exc:`SkipTest` on import are recorded as skips,
Larry Hastings3732ed22014-03-15 21:13:56 -07001709 not errors.
1710 Discovery works for :term:`namespace packages <namespace package>`.
1711 Paths are sorted before being imported so that execution order is
1712 the same even if the underlying file system's ordering is not
1713 dependent on file name.
Michael Foord80cbc9e2013-03-18 17:50:12 -07001714
Barry Warsawd78742a2014-09-08 14:21:37 -04001715 .. versionchanged:: 3.5
1716 Found packages are now checked for ``load_tests`` regardless of
1717 whether their path matches *pattern*, because it is impossible for
1718 a package name to match the default pattern.
1719
Benjamin Petersond2397752009-06-27 23:45:02 +00001720
Benjamin Peterson52baa292009-03-24 00:56:30 +00001721 The following attributes of a :class:`TestLoader` can be configured either by
1722 subclassing or assignment on an instance:
1723
1724
1725 .. attribute:: testMethodPrefix
1726
1727 String giving the prefix of method names which will be interpreted as test
1728 methods. The default value is ``'test'``.
1729
1730 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1731 methods.
1732
1733
1734 .. attribute:: sortTestMethodsUsing
1735
1736 Function to be used to compare method names when sorting them in
1737 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1738
1739
1740 .. attribute:: suiteClass
1741
1742 Callable object that constructs a test suite from a list of tests. No
1743 methods on the resulting object are needed. The default value is the
1744 :class:`TestSuite` class.
1745
1746 This affects all the :meth:`loadTestsFrom\*` methods.
1747
1748
Benjamin Peterson52baa292009-03-24 00:56:30 +00001749.. class:: TestResult
1750
1751 This class is used to compile information about which tests have succeeded
1752 and which have failed.
1753
1754 A :class:`TestResult` object stores the results of a set of tests. The
1755 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1756 properly recorded; test authors do not need to worry about recording the
1757 outcome of tests.
1758
1759 Testing frameworks built on top of :mod:`unittest` may want access to the
1760 :class:`TestResult` object generated by running a set of tests for reporting
1761 purposes; a :class:`TestResult` instance is returned by the
1762 :meth:`TestRunner.run` method for this purpose.
1763
1764 :class:`TestResult` instances have the following attributes that will be of
1765 interest when inspecting the results of running a set of tests:
1766
1767
1768 .. attribute:: errors
1769
1770 A list containing 2-tuples of :class:`TestCase` instances and strings
1771 holding formatted tracebacks. Each tuple represents a test which raised an
1772 unexpected exception.
1773
Benjamin Peterson52baa292009-03-24 00:56:30 +00001774 .. attribute:: failures
1775
1776 A list containing 2-tuples of :class:`TestCase` instances and strings
1777 holding formatted tracebacks. Each tuple represents a test where a failure
Ezio Melottie2202362013-09-07 15:19:30 +03001778 was explicitly signalled using the :meth:`TestCase.assert\*` methods.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001779
Benjamin Peterson52baa292009-03-24 00:56:30 +00001780 .. attribute:: skipped
1781
1782 A list containing 2-tuples of :class:`TestCase` instances and strings
1783 holding the reason for skipping the test.
1784
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001785 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001786
1787 .. attribute:: expectedFailures
1788
Georg Brandl6faee4e2010-09-21 14:48:28 +00001789 A list containing 2-tuples of :class:`TestCase` instances and strings
1790 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001791 of the test case.
1792
1793 .. attribute:: unexpectedSuccesses
1794
1795 A list containing :class:`TestCase` instances that were marked as expected
1796 failures, but succeeded.
1797
1798 .. attribute:: shouldStop
1799
1800 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1801
Benjamin Peterson52baa292009-03-24 00:56:30 +00001802 .. attribute:: testsRun
1803
1804 The total number of tests run so far.
1805
Georg Brandl12037202010-12-02 22:35:25 +00001806 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001807
1808 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1809 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1810 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1811 fails or errors. Any output is also attached to the failure / error message.
1812
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001813 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001814
Benjamin Petersonb48af542010-04-11 20:43:16 +00001815 .. attribute:: failfast
1816
1817 If set to true :meth:`stop` will be called on the first failure or error,
1818 halting the test run.
1819
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001820 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001821
Robert Collinsf0c819a2015-03-06 13:46:35 +13001822 .. attribute:: tb_locals
1823
1824 If set to true then local variables will be shown in tracebacks.
1825
1826 .. versionadded:: 3.5
Benjamin Petersonb48af542010-04-11 20:43:16 +00001827
Benjamin Peterson52baa292009-03-24 00:56:30 +00001828 .. method:: wasSuccessful()
1829
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001830 Return ``True`` if all tests run so far have passed, otherwise returns
1831 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001832
Gregory P. Smith5a6d4bf2014-01-20 01:11:18 -08001833 .. versionchanged:: 3.4
1834 Returns ``False`` if there were any :attr:`unexpectedSuccesses`
1835 from tests marked with the :func:`expectedFailure` decorator.
1836
Benjamin Peterson52baa292009-03-24 00:56:30 +00001837 .. method:: stop()
1838
1839 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001840 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001841 :class:`TestRunner` objects should respect this flag and return without
1842 running any additional tests.
1843
1844 For example, this feature is used by the :class:`TextTestRunner` class to
1845 stop the test framework when the user signals an interrupt from the
1846 keyboard. Interactive tools which provide :class:`TestRunner`
1847 implementations can use this in a similar manner.
1848
1849 The following methods of the :class:`TestResult` class are used to maintain
1850 the internal data structures, and may be extended in subclasses to support
1851 additional reporting requirements. This is particularly useful in building
1852 tools which support interactive reporting while tests are being run.
1853
1854
1855 .. method:: startTest(test)
1856
1857 Called when the test case *test* is about to be run.
1858
Benjamin Peterson52baa292009-03-24 00:56:30 +00001859 .. method:: stopTest(test)
1860
1861 Called after the test case *test* has been executed, regardless of the
1862 outcome.
1863
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001864 .. method:: startTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001865
1866 Called once before any tests are executed.
1867
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001868 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001869
1870
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001871 .. method:: stopTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001872
Ezio Melotti176d6c42010-01-27 20:58:07 +00001873 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001874
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001875 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001876
1877
Benjamin Peterson52baa292009-03-24 00:56:30 +00001878 .. method:: addError(test, err)
1879
Ezio Melottie64a91a2013-09-07 15:23:36 +03001880 Called when the test case *test* raises an unexpected exception. *err* is a
Benjamin Peterson52baa292009-03-24 00:56:30 +00001881 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1882 traceback)``.
1883
1884 The default implementation appends a tuple ``(test, formatted_err)`` to
1885 the instance's :attr:`errors` attribute, where *formatted_err* is a
1886 formatted traceback derived from *err*.
1887
1888
1889 .. method:: addFailure(test, err)
1890
Benjamin Petersond2397752009-06-27 23:45:02 +00001891 Called when the test case *test* signals a failure. *err* is a tuple of
1892 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001893
1894 The default implementation appends a tuple ``(test, formatted_err)`` to
1895 the instance's :attr:`failures` attribute, where *formatted_err* is a
1896 formatted traceback derived from *err*.
1897
1898
1899 .. method:: addSuccess(test)
1900
1901 Called when the test case *test* succeeds.
1902
1903 The default implementation does nothing.
1904
1905
1906 .. method:: addSkip(test, reason)
1907
1908 Called when the test case *test* is skipped. *reason* is the reason the
1909 test gave for skipping.
1910
1911 The default implementation appends a tuple ``(test, reason)`` to the
1912 instance's :attr:`skipped` attribute.
1913
1914
1915 .. method:: addExpectedFailure(test, err)
1916
1917 Called when the test case *test* fails, but was marked with the
1918 :func:`expectedFailure` decorator.
1919
1920 The default implementation appends a tuple ``(test, formatted_err)`` to
1921 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1922 is a formatted traceback derived from *err*.
1923
1924
1925 .. method:: addUnexpectedSuccess(test)
1926
1927 Called when the test case *test* was marked with the
1928 :func:`expectedFailure` decorator, but succeeded.
1929
1930 The default implementation appends the test to the instance's
1931 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001932
Georg Brandl67b21b72010-08-17 15:07:14 +00001933
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001934 .. method:: addSubTest(test, subtest, outcome)
1935
1936 Called when a subtest finishes. *test* is the test case
1937 corresponding to the test method. *subtest* is a custom
1938 :class:`TestCase` instance describing the subtest.
1939
1940 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
1941 it failed with an exception where *outcome* is a tuple of the form
1942 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1943
1944 The default implementation does nothing when the outcome is a
1945 success, and records subtest failures as normal failures.
1946
1947 .. versionadded:: 3.4
1948
1949
Michael Foord34c94622010-02-10 15:51:42 +00001950.. class:: TextTestResult(stream, descriptions, verbosity)
1951
Georg Brandl67b21b72010-08-17 15:07:14 +00001952 A concrete implementation of :class:`TestResult` used by the
1953 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001954
Georg Brandl67b21b72010-08-17 15:07:14 +00001955 .. versionadded:: 3.2
1956 This class was previously named ``_TextTestResult``. The old name still
1957 exists as an alias but is deprecated.
1958
Georg Brandl116aa622007-08-15 14:28:22 +00001959
1960.. data:: defaultTestLoader
1961
1962 Instance of the :class:`TestLoader` class intended to be shared. If no
1963 customization of the :class:`TestLoader` is needed, this instance can be used
1964 instead of repeatedly creating new instances.
1965
1966
Ezio Melotti9c939bc2013-05-07 09:46:30 +03001967.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \
Robert Collinsf0c819a2015-03-06 13:46:35 +13001968 buffer=False, resultclass=None, warnings=None, *, tb_locals=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001969
Michael Foordd218e952011-01-03 12:55:11 +00001970 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001971 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001972 has a few configurable parameters, but is essentially very simple. Graphical
Robert Collinsf0c819a2015-03-06 13:46:35 +13001973 applications which run test suites should provide alternate implementations. Such
1974 implementations should accept ``**kwargs`` as the interface to construct runners
1975 changes when features are added to unittest.
Georg Brandl116aa622007-08-15 14:28:22 +00001976
Ezio Melotti60901872010-12-01 00:56:10 +00001977 By default this runner shows :exc:`DeprecationWarning`,
Senthil Kumaran409ea5d2014-02-08 14:28:03 -08001978 :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and
Larry Hastingsad88d7a2014-02-10 04:26:10 -08001979 :exc:`ImportWarning` even if they are :ref:`ignored by default
1980 <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest
1981 methods <deprecated-aliases>` are also special-cased and, when the warning
1982 filters are ``'default'`` or ``'always'``, they will appear only once
1983 per-module, in order to avoid too many warning messages. This behavior can
Martin Panterb8c5f542016-10-30 04:20:23 +00001984 be overridden using Python's :option:`!-Wd` or :option:`!-Wa` options
1985 (see :ref:`Warning control <using-on-warnings>`) and leaving
Larry Hastingsad88d7a2014-02-10 04:26:10 -08001986 *warnings* to ``None``.
Ezio Melotti60901872010-12-01 00:56:10 +00001987
Michael Foordd218e952011-01-03 12:55:11 +00001988 .. versionchanged:: 3.2
1989 Added the ``warnings`` argument.
1990
1991 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001992 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001993 than import time.
1994
Robert Collinsf0c819a2015-03-06 13:46:35 +13001995 .. versionchanged:: 3.5
1996 Added the tb_locals parameter.
1997
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001998 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001999
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002000 This method returns the instance of ``TestResult`` used by :meth:`run`.
2001 It is not intended to be called directly, but can be overridden in
2002 subclasses to provide a custom ``TestResult``.
2003
Michael Foord34c94622010-02-10 15:51:42 +00002004 ``_makeResult()`` instantiates the class or callable passed in the
2005 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00002006 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00002007 The result class is instantiated with the following arguments::
2008
2009 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002010
Michael Foord4d1639f2013-12-29 23:38:55 +00002011 .. method:: run(test)
2012
2013 This method is the main public interface to the `TextTestRunner`. This
2014 method takes a :class:`TestSuite` or :class:`TestCase` instance. A
2015 :class:`TestResult` is created by calling
2016 :func:`_makeResult` and the test(s) are run and the
2017 results printed to stdout.
2018
Ezio Melotti60901872010-12-01 00:56:10 +00002019
Georg Brandl419e3de2010-12-01 15:44:25 +00002020.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02002021 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00002022 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002023
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002024 A command-line program that loads a set of tests from *module* and runs them;
2025 this is primarily for making test modules conveniently executable.
2026 The simplest use for this function is to include the following line at the
2027 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00002028
2029 if __name__ == '__main__':
2030 unittest.main()
2031
Benjamin Petersond2397752009-06-27 23:45:02 +00002032 You can run tests with more detailed information by passing in the verbosity
2033 argument::
2034
2035 if __name__ == '__main__':
2036 unittest.main(verbosity=2)
2037
R David Murray6e731b02014-01-02 13:43:02 -05002038 The *defaultTest* argument is either the name of a single test or an
2039 iterable of test names to run if no test names are specified via *argv*. If
2040 not specified or ``None`` and no test names are provided via *argv*, all
2041 tests found in *module* are run.
R David Murray12e930f2014-01-02 13:37:26 -05002042
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002043 The *argv* argument can be a list of options passed to the program, with the
2044 first element being the program name. If not specified or ``None``,
2045 the values of :data:`sys.argv` are used.
2046
Georg Brandl116aa622007-08-15 14:28:22 +00002047 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002048 created instance of it. By default ``main`` calls :func:`sys.exit` with
2049 an exit code indicating success or failure of the tests run.
2050
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002051 The *testLoader* argument has to be a :class:`TestLoader` instance,
2052 and defaults to :data:`defaultTestLoader`.
2053
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002054 ``main`` supports being used from the interactive interpreter by passing in the
2055 argument ``exit=False``. This displays the result on standard output without
2056 calling :func:`sys.exit`::
2057
2058 >>> from unittest import main
2059 >>> main(module='test_module', exit=False)
2060
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002061 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00002062 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002063
Zachary Waref0a71cf2016-08-30 00:16:13 -05002064 The *warnings* argument specifies the :ref:`warning filter <warning-filter>`
Ezio Melotti60901872010-12-01 00:56:10 +00002065 that should be used while running the tests. If it's not specified, it will
Martin Panterb8c5f542016-10-30 04:20:23 +00002066 remain ``None`` if a :option:`!-W` option is passed to :program:`python`
2067 (see :ref:`Warning control <using-on-warnings>`),
Ezio Melotti60901872010-12-01 00:56:10 +00002068 otherwise it will be set to ``'default'``.
2069
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002070 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
2071 This stores the result of the tests run as the ``result`` attribute.
2072
Éric Araujo971dc012010-12-16 03:13:05 +00002073 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002074 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00002075
Georg Brandl853947a2010-01-31 18:53:23 +00002076 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002077 The *verbosity*, *failfast*, *catchbreak*, *buffer*
2078 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00002079
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08002080 .. versionchanged:: 3.4
2081 The *defaultTest* parameter was changed to also accept an iterable of
2082 test names.
2083
Benjamin Petersond2397752009-06-27 23:45:02 +00002084
2085load_tests Protocol
2086###################
2087
Georg Brandl853947a2010-01-31 18:53:23 +00002088.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002089
Benjamin Petersond2397752009-06-27 23:45:02 +00002090Modules or packages can customize how tests are loaded from them during normal
2091test runs or test discovery by implementing a function called ``load_tests``.
2092
2093If a test module defines ``load_tests`` it will be called by
2094:meth:`TestLoader.loadTestsFromModule` with the following arguments::
2095
Barry Warsawd78742a2014-09-08 14:21:37 -04002096 load_tests(loader, standard_tests, pattern)
2097
2098where *pattern* is passed straight through from ``loadTestsFromModule``. It
2099defaults to ``None``.
Benjamin Petersond2397752009-06-27 23:45:02 +00002100
2101It should return a :class:`TestSuite`.
2102
2103*loader* is the instance of :class:`TestLoader` doing the loading.
2104*standard_tests* are the tests that would be loaded by default from the
2105module. It is common for test modules to only want to add or remove tests
2106from the standard set of tests.
2107The third argument is used when loading packages as part of test discovery.
2108
2109A typical ``load_tests`` function that loads tests from a specific set of
2110:class:`TestCase` classes may look like::
2111
2112 test_cases = (TestCase1, TestCase2, TestCase3)
2113
2114 def load_tests(loader, tests, pattern):
2115 suite = TestSuite()
2116 for test_class in test_cases:
2117 tests = loader.loadTestsFromTestCase(test_class)
2118 suite.addTests(tests)
2119 return suite
2120
Barry Warsawd78742a2014-09-08 14:21:37 -04002121If discovery is started in a directory containing a package, either from the
2122command line or by calling :meth:`TestLoader.discover`, then the package
2123:file:`__init__.py` will be checked for ``load_tests``. If that function does
2124not exist, discovery will recurse into the package as though it were just
2125another directory. Otherwise, discovery of the package's tests will be left up
2126to ``load_tests`` which is called with the following arguments::
Benjamin Petersond2397752009-06-27 23:45:02 +00002127
2128 load_tests(loader, standard_tests, pattern)
2129
2130This should return a :class:`TestSuite` representing all the tests
2131from the package. (``standard_tests`` will only contain tests
2132collected from :file:`__init__.py`.)
2133
2134Because the pattern is passed into ``load_tests`` the package is free to
2135continue (and potentially modify) test discovery. A 'do nothing'
2136``load_tests`` function for a test package would look like::
2137
2138 def load_tests(loader, standard_tests, pattern):
2139 # top level directory cached on loader instance
2140 this_dir = os.path.dirname(__file__)
2141 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2142 standard_tests.addTests(package_tests)
2143 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002144
Barry Warsawd78742a2014-09-08 14:21:37 -04002145.. versionchanged:: 3.5
2146 Discovery no longer checks package names for matching *pattern* due to the
2147 impossibility of package names matching the default pattern.
2148
2149
Benjamin Petersonb48af542010-04-11 20:43:16 +00002150
2151Class and Module Fixtures
2152-------------------------
2153
2154Class and module level fixtures are implemented in :class:`TestSuite`. When
2155the test suite encounters a test from a new class then :meth:`tearDownClass`
2156from the previous class (if there is one) is called, followed by
2157:meth:`setUpClass` from the new class.
2158
2159Similarly if a test is from a different module from the previous test then
2160``tearDownModule`` from the previous module is run, followed by
2161``setUpModule`` from the new module.
2162
2163After all the tests have run the final ``tearDownClass`` and
2164``tearDownModule`` are run.
2165
2166Note that shared fixtures do not play well with [potential] features like test
2167parallelization and they break test isolation. They should be used with care.
2168
2169The default ordering of tests created by the unittest test loaders is to group
2170all tests from the same modules and classes together. This will lead to
2171``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2172module. If you randomize the order, so that tests from different modules and
2173classes are adjacent to each other, then these shared fixture functions may be
2174called multiple times in a single test run.
2175
2176Shared fixtures are not intended to work with suites with non-standard
2177ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2178support shared fixtures.
2179
2180If there are any exceptions raised during one of the shared fixture functions
2181the test is reported as an error. Because there is no corresponding test
2182instance an ``_ErrorHolder`` object (that has the same interface as a
2183:class:`TestCase`) is created to represent the error. If you are just using
2184the standard unittest test runner then this detail doesn't matter, but if you
2185are a framework author it may be relevant.
2186
2187
2188setUpClass and tearDownClass
2189~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2190
2191These must be implemented as class methods::
2192
2193 import unittest
2194
2195 class Test(unittest.TestCase):
2196 @classmethod
2197 def setUpClass(cls):
2198 cls._connection = createExpensiveConnectionObject()
2199
2200 @classmethod
2201 def tearDownClass(cls):
2202 cls._connection.destroy()
2203
2204If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2205then you must call up to them yourself. The implementations in
2206:class:`TestCase` are empty.
2207
2208If an exception is raised during a ``setUpClass`` then the tests in the class
2209are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002210have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002211:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002212instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002213
2214
2215setUpModule and tearDownModule
2216~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2217
2218These should be implemented as functions::
2219
2220 def setUpModule():
2221 createConnection()
2222
2223 def tearDownModule():
2224 closeConnection()
2225
2226If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002227module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002228:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002229instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002230
2231
2232Signal Handling
2233---------------
2234
Georg Brandl419e3de2010-12-01 15:44:25 +00002235.. versionadded:: 3.2
2236
Éric Araujo8acb67c2010-11-26 23:31:07 +00002237The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002238along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2239more friendly handling of control-C during a test run. With catch break
2240behavior enabled control-C will allow the currently running test to complete,
2241and the test run will then end and report all the results so far. A second
2242control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002243
Michael Foordde4ceab2010-04-25 19:53:49 +00002244The control-c handling signal handler attempts to remain compatible with code or
2245tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2246handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2247i.e. it has been replaced by the system under test and delegated to, then it
2248calls the default handler. This will normally be the expected behavior by code
2249that replaces an installed handler and delegates to it. For individual tests
2250that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2251decorator can be used.
2252
2253There are a few utility functions for framework authors to enable control-c
2254handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002255
2256.. function:: installHandler()
2257
2258 Install the control-c handler. When a :const:`signal.SIGINT` is received
2259 (usually in response to the user pressing control-c) all registered results
2260 have :meth:`~TestResult.stop` called.
2261
Michael Foord469b1f02010-04-26 23:41:26 +00002262
Benjamin Petersonb48af542010-04-11 20:43:16 +00002263.. function:: registerResult(result)
2264
2265 Register a :class:`TestResult` object for control-c handling. Registering a
2266 result stores a weak reference to it, so it doesn't prevent the result from
2267 being garbage collected.
2268
Michael Foordde4ceab2010-04-25 19:53:49 +00002269 Registering a :class:`TestResult` object has no side-effects if control-c
2270 handling is not enabled, so test frameworks can unconditionally register
2271 all results they create independently of whether or not handling is enabled.
2272
Michael Foord469b1f02010-04-26 23:41:26 +00002273
Benjamin Petersonb48af542010-04-11 20:43:16 +00002274.. function:: removeResult(result)
2275
2276 Remove a registered result. Once a result has been removed then
2277 :meth:`~TestResult.stop` will no longer be called on that result object in
2278 response to a control-c.
2279
Michael Foord469b1f02010-04-26 23:41:26 +00002280
Michael Foordde4ceab2010-04-25 19:53:49 +00002281.. function:: removeHandler(function=None)
2282
2283 When called without arguments this function removes the control-c handler
2284 if it has been installed. This function can also be used as a test decorator
2285 to temporarily remove the handler whilst the test is being executed::
2286
2287 @unittest.removeHandler
2288 def test_signal_handling(self):
2289 ...