blob: 2099bd1e2e979c0d10b44d41db01cd43a17abeb6 [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()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000405 suite.addTest(WidgetTestCase('test_default_size'))
406 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000407 return suite
408
Georg Brandl116aa622007-08-15 14:28:22 +0000409You can place the definitions of test cases and test suites in the same modules
410as the code they are to test (such as :file:`widget.py`), but there are several
411advantages to placing the test code in a separate module, such as
412:file:`test_widget.py`:
413
414* The test module can be run standalone from the command line.
415
416* The test code can more easily be separated from shipped code.
417
418* There is less temptation to change test code to fit the code it tests without
419 a good reason.
420
421* Test code should be modified much less frequently than the code it tests.
422
423* Tested code can be refactored more easily.
424
425* Tests for modules written in C must be in separate modules anyway, so why not
426 be consistent?
427
428* If the testing strategy changes, there is no need to change the source code.
429
430
431.. _legacy-unit-tests:
432
433Re-using old test code
434----------------------
435
436Some users will find that they have existing test code that they would like to
437run from :mod:`unittest`, without converting every old test function to a
438:class:`TestCase` subclass.
439
440For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
441This subclass of :class:`TestCase` can be used to wrap an existing test
442function. Set-up and tear-down functions can also be provided.
443
444Given the following test function::
445
446 def testSomething():
447 something = makeSomething()
448 assert something.name is not None
449 # ...
450
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100451one can create an equivalent test case instance as follows, with optional
452set-up and tear-down methods::
Georg Brandl116aa622007-08-15 14:28:22 +0000453
454 testcase = unittest.FunctionTestCase(testSomething,
455 setUp=makeSomethingDB,
456 tearDown=deleteSomethingDB)
457
Georg Brandl116aa622007-08-15 14:28:22 +0000458.. note::
459
Benjamin Petersond2397752009-06-27 23:45:02 +0000460 Even though :class:`FunctionTestCase` can be used to quickly convert an
461 existing test base over to a :mod:`unittest`\ -based system, this approach is
462 not recommended. Taking the time to set up proper :class:`TestCase`
463 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000464
Benjamin Peterson52baa292009-03-24 00:56:30 +0000465In some cases, the existing tests may have been written using the :mod:`doctest`
466module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
467automatically build :class:`unittest.TestSuite` instances from the existing
468:mod:`doctest`\ -based tests.
469
Georg Brandl116aa622007-08-15 14:28:22 +0000470
Benjamin Peterson5254c042009-03-23 22:25:03 +0000471.. _unittest-skipping:
472
473Skipping tests and expected failures
474------------------------------------
475
Michael Foordf5c851a2010-02-05 21:48:03 +0000476.. versionadded:: 3.1
477
Benjamin Peterson5254c042009-03-23 22:25:03 +0000478Unittest supports skipping individual test methods and even whole classes of
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200479tests. In addition, it supports marking a test as an "expected failure," a test
Benjamin Peterson5254c042009-03-23 22:25:03 +0000480that is broken and will fail, but shouldn't be counted as a failure on a
481:class:`TestResult`.
482
483Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
484or one of its conditional variants.
485
Ezio Melottifed69ba2013-03-01 21:26:04 +0200486Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000487
488 class MyTestCase(unittest.TestCase):
489
490 @unittest.skip("demonstrating skipping")
491 def test_nothing(self):
492 self.fail("shouldn't happen")
493
Benjamin Petersond2397752009-06-27 23:45:02 +0000494 @unittest.skipIf(mylib.__version__ < (1, 3),
495 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000496 def test_format(self):
497 # Tests that work for only a certain version of the library.
498 pass
499
500 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
501 def test_windows_support(self):
502 # windows specific testing code
503 pass
504
Ezio Melottifed69ba2013-03-01 21:26:04 +0200505This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000506
Benjamin Petersonded31c42009-03-30 15:04:16 +0000507 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000508 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000509 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000510
511 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000512 Ran 3 tests in 0.005s
513
514 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000515
Ezio Melottifed69ba2013-03-01 21:26:04 +0200516Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000517
Sandro Tosi317075d2012-03-31 18:34:59 +0200518 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000519 class MySkippedTestCase(unittest.TestCase):
520 def test_not_run(self):
521 pass
522
Benjamin Peterson52baa292009-03-24 00:56:30 +0000523:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
524that needs to be set up is not available.
525
Benjamin Peterson5254c042009-03-23 22:25:03 +0000526Expected failures use the :func:`expectedFailure` decorator. ::
527
528 class ExpectedFailureTestCase(unittest.TestCase):
529 @unittest.expectedFailure
530 def test_fail(self):
531 self.assertEqual(1, 0, "broken")
532
533It's easy to roll your own skipping decorators by making a decorator that calls
534:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottifed69ba2013-03-01 21:26:04 +0200535the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000536
537 def skipUnlessHasattr(obj, attr):
538 if hasattr(obj, attr):
539 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200540 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000541
542The following decorators implement test skipping and expected failures:
543
Georg Brandl8a1caa22010-07-29 16:01:11 +0000544.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000545
546 Unconditionally skip the decorated test. *reason* should describe why the
547 test is being skipped.
548
Georg Brandl8a1caa22010-07-29 16:01:11 +0000549.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000550
551 Skip the decorated test if *condition* is true.
552
Georg Brandl8a1caa22010-07-29 16:01:11 +0000553.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000554
Georg Brandl6faee4e2010-09-21 14:48:28 +0000555 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000556
Georg Brandl8a1caa22010-07-29 16:01:11 +0000557.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000558
559 Mark the test as an expected failure. If the test fails when run, the test
560 is not counted as a failure.
561
Ezio Melotti265281a2013-03-27 20:11:55 +0200562.. exception:: SkipTest(reason)
563
564 This exception is raised to skip a test.
565
566 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
567 decorators instead of raising this directly.
568
R David Murray42fa1102014-01-03 13:03:36 -0500569Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them.
570Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run.
571Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000572
Benjamin Peterson5254c042009-03-23 22:25:03 +0000573
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100574.. _subtests:
575
576Distinguishing test iterations using subtests
577---------------------------------------------
578
579.. versionadded:: 3.4
580
581When some of your tests differ only by a some very small differences, for
582instance some parameters, unittest allows you to distinguish them inside
583the body of a test method using the :meth:`~TestCase.subTest` context manager.
584
585For example, the following test::
586
587 class NumbersTest(unittest.TestCase):
588
589 def test_even(self):
590 """
591 Test that numbers between 0 and 5 are all even.
592 """
593 for i in range(0, 6):
594 with self.subTest(i=i):
595 self.assertEqual(i % 2, 0)
596
597will produce the following output::
598
599 ======================================================================
600 FAIL: test_even (__main__.NumbersTest) (i=1)
601 ----------------------------------------------------------------------
602 Traceback (most recent call last):
603 File "subtests.py", line 32, in test_even
604 self.assertEqual(i % 2, 0)
605 AssertionError: 1 != 0
606
607 ======================================================================
608 FAIL: test_even (__main__.NumbersTest) (i=3)
609 ----------------------------------------------------------------------
610 Traceback (most recent call last):
611 File "subtests.py", line 32, in test_even
612 self.assertEqual(i % 2, 0)
613 AssertionError: 1 != 0
614
615 ======================================================================
616 FAIL: test_even (__main__.NumbersTest) (i=5)
617 ----------------------------------------------------------------------
618 Traceback (most recent call last):
619 File "subtests.py", line 32, in test_even
620 self.assertEqual(i % 2, 0)
621 AssertionError: 1 != 0
622
623Without using a subtest, execution would stop after the first failure,
624and the error would be less easy to diagnose because the value of ``i``
625wouldn't be displayed::
626
627 ======================================================================
628 FAIL: test_even (__main__.NumbersTest)
629 ----------------------------------------------------------------------
630 Traceback (most recent call last):
631 File "subtests.py", line 32, in test_even
632 self.assertEqual(i % 2, 0)
633 AssertionError: 1 != 0
634
635
Georg Brandl116aa622007-08-15 14:28:22 +0000636.. _unittest-contents:
637
638Classes and functions
639---------------------
640
Benjamin Peterson52baa292009-03-24 00:56:30 +0000641This section describes in depth the API of :mod:`unittest`.
642
643
644.. _testcase-objects:
645
646Test cases
647~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000648
Georg Brandl7f01a132009-09-16 15:58:14 +0000649.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000650
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100651 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000652 in the :mod:`unittest` universe. This class is intended to be used as a base
653 class, with specific tests being implemented by concrete subclasses. This class
654 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100655 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000656 kinds of failure.
657
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100658 Each instance of :class:`TestCase` will run a single base method: the method
Robert Collinse02f6c22015-07-23 06:37:26 +1200659 named *methodName*.
660 In most uses of :class:`TestCase`, you will neither change
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100661 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000662
Michael Foord1341bb02011-03-14 19:01:46 -0400663 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100664 :class:`TestCase` can be instantiated successfully without providing a
665 *methodName*. This makes it easier to experiment with :class:`TestCase`
666 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000667
668 :class:`TestCase` instances provide three groups of methods: one group used
669 to run the test, another used by the test implementation to check conditions
670 and report failures, and some inquiry methods allowing information about the
671 test itself to be gathered.
672
673 Methods in the first group (running the test) are:
674
Benjamin Peterson52baa292009-03-24 00:56:30 +0000675 .. method:: setUp()
676
677 Method called to prepare the test fixture. This is called immediately
Terry Jan Reedy7f84d1e2014-04-15 23:44:14 -0400678 before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`,
679 any exception raised by this method will be considered an error rather than
Terry Jan Reedy6ac42402014-04-15 23:38:18 -0400680 a test failure. The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000681
682
683 .. method:: tearDown()
684
685 Method called immediately after the test method has been called and the
686 result recorded. This is called even if the test method raised an
687 exception, so the implementation in subclasses may need to be particularly
Ezio Melotti8dea74f2016-03-13 09:40:09 +0200688 careful about checking internal state. Any exception, other than
689 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
690 considered an additional error rather than a test failure (thus increasing
691 the total number of reported errors). This method will only be called if
692 the :meth:`setUp` succeeds, regardless of the outcome of the test method.
693 The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000694
695
Benjamin Petersonb48af542010-04-11 20:43:16 +0000696 .. method:: setUpClass()
697
698 A class method called before tests in an individual class run.
699 ``setUpClass`` is called with the class as the only argument
700 and must be decorated as a :func:`classmethod`::
701
702 @classmethod
703 def setUpClass(cls):
704 ...
705
706 See `Class and Module Fixtures`_ for more details.
707
708 .. versionadded:: 3.2
709
710
711 .. method:: tearDownClass()
712
713 A class method called after tests in an individual class have run.
714 ``tearDownClass`` is called with the class as the only argument
715 and must be decorated as a :meth:`classmethod`::
716
717 @classmethod
718 def tearDownClass(cls):
719 ...
720
721 See `Class and Module Fixtures`_ for more details.
722
723 .. versionadded:: 3.2
724
725
Georg Brandl7f01a132009-09-16 15:58:14 +0000726 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000727
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100728 Run the test, collecting the result into the :class:`TestResult` object
729 passed as *result*. If *result* is omitted or ``None``, a temporary
730 result object is created (by calling the :meth:`defaultTestResult`
731 method) and used. The result object is returned to :meth:`run`'s
732 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000733
734 The same effect may be had by simply calling the :class:`TestCase`
735 instance.
736
Michael Foord1341bb02011-03-14 19:01:46 -0400737 .. versionchanged:: 3.3
738 Previous versions of ``run`` did not return the result. Neither did
739 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000740
Benjamin Petersone549ead2009-03-28 21:42:05 +0000741 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000742
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000743 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000744 test. See :ref:`unittest-skipping` for more information.
745
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000746 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000747
Benjamin Peterson52baa292009-03-24 00:56:30 +0000748
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100749 .. method:: subTest(msg=None, **params)
750
751 Return a context manager which executes the enclosed code block as a
752 subtest. *msg* and *params* are optional, arbitrary values which are
753 displayed whenever a subtest fails, allowing you to identify them
754 clearly.
755
756 A test case can contain any number of subtest declarations, and
757 they can be arbitrarily nested.
758
759 See :ref:`subtests` for more information.
760
761 .. versionadded:: 3.4
762
763
Benjamin Peterson52baa292009-03-24 00:56:30 +0000764 .. method:: debug()
765
766 Run the test without collecting the result. This allows exceptions raised
767 by the test to be propagated to the caller, and can be used to support
768 running tests under a debugger.
769
Ezio Melotti22170ed2010-11-20 09:57:27 +0000770 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000771
Ezio Melottif418db22016-01-12 11:03:31 +0200772 The :class:`TestCase` class provides several assert methods to check for and
773 report failures. The following table lists the most commonly used methods
774 (see the tables below for more assert methods):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000775
Ezio Melotti4370b302010-11-03 20:39:14 +0000776 +-----------------------------------------+-----------------------------+---------------+
777 | Method | Checks that | New in |
778 +=========================================+=============================+===============+
779 | :meth:`assertEqual(a, b) | ``a == b`` | |
780 | <TestCase.assertEqual>` | | |
781 +-----------------------------------------+-----------------------------+---------------+
782 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
783 | <TestCase.assertNotEqual>` | | |
784 +-----------------------------------------+-----------------------------+---------------+
785 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
786 | <TestCase.assertTrue>` | | |
787 +-----------------------------------------+-----------------------------+---------------+
788 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
789 | <TestCase.assertFalse>` | | |
790 +-----------------------------------------+-----------------------------+---------------+
791 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
792 | <TestCase.assertIs>` | | |
793 +-----------------------------------------+-----------------------------+---------------+
794 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
795 | <TestCase.assertIsNot>` | | |
796 +-----------------------------------------+-----------------------------+---------------+
797 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
798 | <TestCase.assertIsNone>` | | |
799 +-----------------------------------------+-----------------------------+---------------+
800 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
801 | <TestCase.assertIsNotNone>` | | |
802 +-----------------------------------------+-----------------------------+---------------+
803 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
804 | <TestCase.assertIn>` | | |
805 +-----------------------------------------+-----------------------------+---------------+
806 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
807 | <TestCase.assertNotIn>` | | |
808 +-----------------------------------------+-----------------------------+---------------+
809 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
810 | <TestCase.assertIsInstance>` | | |
811 +-----------------------------------------+-----------------------------+---------------+
812 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
813 | <TestCase.assertNotIsInstance>` | | |
814 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000815
Ezio Melottib4dc2502011-05-06 15:01:41 +0300816 All the assert methods accept a *msg* argument that, if specified, is used
817 as the error message on failure (see also :data:`longMessage`).
818 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
819 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
820 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000821
Michael Foorde180d392011-01-28 19:51:48 +0000822 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000823
Michael Foorde180d392011-01-28 19:51:48 +0000824 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000825 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000826
Michael Foorde180d392011-01-28 19:51:48 +0000827 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000828 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200829 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000830 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000831 error message (see also the :ref:`list of type-specific methods
832 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000833
Raymond Hettinger35a88362009-04-09 00:08:24 +0000834 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200835 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000836
Michael Foord28a817e2010-02-09 00:03:57 +0000837 .. versionchanged:: 3.2
838 :meth:`assertMultiLineEqual` added as the default type equality
839 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000840
Benjamin Peterson52baa292009-03-24 00:56:30 +0000841
Michael Foorde180d392011-01-28 19:51:48 +0000842 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000843
Michael Foorde180d392011-01-28 19:51:48 +0000844 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000845 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000846
Ezio Melotti4370b302010-11-03 20:39:14 +0000847 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000848 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000849
Ezio Melotti4841fd62010-11-05 15:43:40 +0000850 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000851
Ezio Melotti4841fd62010-11-05 15:43:40 +0000852 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
853 is True`` (use ``assertIs(expr, True)`` for the latter). This method
854 should also be avoided when more specific methods are available (e.g.
855 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
856 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000857
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000858
Michael Foorde180d392011-01-28 19:51:48 +0000859 .. method:: assertIs(first, second, msg=None)
860 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000861
Michael Foorde180d392011-01-28 19:51:48 +0000862 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000863 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000864
Raymond Hettinger35a88362009-04-09 00:08:24 +0000865 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000866
867
Ezio Melotti4370b302010-11-03 20:39:14 +0000868 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000869 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000870
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300871 Test that *expr* is (or is not) ``None``.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000872
Ezio Melotti4370b302010-11-03 20:39:14 +0000873 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000874
875
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000876 .. method:: assertIn(first, second, msg=None)
877 assertNotIn(first, second, msg=None)
878
Ezio Melotti4841fd62010-11-05 15:43:40 +0000879 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000880
Raymond Hettinger35a88362009-04-09 00:08:24 +0000881 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000882
883
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000884 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000885 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000886
Ezio Melotti9794a262010-11-04 14:52:13 +0000887 Test that *obj* is (or is not) an instance of *cls* (which can be a
888 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200889 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000890
Ezio Melotti4370b302010-11-03 20:39:14 +0000891 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000892
893
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000894
Ezio Melottif418db22016-01-12 11:03:31 +0200895 It is also possible to check the production of exceptions, warnings, and
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200896 log messages using the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000897
Ezio Melotti4370b302010-11-03 20:39:14 +0000898 +---------------------------------------------------------+--------------------------------------+------------+
899 | Method | Checks that | New in |
900 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200901 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000902 | <TestCase.assertRaises>` | | |
903 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300904 | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
905 | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000906 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200907 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000908 | <TestCase.assertWarns>` | | |
909 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300910 | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
911 | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000912 +---------------------------------------------------------+--------------------------------------+------------+
Georg Brandled007d52013-11-24 16:09:26 +0100913 | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 |
914 | <TestCase.assertLogs>` | with minimum *level* | |
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200915 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000916
Georg Brandl7f01a132009-09-16 15:58:14 +0000917 .. method:: assertRaises(exception, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300918 assertRaises(exception, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000919
920 Test that an exception is raised when *callable* is called with any
921 positional or keyword arguments that are also passed to
922 :meth:`assertRaises`. The test passes if *exception* is raised, is an
923 error if another exception is raised, or fails if no exception is raised.
924 To catch any of a group of exceptions, a tuple containing the exception
925 classes may be passed as *exception*.
926
Ezio Melottib4dc2502011-05-06 15:01:41 +0300927 If only the *exception* and possibly the *msg* arguments are given,
928 return a context manager so that the code under test can be written
929 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000930
Michael Foord41531f22010-02-05 21:13:40 +0000931 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000932 do_something()
933
Ezio Melottib4dc2502011-05-06 15:01:41 +0300934 When used as a context manager, :meth:`assertRaises` accepts the
935 additional keyword argument *msg*.
936
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000937 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000938 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000939 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000940
Georg Brandl8a1caa22010-07-29 16:01:11 +0000941 with self.assertRaises(SomeException) as cm:
942 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000943
Georg Brandl8a1caa22010-07-29 16:01:11 +0000944 the_exception = cm.exception
945 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000946
Ezio Melotti49008232010-02-08 21:57:48 +0000947 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000948 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000949
Ezio Melotti49008232010-02-08 21:57:48 +0000950 .. versionchanged:: 3.2
951 Added the :attr:`exception` attribute.
952
Ezio Melottib4dc2502011-05-06 15:01:41 +0300953 .. versionchanged:: 3.3
954 Added the *msg* keyword argument when used as a context manager.
955
Benjamin Peterson52baa292009-03-24 00:56:30 +0000956
Ezio Melottied3a7d22010-12-01 02:32:32 +0000957 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300958 assertRaisesRegex(exception, regex, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000959
Ezio Melottied3a7d22010-12-01 02:32:32 +0000960 Like :meth:`assertRaises` but also tests that *regex* matches
961 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000962 a regular expression object or a string containing a regular expression
963 suitable for use by :func:`re.search`. Examples::
964
Terry Jan Reedyc4565a92013-06-29 13:15:43 -0400965 self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
Ezio Melottied3a7d22010-12-01 02:32:32 +0000966 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000967
968 or::
969
Ezio Melottied3a7d22010-12-01 02:32:32 +0000970 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000971 int('XYZ')
972
Georg Brandl419e3de2010-12-01 15:44:25 +0000973 .. versionadded:: 3.1
974 under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +0300975
Ezio Melottied3a7d22010-12-01 02:32:32 +0000976 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +0000977 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000978
Ezio Melottib4dc2502011-05-06 15:01:41 +0300979 .. versionchanged:: 3.3
980 Added the *msg* keyword argument when used as a context manager.
981
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000982
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000983 .. method:: assertWarns(warning, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300984 assertWarns(warning, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000985
986 Test that a warning is triggered when *callable* is called with any
987 positional or keyword arguments that are also passed to
988 :meth:`assertWarns`. The test passes if *warning* is triggered and
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400989 fails if it isn't. Any exception is an error.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000990 To catch any of a group of warnings, a tuple containing the warning
991 classes may be passed as *warnings*.
992
Ezio Melottib4dc2502011-05-06 15:01:41 +0300993 If only the *warning* and possibly the *msg* arguments are given,
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400994 return a context manager so that the code under test can be written
Ezio Melottib4dc2502011-05-06 15:01:41 +0300995 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000996
997 with self.assertWarns(SomeWarning):
998 do_something()
999
Terry Jan Reedy9eda66d2013-07-27 16:15:29 -04001000 When used as a context manager, :meth:`assertWarns` accepts the
Ezio Melottib4dc2502011-05-06 15:01:41 +03001001 additional keyword argument *msg*.
1002
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001003 The context manager will store the caught warning object in its
1004 :attr:`warning` attribute, and the source line which triggered the
1005 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1006 This can be useful if the intention is to perform additional checks
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001007 on the warning caught::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001008
1009 with self.assertWarns(SomeWarning) as cm:
1010 do_something()
1011
1012 self.assertIn('myfile.py', cm.filename)
1013 self.assertEqual(320, cm.lineno)
1014
1015 This method works regardless of the warning filters in place when it
1016 is called.
1017
1018 .. versionadded:: 3.2
1019
Ezio Melottib4dc2502011-05-06 15:01:41 +03001020 .. versionchanged:: 3.3
1021 Added the *msg* keyword argument when used as a context manager.
1022
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001023
Ezio Melottied3a7d22010-12-01 02:32:32 +00001024 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001025 assertWarnsRegex(warning, regex, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001026
Ezio Melottied3a7d22010-12-01 02:32:32 +00001027 Like :meth:`assertWarns` but also tests that *regex* matches on the
1028 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001029 object or a string containing a regular expression suitable for use
1030 by :func:`re.search`. Example::
1031
Ezio Melottied3a7d22010-12-01 02:32:32 +00001032 self.assertWarnsRegex(DeprecationWarning,
1033 r'legacy_function\(\) is deprecated',
1034 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001035
1036 or::
1037
Ezio Melottied3a7d22010-12-01 02:32:32 +00001038 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001039 frobnicate('/etc/passwd')
1040
1041 .. versionadded:: 3.2
1042
Ezio Melottib4dc2502011-05-06 15:01:41 +03001043 .. versionchanged:: 3.3
1044 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001045
Antoine Pitrou0715b9f2013-09-14 19:45:47 +02001046 .. method:: assertLogs(logger=None, level=None)
1047
1048 A context manager to test that at least one message is logged on
1049 the *logger* or one of its children, with at least the given
1050 *level*.
1051
1052 If given, *logger* should be a :class:`logging.Logger` object or a
1053 :class:`str` giving the name of a logger. The default is the root
1054 logger, which will catch all messages.
1055
1056 If given, *level* should be either a numeric logging level or
1057 its string equivalent (for example either ``"ERROR"`` or
1058 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`.
1059
1060 The test passes if at least one message emitted inside the ``with``
1061 block matches the *logger* and *level* conditions, otherwise it fails.
1062
1063 The object returned by the context manager is a recording helper
1064 which keeps tracks of the matching log messages. It has two
1065 attributes:
1066
1067 .. attribute:: records
1068
1069 A list of :class:`logging.LogRecord` objects of the matching
1070 log messages.
1071
1072 .. attribute:: output
1073
1074 A list of :class:`str` objects with the formatted output of
1075 matching messages.
1076
1077 Example::
1078
1079 with self.assertLogs('foo', level='INFO') as cm:
1080 logging.getLogger('foo').info('first message')
1081 logging.getLogger('foo.bar').error('second message')
1082 self.assertEqual(cm.output, ['INFO:foo:first message',
1083 'ERROR:foo.bar:second message'])
1084
1085 .. versionadded:: 3.4
1086
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001087
Ezio Melotti4370b302010-11-03 20:39:14 +00001088 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001089
Ezio Melotti4370b302010-11-03 20:39:14 +00001090 +---------------------------------------+--------------------------------+--------------+
1091 | Method | Checks that | New in |
1092 +=======================================+================================+==============+
1093 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1094 | <TestCase.assertAlmostEqual>` | | |
1095 +---------------------------------------+--------------------------------+--------------+
1096 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1097 | <TestCase.assertNotAlmostEqual>` | | |
1098 +---------------------------------------+--------------------------------+--------------+
1099 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1100 | <TestCase.assertGreater>` | | |
1101 +---------------------------------------+--------------------------------+--------------+
1102 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1103 | <TestCase.assertGreaterEqual>` | | |
1104 +---------------------------------------+--------------------------------+--------------+
1105 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1106 | <TestCase.assertLess>` | | |
1107 +---------------------------------------+--------------------------------+--------------+
1108 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1109 | <TestCase.assertLessEqual>` | | |
1110 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001111 | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001112 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001113 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001114 | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001115 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001116 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001117 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001118 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001119 | | regardless of their order | |
1120 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001121
1122
Michael Foorde180d392011-01-28 19:51:48 +00001123 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1124 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001125
Michael Foorde180d392011-01-28 19:51:48 +00001126 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001127 equal by computing the difference, rounding to the given number of
1128 decimal *places* (default 7), and comparing to zero. Note that these
1129 methods round the values to the given number of *decimal places* (i.e.
1130 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001131
Ezio Melotti4370b302010-11-03 20:39:14 +00001132 If *delta* is supplied instead of *places* then the difference
Ezio Melottid51914c2013-08-11 13:04:50 +03001133 between *first* and *second* must be less or equal to (or greater than) *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001134
Ezio Melotti4370b302010-11-03 20:39:14 +00001135 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001136
Ezio Melotti4370b302010-11-03 20:39:14 +00001137 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001138 :meth:`assertAlmostEqual` automatically considers almost equal objects
1139 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1140 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001141
Ezio Melotti4370b302010-11-03 20:39:14 +00001142
Michael Foorde180d392011-01-28 19:51:48 +00001143 .. method:: assertGreater(first, second, msg=None)
1144 assertGreaterEqual(first, second, msg=None)
1145 assertLess(first, second, msg=None)
1146 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001147
Michael Foorde180d392011-01-28 19:51:48 +00001148 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001149 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001150
1151 >>> self.assertGreaterEqual(3, 4)
1152 AssertionError: "3" unexpectedly not greater than or equal to "4"
1153
1154 .. versionadded:: 3.1
1155
1156
Ezio Melottied3a7d22010-12-01 02:32:32 +00001157 .. method:: assertRegex(text, regex, msg=None)
1158 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001159
Ezio Melottied3a7d22010-12-01 02:32:32 +00001160 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001161 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001162 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001163 may be a regular expression object or a string containing a regular
1164 expression suitable for use by :func:`re.search`.
1165
Georg Brandl419e3de2010-12-01 15:44:25 +00001166 .. versionadded:: 3.1
1167 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001168 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001169 The method ``assertRegexpMatches()`` has been renamed to
1170 :meth:`.assertRegex`.
1171 .. versionadded:: 3.2
1172 :meth:`.assertNotRegex`.
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001173 .. versionadded:: 3.5
1174 The name ``assertNotRegexpMatches`` is a deprecated alias
1175 for :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001176
1177
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001178 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001179
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001180 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001181 regardless of their order. When they don't, an error message listing the
1182 differences between the sequences will be generated.
1183
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001184 Duplicate elements are *not* ignored when comparing *first* and
1185 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001186 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001187 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001188 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001189
Ezio Melotti4370b302010-11-03 20:39:14 +00001190 .. versionadded:: 3.2
1191
Ezio Melotti4370b302010-11-03 20:39:14 +00001192
Ezio Melotti22170ed2010-11-20 09:57:27 +00001193 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001194
Ezio Melotti22170ed2010-11-20 09:57:27 +00001195 The :meth:`assertEqual` method dispatches the equality check for objects of
1196 the same type to different type-specific methods. These methods are already
1197 implemented for most of the built-in types, but it's also possible to
1198 register new methods using :meth:`addTypeEqualityFunc`:
1199
1200 .. method:: addTypeEqualityFunc(typeobj, function)
1201
1202 Registers a type-specific method called by :meth:`assertEqual` to check
1203 if two objects of exactly the same *typeobj* (not subclasses) compare
1204 equal. *function* must take two positional arguments and a third msg=None
1205 keyword argument just as :meth:`assertEqual` does. It must raise
1206 :data:`self.failureException(msg) <failureException>` when inequality
1207 between the first two parameters is detected -- possibly providing useful
1208 information and explaining the inequalities in details in the error
1209 message.
1210
1211 .. versionadded:: 3.1
1212
1213 The list of type-specific methods automatically used by
1214 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1215 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001216
1217 +-----------------------------------------+-----------------------------+--------------+
1218 | Method | Used to compare | New in |
1219 +=========================================+=============================+==============+
1220 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1221 | <TestCase.assertMultiLineEqual>` | | |
1222 +-----------------------------------------+-----------------------------+--------------+
1223 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1224 | <TestCase.assertSequenceEqual>` | | |
1225 +-----------------------------------------+-----------------------------+--------------+
1226 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1227 | <TestCase.assertListEqual>` | | |
1228 +-----------------------------------------+-----------------------------+--------------+
1229 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1230 | <TestCase.assertTupleEqual>` | | |
1231 +-----------------------------------------+-----------------------------+--------------+
1232 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1233 | <TestCase.assertSetEqual>` | | |
1234 +-----------------------------------------+-----------------------------+--------------+
1235 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1236 | <TestCase.assertDictEqual>` | | |
1237 +-----------------------------------------+-----------------------------+--------------+
1238
1239
1240
Michael Foorde180d392011-01-28 19:51:48 +00001241 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001242
Michael Foorde180d392011-01-28 19:51:48 +00001243 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001244 When not equal a diff of the two strings highlighting the differences
1245 will be included in the error message. This method is used by default
1246 when comparing strings with :meth:`assertEqual`.
1247
Ezio Melotti4370b302010-11-03 20:39:14 +00001248 .. versionadded:: 3.1
1249
1250
Michael Foorde180d392011-01-28 19:51:48 +00001251 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001252
1253 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001254 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001255 be raised. If the sequences are different an error message is
1256 constructed that shows the difference between the two.
1257
Ezio Melotti22170ed2010-11-20 09:57:27 +00001258 This method is not called directly by :meth:`assertEqual`, but
1259 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001260 :meth:`assertTupleEqual`.
1261
1262 .. versionadded:: 3.1
1263
1264
Michael Foorde180d392011-01-28 19:51:48 +00001265 .. method:: assertListEqual(first, second, msg=None)
1266 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001267
Ezio Melotti49ccd512012-08-29 17:50:42 +03001268 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001269 constructed that shows only the differences between the two. An error
1270 is also raised if either of the parameters are of the wrong type.
1271 These methods are used by default when comparing lists or tuples with
1272 :meth:`assertEqual`.
1273
Ezio Melotti4370b302010-11-03 20:39:14 +00001274 .. versionadded:: 3.1
1275
1276
Michael Foorde180d392011-01-28 19:51:48 +00001277 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001278
1279 Tests that two sets are equal. If not, an error message is constructed
1280 that lists the differences between the sets. This method is used by
1281 default when comparing sets or frozensets with :meth:`assertEqual`.
1282
Michael Foorde180d392011-01-28 19:51:48 +00001283 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001284 method.
1285
Ezio Melotti4370b302010-11-03 20:39:14 +00001286 .. versionadded:: 3.1
1287
1288
Michael Foorde180d392011-01-28 19:51:48 +00001289 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001290
1291 Test that two dictionaries are equal. If not, an error message is
1292 constructed that shows the differences in the dictionaries. This
1293 method will be used by default to compare dictionaries in
1294 calls to :meth:`assertEqual`.
1295
Ezio Melotti4370b302010-11-03 20:39:14 +00001296 .. versionadded:: 3.1
1297
1298
1299
Ezio Melotti22170ed2010-11-20 09:57:27 +00001300 .. _other-methods-and-attrs:
1301
Ezio Melotti4370b302010-11-03 20:39:14 +00001302 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001303
Benjamin Peterson52baa292009-03-24 00:56:30 +00001304
Georg Brandl7f01a132009-09-16 15:58:14 +00001305 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001306
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001307 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001308 the error message.
1309
1310
1311 .. attribute:: failureException
1312
1313 This class attribute gives the exception raised by the test method. If a
1314 test framework needs to use a specialized exception, possibly to carry
1315 additional information, it must subclass this exception in order to "play
1316 fair" with the framework. The initial value of this attribute is
1317 :exc:`AssertionError`.
1318
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001319
1320 .. attribute:: longMessage
1321
Guido van Rossum4a452352016-10-13 14:23:01 -07001322 This class attribute determines what happens when a custom failure message
1323 is passed as the msg argument to an assertXYY call that fails.
1324 ``True`` is the default value. In this case, the custom message is appended
1325 to the end of the standard failure message.
1326 When set to ``False``, the custom message replaces the standard message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001327
Guido van Rossum4a452352016-10-13 14:23:01 -07001328 The class setting can be overridden in individual test methods by assigning
1329 an instance attribute, self.longMessage, to ``True`` or ``False`` before
1330 calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001331
Guido van Rossum4a452352016-10-13 14:23:01 -07001332 The class setting gets reset before each test call.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001333
Raymond Hettinger35a88362009-04-09 00:08:24 +00001334 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001335
1336
Michael Foord98b3e762010-06-05 21:59:55 +00001337 .. attribute:: maxDiff
1338
1339 This attribute controls the maximum length of diffs output by assert
1340 methods that report diffs on failure. It defaults to 80*8 characters.
1341 Assert methods affected by this attribute are
1342 :meth:`assertSequenceEqual` (including all the sequence comparison
1343 methods that delegate to it), :meth:`assertDictEqual` and
1344 :meth:`assertMultiLineEqual`.
1345
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001346 Setting ``maxDiff`` to ``None`` means that there is no maximum length of
Michael Foord98b3e762010-06-05 21:59:55 +00001347 diffs.
1348
1349 .. versionadded:: 3.2
1350
1351
Benjamin Peterson52baa292009-03-24 00:56:30 +00001352 Testing frameworks can use the following methods to collect information on
1353 the test:
1354
1355
1356 .. method:: countTestCases()
1357
1358 Return the number of tests represented by this test object. For
1359 :class:`TestCase` instances, this will always be ``1``.
1360
1361
1362 .. method:: defaultTestResult()
1363
1364 Return an instance of the test result class that should be used for this
1365 test case class (if no other result instance is provided to the
1366 :meth:`run` method).
1367
1368 For :class:`TestCase` instances, this will always be an instance of
1369 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1370 as necessary.
1371
1372
1373 .. method:: id()
1374
1375 Return a string identifying the specific test case. This is usually the
1376 full name of the test method, including the module and class name.
1377
1378
1379 .. method:: shortDescription()
1380
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001381 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001382 has been provided. The default implementation of this method
1383 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001384 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001385
Georg Brandl419e3de2010-12-01 15:44:25 +00001386 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001387 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001388 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001389 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001390 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001391
Georg Brandl116aa622007-08-15 14:28:22 +00001392
Georg Brandl7f01a132009-09-16 15:58:14 +00001393 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001394
1395 Add a function to be called after :meth:`tearDown` to cleanup resources
1396 used during the test. Functions will be called in reverse order to the
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +03001397 order they are added (:abbr:`LIFO (last-in, first-out)`). They
1398 are called with any arguments and keyword arguments passed into
1399 :meth:`addCleanup` when they are added.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001400
1401 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1402 then any cleanup functions added will still be called.
1403
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001404 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001405
1406
1407 .. method:: doCleanups()
1408
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001409 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001410 after :meth:`setUp` if :meth:`setUp` raises an exception.
1411
1412 It is responsible for calling all the cleanup functions added by
1413 :meth:`addCleanup`. If you need cleanup functions to be called
1414 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1415 yourself.
1416
1417 :meth:`doCleanups` pops methods off the stack of cleanup
1418 functions one at a time, so it can be called at any time.
1419
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001420 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001421
1422
Georg Brandl7f01a132009-09-16 15:58:14 +00001423.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001424
1425 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001426 allows the test runner to drive the test, but does not provide the methods
1427 which test code can use to check and report errors. This is used to create
1428 test cases using legacy test code, allowing it to be integrated into a
1429 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001430
1431
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001432.. _deprecated-aliases:
1433
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001434Deprecated aliases
1435##################
1436
1437For historical reasons, some of the :class:`TestCase` methods had one or more
1438aliases that are now deprecated. The following table lists the correct names
1439along with their deprecated aliases:
1440
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001441 ============================== ====================== =======================
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001442 Method Name Deprecated alias Deprecated alias
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001443 ============================== ====================== =======================
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001444 :meth:`.assertEqual` failUnlessEqual assertEquals
1445 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1446 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001447 :meth:`.assertFalse` failIf
1448 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001449 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1450 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001451 :meth:`.assertRegex` assertRegexpMatches
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001452 :meth:`.assertNotRegex` assertNotRegexpMatches
Ezio Melottied3a7d22010-12-01 02:32:32 +00001453 :meth:`.assertRaisesRegex` assertRaisesRegexp
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001454 ============================== ====================== =======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001455
Ezio Melotti361467e2011-04-03 17:37:58 +03001456 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001457 the fail* aliases listed in the second column.
1458 .. deprecated:: 3.2
1459 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001460 .. deprecated:: 3.2
1461 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001462 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`.
1463 .. deprecated:: 3.5
1464 the ``assertNotRegexpMatches`` name in favor of :meth:`.assertNotRegex`.
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001465
Benjamin Peterson52baa292009-03-24 00:56:30 +00001466.. _testsuite-objects:
1467
Benjamin Peterson52baa292009-03-24 00:56:30 +00001468Grouping tests
1469~~~~~~~~~~~~~~
1470
Georg Brandl7f01a132009-09-16 15:58:14 +00001471.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001472
Martin Panter37f183d2017-01-18 12:06:38 +00001473 This class represents an aggregation of individual test cases and test suites.
Georg Brandl116aa622007-08-15 14:28:22 +00001474 The class presents the interface needed by the test runner to allow it to be run
1475 as any other test case. Running a :class:`TestSuite` instance is the same as
1476 iterating over the suite, running each test individually.
1477
1478 If *tests* is given, it must be an iterable of individual test cases or other
1479 test suites that will be used to build the suite initially. Additional methods
1480 are provided to add test cases and suites to the collection later on.
1481
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001482 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1483 they do not actually implement a test. Instead, they are used to aggregate
1484 tests into groups of tests that should be run together. Some additional
1485 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001486
1487
1488 .. method:: TestSuite.addTest(test)
1489
1490 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1491
1492
1493 .. method:: TestSuite.addTests(tests)
1494
1495 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1496 instances to this test suite.
1497
Benjamin Petersond2397752009-06-27 23:45:02 +00001498 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1499 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001500
1501 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1502
1503
1504 .. method:: run(result)
1505
1506 Run the tests associated with this suite, collecting the result into the
1507 test result object passed as *result*. Note that unlike
1508 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1509 be passed in.
1510
1511
1512 .. method:: debug()
1513
1514 Run the tests associated with this suite without collecting the
1515 result. This allows exceptions raised by the test to be propagated to the
1516 caller and can be used to support running tests under a debugger.
1517
1518
1519 .. method:: countTestCases()
1520
1521 Return the number of tests represented by this test object, including all
1522 individual tests and sub-suites.
1523
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001524
1525 .. method:: __iter__()
1526
1527 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1528 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
Andrew Svetloveb973682013-08-28 21:28:38 +03001529 that this method may be called several times on a single suite (for
1530 example when counting tests or comparing for equality) so the tests
1531 returned by repeated iterations before :meth:`TestSuite.run` must be the
1532 same for each call iteration. After :meth:`TestSuite.run`, callers should
1533 not rely on the tests returned by this method unless the caller uses a
1534 subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
1535 test references.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001536
Georg Brandl853947a2010-01-31 18:53:23 +00001537 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001538 In earlier versions the :class:`TestSuite` accessed tests directly rather
1539 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1540 for providing tests.
1541
Andrew Svetloveb973682013-08-28 21:28:38 +03001542 .. versionchanged:: 3.4
1543 In earlier versions the :class:`TestSuite` held references to each
1544 :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
1545 that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
1546
Benjamin Peterson52baa292009-03-24 00:56:30 +00001547 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1548 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1549
1550
Benjamin Peterson52baa292009-03-24 00:56:30 +00001551Loading and running tests
1552~~~~~~~~~~~~~~~~~~~~~~~~~
1553
Georg Brandl116aa622007-08-15 14:28:22 +00001554.. class:: TestLoader()
1555
Benjamin Peterson52baa292009-03-24 00:56:30 +00001556 The :class:`TestLoader` class is used to create test suites from classes and
1557 modules. Normally, there is no need to create an instance of this class; the
1558 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001559 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1560 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001561
Robert Collinsf920c212014-10-20 13:24:05 +13001562 :class:`TestLoader` objects have the following attributes:
1563
1564
1565 .. attribute:: errors
1566
1567 A list of the non-fatal errors encountered while loading tests. Not reset
1568 by the loader at any point. Fatal errors are signalled by the relevant
1569 a method raising an exception to the caller. Non-fatal errors are also
1570 indicated by a synthetic test that will raise the original error when
1571 run.
1572
1573 .. versionadded:: 3.5
1574
1575
Benjamin Peterson52baa292009-03-24 00:56:30 +00001576 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001577
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001578
Benjamin Peterson52baa292009-03-24 00:56:30 +00001579 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001580
Martin Panter37f183d2017-01-18 12:06:38 +00001581 Return a suite of all test cases contained in the :class:`TestCase`\ -derived
Benjamin Peterson52baa292009-03-24 00:56:30 +00001582 :class:`testCaseClass`.
1583
Robert Collinse02f6c22015-07-23 06:37:26 +12001584 A test case instance is created for each method named by
1585 :meth:`getTestCaseNames`. By default these are the method names
1586 beginning with ``test``. If :meth:`getTestCaseNames` returns no
1587 methods, but the :meth:`runTest` method is implemented, a single test
1588 case is created for that method instead.
1589
Benjamin Peterson52baa292009-03-24 00:56:30 +00001590
Barry Warsawd78742a2014-09-08 14:21:37 -04001591 .. method:: loadTestsFromModule(module, pattern=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001592
Martin Panter37f183d2017-01-18 12:06:38 +00001593 Return a suite of all test cases contained in the given module. This
Benjamin Peterson52baa292009-03-24 00:56:30 +00001594 method searches *module* for classes derived from :class:`TestCase` and
1595 creates an instance of the class for each test method defined for the
1596 class.
1597
Georg Brandle720c0a2009-04-27 16:20:50 +00001598 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001599
1600 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1601 convenient in sharing fixtures and helper functions, defining test
1602 methods on base classes that are not intended to be instantiated
1603 directly does not play well with this method. Doing so, however, can
1604 be useful when the fixtures are different and defined in subclasses.
1605
Benjamin Petersond2397752009-06-27 23:45:02 +00001606 If a module provides a ``load_tests`` function it will be called to
1607 load the tests. This allows modules to customize test loading.
Barry Warsawd78742a2014-09-08 14:21:37 -04001608 This is the `load_tests protocol`_. The *pattern* argument is passed as
1609 the third argument to ``load_tests``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001610
Georg Brandl853947a2010-01-31 18:53:23 +00001611 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001612 Support for ``load_tests`` added.
1613
Barry Warsawd78742a2014-09-08 14:21:37 -04001614 .. versionchanged:: 3.5
1615 The undocumented and unofficial *use_load_tests* default argument is
1616 deprecated and ignored, although it is still accepted for backward
1617 compatibility. The method also now accepts a keyword-only argument
1618 *pattern* which is passed to ``load_tests`` as the third argument.
1619
Benjamin Peterson52baa292009-03-24 00:56:30 +00001620
Georg Brandl7f01a132009-09-16 15:58:14 +00001621 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001622
Martin Panter37f183d2017-01-18 12:06:38 +00001623 Return a suite of all test cases given a string specifier.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001624
1625 The specifier *name* is a "dotted name" that may resolve either to a
1626 module, a test case class, a test method within a test case class, a
1627 :class:`TestSuite` instance, or a callable object which returns a
1628 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1629 applied in the order listed here; that is, a method on a possible test
1630 case class will be picked up as "a test method within a test case class",
1631 rather than "a callable object".
1632
1633 For example, if you have a module :mod:`SampleTests` containing a
1634 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1635 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001636 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1637 return a suite which will run all three test methods. Using the specifier
1638 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1639 suite which will run only the :meth:`test_two` test method. The specifier
1640 can refer to modules and packages which have not been imported; they will
1641 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001642
1643 The method optionally resolves *name* relative to the given *module*.
1644
Martin Panter536d70e2017-01-14 08:23:08 +00001645 .. versionchanged:: 3.5
1646 If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing
1647 *name* then a synthetic test that raises that error when run will be
1648 returned. These errors are included in the errors accumulated by
1649 self.errors.
Robert Collins659dd622014-10-30 08:27:27 +13001650
Benjamin Peterson52baa292009-03-24 00:56:30 +00001651
Georg Brandl7f01a132009-09-16 15:58:14 +00001652 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001653
1654 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1655 than a single name. The return value is a test suite which supports all
1656 the tests defined for each name.
1657
1658
1659 .. method:: getTestCaseNames(testCaseClass)
1660
1661 Return a sorted sequence of method names found within *testCaseClass*;
1662 this should be a subclass of :class:`TestCase`.
1663
Benjamin Petersond2397752009-06-27 23:45:02 +00001664
1665 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1666
Larry Hastings3732ed22014-03-15 21:13:56 -07001667 Find all the test modules by recursing into subdirectories from the
1668 specified start directory, and return a TestSuite object containing them.
1669 Only test files that match *pattern* will be loaded. (Using shell style
1670 pattern matching.) Only module names that are importable (i.e. are valid
1671 Python identifiers) will be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001672
1673 All test modules must be importable from the top level of the project. If
1674 the start directory is not the top level directory then the top level
1675 directory must be specified separately.
1676
Barry Warsawd78742a2014-09-08 14:21:37 -04001677 If importing a module fails, for example due to a syntax error, then
1678 this will be recorded as a single error and discovery will continue. If
1679 the import failure is due to :exc:`SkipTest` being raised, it will be
1680 recorded as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001681
Barry Warsawd78742a2014-09-08 14:21:37 -04001682 If a package (a directory containing a file named :file:`__init__.py`) is
1683 found, the package will be checked for a ``load_tests`` function. If this
Robert Collinsbf2bda32014-11-05 03:09:01 +13001684 exists then it will be called
1685 ``package.load_tests(loader, tests, pattern)``. Test discovery takes care
1686 to ensure that a package is only checked for tests once during an
1687 invocation, even if the load_tests function itself calls
1688 ``loader.discover``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001689
Barry Warsawd78742a2014-09-08 14:21:37 -04001690 If ``load_tests`` exists then discovery does *not* recurse into the
1691 package, ``load_tests`` is responsible for loading all tests in the
1692 package.
Benjamin Petersond2397752009-06-27 23:45:02 +00001693
1694 The pattern is deliberately not stored as a loader attribute so that
1695 packages can continue discovery themselves. *top_level_dir* is stored so
1696 ``load_tests`` does not need to pass this argument in to
1697 ``loader.discover()``.
1698
Benjamin Petersonb48af542010-04-11 20:43:16 +00001699 *start_dir* can be a dotted module name as well as a directory.
1700
Georg Brandl853947a2010-01-31 18:53:23 +00001701 .. versionadded:: 3.2
1702
Ezio Melottieae2b382013-03-01 14:47:50 +02001703 .. versionchanged:: 3.4
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001704 Modules that raise :exc:`SkipTest` on import are recorded as skips,
Larry Hastings3732ed22014-03-15 21:13:56 -07001705 not errors.
1706 Discovery works for :term:`namespace packages <namespace package>`.
1707 Paths are sorted before being imported so that execution order is
1708 the same even if the underlying file system's ordering is not
1709 dependent on file name.
Michael Foord80cbc9e2013-03-18 17:50:12 -07001710
Barry Warsawd78742a2014-09-08 14:21:37 -04001711 .. versionchanged:: 3.5
1712 Found packages are now checked for ``load_tests`` regardless of
1713 whether their path matches *pattern*, because it is impossible for
1714 a package name to match the default pattern.
1715
Benjamin Petersond2397752009-06-27 23:45:02 +00001716
Benjamin Peterson52baa292009-03-24 00:56:30 +00001717 The following attributes of a :class:`TestLoader` can be configured either by
1718 subclassing or assignment on an instance:
1719
1720
1721 .. attribute:: testMethodPrefix
1722
1723 String giving the prefix of method names which will be interpreted as test
1724 methods. The default value is ``'test'``.
1725
1726 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1727 methods.
1728
1729
1730 .. attribute:: sortTestMethodsUsing
1731
1732 Function to be used to compare method names when sorting them in
1733 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1734
1735
1736 .. attribute:: suiteClass
1737
1738 Callable object that constructs a test suite from a list of tests. No
1739 methods on the resulting object are needed. The default value is the
1740 :class:`TestSuite` class.
1741
1742 This affects all the :meth:`loadTestsFrom\*` methods.
1743
1744
Benjamin Peterson52baa292009-03-24 00:56:30 +00001745.. class:: TestResult
1746
1747 This class is used to compile information about which tests have succeeded
1748 and which have failed.
1749
1750 A :class:`TestResult` object stores the results of a set of tests. The
1751 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1752 properly recorded; test authors do not need to worry about recording the
1753 outcome of tests.
1754
1755 Testing frameworks built on top of :mod:`unittest` may want access to the
1756 :class:`TestResult` object generated by running a set of tests for reporting
1757 purposes; a :class:`TestResult` instance is returned by the
1758 :meth:`TestRunner.run` method for this purpose.
1759
1760 :class:`TestResult` instances have the following attributes that will be of
1761 interest when inspecting the results of running a set of tests:
1762
1763
1764 .. attribute:: errors
1765
1766 A list containing 2-tuples of :class:`TestCase` instances and strings
1767 holding formatted tracebacks. Each tuple represents a test which raised an
1768 unexpected exception.
1769
Benjamin Peterson52baa292009-03-24 00:56:30 +00001770 .. attribute:: failures
1771
1772 A list containing 2-tuples of :class:`TestCase` instances and strings
1773 holding formatted tracebacks. Each tuple represents a test where a failure
Ezio Melottie2202362013-09-07 15:19:30 +03001774 was explicitly signalled using the :meth:`TestCase.assert\*` methods.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001775
Benjamin Peterson52baa292009-03-24 00:56:30 +00001776 .. attribute:: skipped
1777
1778 A list containing 2-tuples of :class:`TestCase` instances and strings
1779 holding the reason for skipping the test.
1780
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001781 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001782
1783 .. attribute:: expectedFailures
1784
Georg Brandl6faee4e2010-09-21 14:48:28 +00001785 A list containing 2-tuples of :class:`TestCase` instances and strings
1786 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001787 of the test case.
1788
1789 .. attribute:: unexpectedSuccesses
1790
1791 A list containing :class:`TestCase` instances that were marked as expected
1792 failures, but succeeded.
1793
1794 .. attribute:: shouldStop
1795
1796 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1797
Benjamin Peterson52baa292009-03-24 00:56:30 +00001798 .. attribute:: testsRun
1799
1800 The total number of tests run so far.
1801
Georg Brandl12037202010-12-02 22:35:25 +00001802 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001803
1804 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1805 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1806 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1807 fails or errors. Any output is also attached to the failure / error message.
1808
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001809 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001810
Benjamin Petersonb48af542010-04-11 20:43:16 +00001811 .. attribute:: failfast
1812
1813 If set to true :meth:`stop` will be called on the first failure or error,
1814 halting the test run.
1815
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001816 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001817
Robert Collinsf0c819a2015-03-06 13:46:35 +13001818 .. attribute:: tb_locals
1819
1820 If set to true then local variables will be shown in tracebacks.
1821
1822 .. versionadded:: 3.5
Benjamin Petersonb48af542010-04-11 20:43:16 +00001823
Benjamin Peterson52baa292009-03-24 00:56:30 +00001824 .. method:: wasSuccessful()
1825
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001826 Return ``True`` if all tests run so far have passed, otherwise returns
1827 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001828
Gregory P. Smith5a6d4bf2014-01-20 01:11:18 -08001829 .. versionchanged:: 3.4
1830 Returns ``False`` if there were any :attr:`unexpectedSuccesses`
1831 from tests marked with the :func:`expectedFailure` decorator.
1832
Benjamin Peterson52baa292009-03-24 00:56:30 +00001833 .. method:: stop()
1834
1835 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001836 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001837 :class:`TestRunner` objects should respect this flag and return without
1838 running any additional tests.
1839
1840 For example, this feature is used by the :class:`TextTestRunner` class to
1841 stop the test framework when the user signals an interrupt from the
1842 keyboard. Interactive tools which provide :class:`TestRunner`
1843 implementations can use this in a similar manner.
1844
1845 The following methods of the :class:`TestResult` class are used to maintain
1846 the internal data structures, and may be extended in subclasses to support
1847 additional reporting requirements. This is particularly useful in building
1848 tools which support interactive reporting while tests are being run.
1849
1850
1851 .. method:: startTest(test)
1852
1853 Called when the test case *test* is about to be run.
1854
Benjamin Peterson52baa292009-03-24 00:56:30 +00001855 .. method:: stopTest(test)
1856
1857 Called after the test case *test* has been executed, regardless of the
1858 outcome.
1859
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001860 .. method:: startTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001861
1862 Called once before any tests are executed.
1863
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001864 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001865
1866
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001867 .. method:: stopTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001868
Ezio Melotti176d6c42010-01-27 20:58:07 +00001869 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001870
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001871 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001872
1873
Benjamin Peterson52baa292009-03-24 00:56:30 +00001874 .. method:: addError(test, err)
1875
Ezio Melottie64a91a2013-09-07 15:23:36 +03001876 Called when the test case *test* raises an unexpected exception. *err* is a
Benjamin Peterson52baa292009-03-24 00:56:30 +00001877 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1878 traceback)``.
1879
1880 The default implementation appends a tuple ``(test, formatted_err)`` to
1881 the instance's :attr:`errors` attribute, where *formatted_err* is a
1882 formatted traceback derived from *err*.
1883
1884
1885 .. method:: addFailure(test, err)
1886
Benjamin Petersond2397752009-06-27 23:45:02 +00001887 Called when the test case *test* signals a failure. *err* is a tuple of
1888 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001889
1890 The default implementation appends a tuple ``(test, formatted_err)`` to
1891 the instance's :attr:`failures` attribute, where *formatted_err* is a
1892 formatted traceback derived from *err*.
1893
1894
1895 .. method:: addSuccess(test)
1896
1897 Called when the test case *test* succeeds.
1898
1899 The default implementation does nothing.
1900
1901
1902 .. method:: addSkip(test, reason)
1903
1904 Called when the test case *test* is skipped. *reason* is the reason the
1905 test gave for skipping.
1906
1907 The default implementation appends a tuple ``(test, reason)`` to the
1908 instance's :attr:`skipped` attribute.
1909
1910
1911 .. method:: addExpectedFailure(test, err)
1912
1913 Called when the test case *test* fails, but was marked with the
1914 :func:`expectedFailure` decorator.
1915
1916 The default implementation appends a tuple ``(test, formatted_err)`` to
1917 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1918 is a formatted traceback derived from *err*.
1919
1920
1921 .. method:: addUnexpectedSuccess(test)
1922
1923 Called when the test case *test* was marked with the
1924 :func:`expectedFailure` decorator, but succeeded.
1925
1926 The default implementation appends the test to the instance's
1927 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001928
Georg Brandl67b21b72010-08-17 15:07:14 +00001929
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001930 .. method:: addSubTest(test, subtest, outcome)
1931
1932 Called when a subtest finishes. *test* is the test case
1933 corresponding to the test method. *subtest* is a custom
1934 :class:`TestCase` instance describing the subtest.
1935
1936 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
1937 it failed with an exception where *outcome* is a tuple of the form
1938 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1939
1940 The default implementation does nothing when the outcome is a
1941 success, and records subtest failures as normal failures.
1942
1943 .. versionadded:: 3.4
1944
1945
Michael Foord34c94622010-02-10 15:51:42 +00001946.. class:: TextTestResult(stream, descriptions, verbosity)
1947
Georg Brandl67b21b72010-08-17 15:07:14 +00001948 A concrete implementation of :class:`TestResult` used by the
1949 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001950
Georg Brandl67b21b72010-08-17 15:07:14 +00001951 .. versionadded:: 3.2
1952 This class was previously named ``_TextTestResult``. The old name still
1953 exists as an alias but is deprecated.
1954
Georg Brandl116aa622007-08-15 14:28:22 +00001955
1956.. data:: defaultTestLoader
1957
1958 Instance of the :class:`TestLoader` class intended to be shared. If no
1959 customization of the :class:`TestLoader` is needed, this instance can be used
1960 instead of repeatedly creating new instances.
1961
1962
Ezio Melotti9c939bc2013-05-07 09:46:30 +03001963.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \
Robert Collinsf0c819a2015-03-06 13:46:35 +13001964 buffer=False, resultclass=None, warnings=None, *, tb_locals=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001965
Michael Foordd218e952011-01-03 12:55:11 +00001966 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001967 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001968 has a few configurable parameters, but is essentially very simple. Graphical
Robert Collinsf0c819a2015-03-06 13:46:35 +13001969 applications which run test suites should provide alternate implementations. Such
1970 implementations should accept ``**kwargs`` as the interface to construct runners
1971 changes when features are added to unittest.
Georg Brandl116aa622007-08-15 14:28:22 +00001972
Ezio Melotti60901872010-12-01 00:56:10 +00001973 By default this runner shows :exc:`DeprecationWarning`,
Senthil Kumaran409ea5d2014-02-08 14:28:03 -08001974 :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and
Larry Hastingsad88d7a2014-02-10 04:26:10 -08001975 :exc:`ImportWarning` even if they are :ref:`ignored by default
1976 <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest
1977 methods <deprecated-aliases>` are also special-cased and, when the warning
1978 filters are ``'default'`` or ``'always'``, they will appear only once
1979 per-module, in order to avoid too many warning messages. This behavior can
Martin Panterb8c5f542016-10-30 04:20:23 +00001980 be overridden using Python's :option:`!-Wd` or :option:`!-Wa` options
1981 (see :ref:`Warning control <using-on-warnings>`) and leaving
Larry Hastingsad88d7a2014-02-10 04:26:10 -08001982 *warnings* to ``None``.
Ezio Melotti60901872010-12-01 00:56:10 +00001983
Michael Foordd218e952011-01-03 12:55:11 +00001984 .. versionchanged:: 3.2
1985 Added the ``warnings`` argument.
1986
1987 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001988 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001989 than import time.
1990
Robert Collinsf0c819a2015-03-06 13:46:35 +13001991 .. versionchanged:: 3.5
1992 Added the tb_locals parameter.
1993
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001994 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001995
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001996 This method returns the instance of ``TestResult`` used by :meth:`run`.
1997 It is not intended to be called directly, but can be overridden in
1998 subclasses to provide a custom ``TestResult``.
1999
Michael Foord34c94622010-02-10 15:51:42 +00002000 ``_makeResult()`` instantiates the class or callable passed in the
2001 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00002002 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00002003 The result class is instantiated with the following arguments::
2004
2005 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002006
Michael Foord4d1639f2013-12-29 23:38:55 +00002007 .. method:: run(test)
2008
2009 This method is the main public interface to the `TextTestRunner`. This
2010 method takes a :class:`TestSuite` or :class:`TestCase` instance. A
2011 :class:`TestResult` is created by calling
2012 :func:`_makeResult` and the test(s) are run and the
2013 results printed to stdout.
2014
Ezio Melotti60901872010-12-01 00:56:10 +00002015
Georg Brandl419e3de2010-12-01 15:44:25 +00002016.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02002017 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00002018 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002019
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002020 A command-line program that loads a set of tests from *module* and runs them;
2021 this is primarily for making test modules conveniently executable.
2022 The simplest use for this function is to include the following line at the
2023 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00002024
2025 if __name__ == '__main__':
2026 unittest.main()
2027
Benjamin Petersond2397752009-06-27 23:45:02 +00002028 You can run tests with more detailed information by passing in the verbosity
2029 argument::
2030
2031 if __name__ == '__main__':
2032 unittest.main(verbosity=2)
2033
R David Murray6e731b02014-01-02 13:43:02 -05002034 The *defaultTest* argument is either the name of a single test or an
2035 iterable of test names to run if no test names are specified via *argv*. If
2036 not specified or ``None`` and no test names are provided via *argv*, all
2037 tests found in *module* are run.
R David Murray12e930f2014-01-02 13:37:26 -05002038
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002039 The *argv* argument can be a list of options passed to the program, with the
2040 first element being the program name. If not specified or ``None``,
2041 the values of :data:`sys.argv` are used.
2042
Georg Brandl116aa622007-08-15 14:28:22 +00002043 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002044 created instance of it. By default ``main`` calls :func:`sys.exit` with
2045 an exit code indicating success or failure of the tests run.
2046
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002047 The *testLoader* argument has to be a :class:`TestLoader` instance,
2048 and defaults to :data:`defaultTestLoader`.
2049
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002050 ``main`` supports being used from the interactive interpreter by passing in the
2051 argument ``exit=False``. This displays the result on standard output without
2052 calling :func:`sys.exit`::
2053
2054 >>> from unittest import main
2055 >>> main(module='test_module', exit=False)
2056
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002057 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00002058 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002059
Zachary Waref0a71cf2016-08-30 00:16:13 -05002060 The *warnings* argument specifies the :ref:`warning filter <warning-filter>`
Ezio Melotti60901872010-12-01 00:56:10 +00002061 that should be used while running the tests. If it's not specified, it will
Martin Panterb8c5f542016-10-30 04:20:23 +00002062 remain ``None`` if a :option:`!-W` option is passed to :program:`python`
2063 (see :ref:`Warning control <using-on-warnings>`),
Ezio Melotti60901872010-12-01 00:56:10 +00002064 otherwise it will be set to ``'default'``.
2065
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002066 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
2067 This stores the result of the tests run as the ``result`` attribute.
2068
Éric Araujo971dc012010-12-16 03:13:05 +00002069 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002070 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00002071
Georg Brandl853947a2010-01-31 18:53:23 +00002072 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002073 The *verbosity*, *failfast*, *catchbreak*, *buffer*
2074 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00002075
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08002076 .. versionchanged:: 3.4
2077 The *defaultTest* parameter was changed to also accept an iterable of
2078 test names.
2079
Benjamin Petersond2397752009-06-27 23:45:02 +00002080
2081load_tests Protocol
2082###################
2083
Georg Brandl853947a2010-01-31 18:53:23 +00002084.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002085
Benjamin Petersond2397752009-06-27 23:45:02 +00002086Modules or packages can customize how tests are loaded from them during normal
2087test runs or test discovery by implementing a function called ``load_tests``.
2088
2089If a test module defines ``load_tests`` it will be called by
2090:meth:`TestLoader.loadTestsFromModule` with the following arguments::
2091
Barry Warsawd78742a2014-09-08 14:21:37 -04002092 load_tests(loader, standard_tests, pattern)
2093
2094where *pattern* is passed straight through from ``loadTestsFromModule``. It
2095defaults to ``None``.
Benjamin Petersond2397752009-06-27 23:45:02 +00002096
2097It should return a :class:`TestSuite`.
2098
2099*loader* is the instance of :class:`TestLoader` doing the loading.
2100*standard_tests* are the tests that would be loaded by default from the
2101module. It is common for test modules to only want to add or remove tests
2102from the standard set of tests.
2103The third argument is used when loading packages as part of test discovery.
2104
2105A typical ``load_tests`` function that loads tests from a specific set of
2106:class:`TestCase` classes may look like::
2107
2108 test_cases = (TestCase1, TestCase2, TestCase3)
2109
2110 def load_tests(loader, tests, pattern):
2111 suite = TestSuite()
2112 for test_class in test_cases:
2113 tests = loader.loadTestsFromTestCase(test_class)
2114 suite.addTests(tests)
2115 return suite
2116
Barry Warsawd78742a2014-09-08 14:21:37 -04002117If discovery is started in a directory containing a package, either from the
2118command line or by calling :meth:`TestLoader.discover`, then the package
2119:file:`__init__.py` will be checked for ``load_tests``. If that function does
2120not exist, discovery will recurse into the package as though it were just
2121another directory. Otherwise, discovery of the package's tests will be left up
2122to ``load_tests`` which is called with the following arguments::
Benjamin Petersond2397752009-06-27 23:45:02 +00002123
2124 load_tests(loader, standard_tests, pattern)
2125
2126This should return a :class:`TestSuite` representing all the tests
2127from the package. (``standard_tests`` will only contain tests
2128collected from :file:`__init__.py`.)
2129
2130Because the pattern is passed into ``load_tests`` the package is free to
2131continue (and potentially modify) test discovery. A 'do nothing'
2132``load_tests`` function for a test package would look like::
2133
2134 def load_tests(loader, standard_tests, pattern):
2135 # top level directory cached on loader instance
2136 this_dir = os.path.dirname(__file__)
2137 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2138 standard_tests.addTests(package_tests)
2139 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002140
Barry Warsawd78742a2014-09-08 14:21:37 -04002141.. versionchanged:: 3.5
2142 Discovery no longer checks package names for matching *pattern* due to the
2143 impossibility of package names matching the default pattern.
2144
2145
Benjamin Petersonb48af542010-04-11 20:43:16 +00002146
2147Class and Module Fixtures
2148-------------------------
2149
2150Class and module level fixtures are implemented in :class:`TestSuite`. When
2151the test suite encounters a test from a new class then :meth:`tearDownClass`
2152from the previous class (if there is one) is called, followed by
2153:meth:`setUpClass` from the new class.
2154
2155Similarly if a test is from a different module from the previous test then
2156``tearDownModule`` from the previous module is run, followed by
2157``setUpModule`` from the new module.
2158
2159After all the tests have run the final ``tearDownClass`` and
2160``tearDownModule`` are run.
2161
2162Note that shared fixtures do not play well with [potential] features like test
2163parallelization and they break test isolation. They should be used with care.
2164
2165The default ordering of tests created by the unittest test loaders is to group
2166all tests from the same modules and classes together. This will lead to
2167``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2168module. If you randomize the order, so that tests from different modules and
2169classes are adjacent to each other, then these shared fixture functions may be
2170called multiple times in a single test run.
2171
2172Shared fixtures are not intended to work with suites with non-standard
2173ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2174support shared fixtures.
2175
2176If there are any exceptions raised during one of the shared fixture functions
2177the test is reported as an error. Because there is no corresponding test
2178instance an ``_ErrorHolder`` object (that has the same interface as a
2179:class:`TestCase`) is created to represent the error. If you are just using
2180the standard unittest test runner then this detail doesn't matter, but if you
2181are a framework author it may be relevant.
2182
2183
2184setUpClass and tearDownClass
2185~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2186
2187These must be implemented as class methods::
2188
2189 import unittest
2190
2191 class Test(unittest.TestCase):
2192 @classmethod
2193 def setUpClass(cls):
2194 cls._connection = createExpensiveConnectionObject()
2195
2196 @classmethod
2197 def tearDownClass(cls):
2198 cls._connection.destroy()
2199
2200If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2201then you must call up to them yourself. The implementations in
2202:class:`TestCase` are empty.
2203
2204If an exception is raised during a ``setUpClass`` then the tests in the class
2205are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002206have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002207:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002208instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002209
2210
2211setUpModule and tearDownModule
2212~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2213
2214These should be implemented as functions::
2215
2216 def setUpModule():
2217 createConnection()
2218
2219 def tearDownModule():
2220 closeConnection()
2221
2222If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002223module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002224:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002225instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002226
2227
2228Signal Handling
2229---------------
2230
Georg Brandl419e3de2010-12-01 15:44:25 +00002231.. versionadded:: 3.2
2232
Éric Araujo8acb67c2010-11-26 23:31:07 +00002233The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002234along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2235more friendly handling of control-C during a test run. With catch break
2236behavior enabled control-C will allow the currently running test to complete,
2237and the test run will then end and report all the results so far. A second
2238control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002239
Michael Foordde4ceab2010-04-25 19:53:49 +00002240The control-c handling signal handler attempts to remain compatible with code or
2241tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2242handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2243i.e. it has been replaced by the system under test and delegated to, then it
2244calls the default handler. This will normally be the expected behavior by code
2245that replaces an installed handler and delegates to it. For individual tests
2246that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2247decorator can be used.
2248
2249There are a few utility functions for framework authors to enable control-c
2250handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002251
2252.. function:: installHandler()
2253
2254 Install the control-c handler. When a :const:`signal.SIGINT` is received
2255 (usually in response to the user pressing control-c) all registered results
2256 have :meth:`~TestResult.stop` called.
2257
Michael Foord469b1f02010-04-26 23:41:26 +00002258
Benjamin Petersonb48af542010-04-11 20:43:16 +00002259.. function:: registerResult(result)
2260
2261 Register a :class:`TestResult` object for control-c handling. Registering a
2262 result stores a weak reference to it, so it doesn't prevent the result from
2263 being garbage collected.
2264
Michael Foordde4ceab2010-04-25 19:53:49 +00002265 Registering a :class:`TestResult` object has no side-effects if control-c
2266 handling is not enabled, so test frameworks can unconditionally register
2267 all results they create independently of whether or not handling is enabled.
2268
Michael Foord469b1f02010-04-26 23:41:26 +00002269
Benjamin Petersonb48af542010-04-11 20:43:16 +00002270.. function:: removeResult(result)
2271
2272 Remove a registered result. Once a result has been removed then
2273 :meth:`~TestResult.stop` will no longer be called on that result object in
2274 response to a control-c.
2275
Michael Foord469b1f02010-04-26 23:41:26 +00002276
Michael Foordde4ceab2010-04-25 19:53:49 +00002277.. function:: removeHandler(function=None)
2278
2279 When called without arguments this function removes the control-c handler
2280 if it has been installed. This function can also be used as a test decorator
2281 to temporarily remove the handler whilst the test is being executed::
2282
2283 @unittest.removeHandler
2284 def test_signal_handling(self):
2285 ...