blob: e5646aef6ac65c62d0574959add15987e98a5ce5 [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
Ezio Melotti9794a262010-11-04 14:52:13 +0000871 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`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001173
1174
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001175 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001176
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001177 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001178 regardless of their order. When they don't, an error message listing the
1179 differences between the sequences will be generated.
1180
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001181 Duplicate elements are *not* ignored when comparing *first* and
1182 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001183 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001184 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001185 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001186
Ezio Melotti4370b302010-11-03 20:39:14 +00001187 .. versionadded:: 3.2
1188
Ezio Melotti4370b302010-11-03 20:39:14 +00001189
Ezio Melotti22170ed2010-11-20 09:57:27 +00001190 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001191
Ezio Melotti22170ed2010-11-20 09:57:27 +00001192 The :meth:`assertEqual` method dispatches the equality check for objects of
1193 the same type to different type-specific methods. These methods are already
1194 implemented for most of the built-in types, but it's also possible to
1195 register new methods using :meth:`addTypeEqualityFunc`:
1196
1197 .. method:: addTypeEqualityFunc(typeobj, function)
1198
1199 Registers a type-specific method called by :meth:`assertEqual` to check
1200 if two objects of exactly the same *typeobj* (not subclasses) compare
1201 equal. *function* must take two positional arguments and a third msg=None
1202 keyword argument just as :meth:`assertEqual` does. It must raise
1203 :data:`self.failureException(msg) <failureException>` when inequality
1204 between the first two parameters is detected -- possibly providing useful
1205 information and explaining the inequalities in details in the error
1206 message.
1207
1208 .. versionadded:: 3.1
1209
1210 The list of type-specific methods automatically used by
1211 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1212 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001213
1214 +-----------------------------------------+-----------------------------+--------------+
1215 | Method | Used to compare | New in |
1216 +=========================================+=============================+==============+
1217 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1218 | <TestCase.assertMultiLineEqual>` | | |
1219 +-----------------------------------------+-----------------------------+--------------+
1220 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1221 | <TestCase.assertSequenceEqual>` | | |
1222 +-----------------------------------------+-----------------------------+--------------+
1223 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1224 | <TestCase.assertListEqual>` | | |
1225 +-----------------------------------------+-----------------------------+--------------+
1226 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1227 | <TestCase.assertTupleEqual>` | | |
1228 +-----------------------------------------+-----------------------------+--------------+
1229 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1230 | <TestCase.assertSetEqual>` | | |
1231 +-----------------------------------------+-----------------------------+--------------+
1232 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1233 | <TestCase.assertDictEqual>` | | |
1234 +-----------------------------------------+-----------------------------+--------------+
1235
1236
1237
Michael Foorde180d392011-01-28 19:51:48 +00001238 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001239
Michael Foorde180d392011-01-28 19:51:48 +00001240 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001241 When not equal a diff of the two strings highlighting the differences
1242 will be included in the error message. This method is used by default
1243 when comparing strings with :meth:`assertEqual`.
1244
Ezio Melotti4370b302010-11-03 20:39:14 +00001245 .. versionadded:: 3.1
1246
1247
Michael Foorde180d392011-01-28 19:51:48 +00001248 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001249
1250 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001251 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001252 be raised. If the sequences are different an error message is
1253 constructed that shows the difference between the two.
1254
Ezio Melotti22170ed2010-11-20 09:57:27 +00001255 This method is not called directly by :meth:`assertEqual`, but
1256 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001257 :meth:`assertTupleEqual`.
1258
1259 .. versionadded:: 3.1
1260
1261
Michael Foorde180d392011-01-28 19:51:48 +00001262 .. method:: assertListEqual(first, second, msg=None)
1263 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001264
Ezio Melotti49ccd512012-08-29 17:50:42 +03001265 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001266 constructed that shows only the differences between the two. An error
1267 is also raised if either of the parameters are of the wrong type.
1268 These methods are used by default when comparing lists or tuples with
1269 :meth:`assertEqual`.
1270
Ezio Melotti4370b302010-11-03 20:39:14 +00001271 .. versionadded:: 3.1
1272
1273
Michael Foorde180d392011-01-28 19:51:48 +00001274 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001275
1276 Tests that two sets are equal. If not, an error message is constructed
1277 that lists the differences between the sets. This method is used by
1278 default when comparing sets or frozensets with :meth:`assertEqual`.
1279
Michael Foorde180d392011-01-28 19:51:48 +00001280 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001281 method.
1282
Ezio Melotti4370b302010-11-03 20:39:14 +00001283 .. versionadded:: 3.1
1284
1285
Michael Foorde180d392011-01-28 19:51:48 +00001286 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001287
1288 Test that two dictionaries are equal. If not, an error message is
1289 constructed that shows the differences in the dictionaries. This
1290 method will be used by default to compare dictionaries in
1291 calls to :meth:`assertEqual`.
1292
Ezio Melotti4370b302010-11-03 20:39:14 +00001293 .. versionadded:: 3.1
1294
1295
1296
Ezio Melotti22170ed2010-11-20 09:57:27 +00001297 .. _other-methods-and-attrs:
1298
Ezio Melotti4370b302010-11-03 20:39:14 +00001299 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001300
Benjamin Peterson52baa292009-03-24 00:56:30 +00001301
Georg Brandl7f01a132009-09-16 15:58:14 +00001302 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001303
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001304 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001305 the error message.
1306
1307
1308 .. attribute:: failureException
1309
1310 This class attribute gives the exception raised by the test method. If a
1311 test framework needs to use a specialized exception, possibly to carry
1312 additional information, it must subclass this exception in order to "play
1313 fair" with the framework. The initial value of this attribute is
1314 :exc:`AssertionError`.
1315
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001316
1317 .. attribute:: longMessage
1318
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001319 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001320 :ref:`assert methods <assert-methods>` will be appended to the end of the
1321 normal failure message. The normal messages contain useful information
1322 about the objects involved, for example the message from assertEqual
1323 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001324 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001325 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001326
Michael Foord5074df62010-12-03 00:53:09 +00001327 This attribute defaults to ``True``. If set to False then a custom message
1328 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001329
1330 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001331 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001332
Raymond Hettinger35a88362009-04-09 00:08:24 +00001333 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001334
1335
Michael Foord98b3e762010-06-05 21:59:55 +00001336 .. attribute:: maxDiff
1337
1338 This attribute controls the maximum length of diffs output by assert
1339 methods that report diffs on failure. It defaults to 80*8 characters.
1340 Assert methods affected by this attribute are
1341 :meth:`assertSequenceEqual` (including all the sequence comparison
1342 methods that delegate to it), :meth:`assertDictEqual` and
1343 :meth:`assertMultiLineEqual`.
1344
1345 Setting ``maxDiff`` to None means that there is no maximum length of
1346 diffs.
1347
1348 .. versionadded:: 3.2
1349
1350
Benjamin Peterson52baa292009-03-24 00:56:30 +00001351 Testing frameworks can use the following methods to collect information on
1352 the test:
1353
1354
1355 .. method:: countTestCases()
1356
1357 Return the number of tests represented by this test object. For
1358 :class:`TestCase` instances, this will always be ``1``.
1359
1360
1361 .. method:: defaultTestResult()
1362
1363 Return an instance of the test result class that should be used for this
1364 test case class (if no other result instance is provided to the
1365 :meth:`run` method).
1366
1367 For :class:`TestCase` instances, this will always be an instance of
1368 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1369 as necessary.
1370
1371
1372 .. method:: id()
1373
1374 Return a string identifying the specific test case. This is usually the
1375 full name of the test method, including the module and class name.
1376
1377
1378 .. method:: shortDescription()
1379
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001380 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001381 has been provided. The default implementation of this method
1382 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001383 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001384
Georg Brandl419e3de2010-12-01 15:44:25 +00001385 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001386 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001387 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001388 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001389 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001390
Georg Brandl116aa622007-08-15 14:28:22 +00001391
Georg Brandl7f01a132009-09-16 15:58:14 +00001392 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001393
1394 Add a function to be called after :meth:`tearDown` to cleanup resources
1395 used during the test. Functions will be called in reverse order to the
1396 order they are added (LIFO). They are called with any arguments and
1397 keyword arguments passed into :meth:`addCleanup` when they are
1398 added.
1399
1400 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1401 then any cleanup functions added will still be called.
1402
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001403 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001404
1405
1406 .. method:: doCleanups()
1407
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001408 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001409 after :meth:`setUp` if :meth:`setUp` raises an exception.
1410
1411 It is responsible for calling all the cleanup functions added by
1412 :meth:`addCleanup`. If you need cleanup functions to be called
1413 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1414 yourself.
1415
1416 :meth:`doCleanups` pops methods off the stack of cleanup
1417 functions one at a time, so it can be called at any time.
1418
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001419 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001420
1421
Georg Brandl7f01a132009-09-16 15:58:14 +00001422.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001423
1424 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001425 allows the test runner to drive the test, but does not provide the methods
1426 which test code can use to check and report errors. This is used to create
1427 test cases using legacy test code, allowing it to be integrated into a
1428 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001429
1430
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001431.. _deprecated-aliases:
1432
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001433Deprecated aliases
1434##################
1435
1436For historical reasons, some of the :class:`TestCase` methods had one or more
1437aliases that are now deprecated. The following table lists the correct names
1438along with their deprecated aliases:
1439
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001440 ============================== ====================== ======================
1441 Method Name Deprecated alias Deprecated alias
1442 ============================== ====================== ======================
1443 :meth:`.assertEqual` failUnlessEqual assertEquals
1444 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1445 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001446 :meth:`.assertFalse` failIf
1447 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001448 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1449 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001450 :meth:`.assertRegex` assertRegexpMatches
1451 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001452 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001453
Ezio Melotti361467e2011-04-03 17:37:58 +03001454 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001455 the fail* aliases listed in the second column.
1456 .. deprecated:: 3.2
1457 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001458 .. deprecated:: 3.2
1459 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1460 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001461
1462
Benjamin Peterson52baa292009-03-24 00:56:30 +00001463.. _testsuite-objects:
1464
Benjamin Peterson52baa292009-03-24 00:56:30 +00001465Grouping tests
1466~~~~~~~~~~~~~~
1467
Georg Brandl7f01a132009-09-16 15:58:14 +00001468.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001469
1470 This class represents an aggregation of individual tests cases and test suites.
1471 The class presents the interface needed by the test runner to allow it to be run
1472 as any other test case. Running a :class:`TestSuite` instance is the same as
1473 iterating over the suite, running each test individually.
1474
1475 If *tests* is given, it must be an iterable of individual test cases or other
1476 test suites that will be used to build the suite initially. Additional methods
1477 are provided to add test cases and suites to the collection later on.
1478
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001479 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1480 they do not actually implement a test. Instead, they are used to aggregate
1481 tests into groups of tests that should be run together. Some additional
1482 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001483
1484
1485 .. method:: TestSuite.addTest(test)
1486
1487 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1488
1489
1490 .. method:: TestSuite.addTests(tests)
1491
1492 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1493 instances to this test suite.
1494
Benjamin Petersond2397752009-06-27 23:45:02 +00001495 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1496 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001497
1498 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1499
1500
1501 .. method:: run(result)
1502
1503 Run the tests associated with this suite, collecting the result into the
1504 test result object passed as *result*. Note that unlike
1505 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1506 be passed in.
1507
1508
1509 .. method:: debug()
1510
1511 Run the tests associated with this suite without collecting the
1512 result. This allows exceptions raised by the test to be propagated to the
1513 caller and can be used to support running tests under a debugger.
1514
1515
1516 .. method:: countTestCases()
1517
1518 Return the number of tests represented by this test object, including all
1519 individual tests and sub-suites.
1520
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001521
1522 .. method:: __iter__()
1523
1524 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1525 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
Andrew Svetloveb973682013-08-28 21:28:38 +03001526 that this method may be called several times on a single suite (for
1527 example when counting tests or comparing for equality) so the tests
1528 returned by repeated iterations before :meth:`TestSuite.run` must be the
1529 same for each call iteration. After :meth:`TestSuite.run`, callers should
1530 not rely on the tests returned by this method unless the caller uses a
1531 subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
1532 test references.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001533
Georg Brandl853947a2010-01-31 18:53:23 +00001534 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001535 In earlier versions the :class:`TestSuite` accessed tests directly rather
1536 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1537 for providing tests.
1538
Andrew Svetloveb973682013-08-28 21:28:38 +03001539 .. versionchanged:: 3.4
1540 In earlier versions the :class:`TestSuite` held references to each
1541 :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
1542 that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
1543
Benjamin Peterson52baa292009-03-24 00:56:30 +00001544 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1545 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1546
1547
Benjamin Peterson52baa292009-03-24 00:56:30 +00001548Loading and running tests
1549~~~~~~~~~~~~~~~~~~~~~~~~~
1550
Georg Brandl116aa622007-08-15 14:28:22 +00001551.. class:: TestLoader()
1552
Benjamin Peterson52baa292009-03-24 00:56:30 +00001553 The :class:`TestLoader` class is used to create test suites from classes and
1554 modules. Normally, there is no need to create an instance of this class; the
1555 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001556 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1557 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001558
Robert Collinsf920c212014-10-20 13:24:05 +13001559 :class:`TestLoader` objects have the following attributes:
1560
1561
1562 .. attribute:: errors
1563
1564 A list of the non-fatal errors encountered while loading tests. Not reset
1565 by the loader at any point. Fatal errors are signalled by the relevant
1566 a method raising an exception to the caller. Non-fatal errors are also
1567 indicated by a synthetic test that will raise the original error when
1568 run.
1569
1570 .. versionadded:: 3.5
1571
1572
Benjamin Peterson52baa292009-03-24 00:56:30 +00001573 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001574
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001575
Benjamin Peterson52baa292009-03-24 00:56:30 +00001576 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001577
Benjamin Peterson52baa292009-03-24 00:56:30 +00001578 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1579 :class:`testCaseClass`.
1580
Robert Collinse02f6c22015-07-23 06:37:26 +12001581 A test case instance is created for each method named by
1582 :meth:`getTestCaseNames`. By default these are the method names
1583 beginning with ``test``. If :meth:`getTestCaseNames` returns no
1584 methods, but the :meth:`runTest` method is implemented, a single test
1585 case is created for that method instead.
1586
Benjamin Peterson52baa292009-03-24 00:56:30 +00001587
Barry Warsawd78742a2014-09-08 14:21:37 -04001588 .. method:: loadTestsFromModule(module, pattern=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001589
1590 Return a suite of all tests cases contained in the given module. This
1591 method searches *module* for classes derived from :class:`TestCase` and
1592 creates an instance of the class for each test method defined for the
1593 class.
1594
Georg Brandle720c0a2009-04-27 16:20:50 +00001595 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001596
1597 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1598 convenient in sharing fixtures and helper functions, defining test
1599 methods on base classes that are not intended to be instantiated
1600 directly does not play well with this method. Doing so, however, can
1601 be useful when the fixtures are different and defined in subclasses.
1602
Benjamin Petersond2397752009-06-27 23:45:02 +00001603 If a module provides a ``load_tests`` function it will be called to
1604 load the tests. This allows modules to customize test loading.
Barry Warsawd78742a2014-09-08 14:21:37 -04001605 This is the `load_tests protocol`_. The *pattern* argument is passed as
1606 the third argument to ``load_tests``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001607
Georg Brandl853947a2010-01-31 18:53:23 +00001608 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001609 Support for ``load_tests`` added.
1610
Barry Warsawd78742a2014-09-08 14:21:37 -04001611 .. versionchanged:: 3.5
1612 The undocumented and unofficial *use_load_tests* default argument is
1613 deprecated and ignored, although it is still accepted for backward
1614 compatibility. The method also now accepts a keyword-only argument
1615 *pattern* which is passed to ``load_tests`` as the third argument.
1616
Benjamin Peterson52baa292009-03-24 00:56:30 +00001617
Georg Brandl7f01a132009-09-16 15:58:14 +00001618 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001619
1620 Return a suite of all tests cases given a string specifier.
1621
1622 The specifier *name* is a "dotted name" that may resolve either to a
1623 module, a test case class, a test method within a test case class, a
1624 :class:`TestSuite` instance, or a callable object which returns a
1625 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1626 applied in the order listed here; that is, a method on a possible test
1627 case class will be picked up as "a test method within a test case class",
1628 rather than "a callable object".
1629
1630 For example, if you have a module :mod:`SampleTests` containing a
1631 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1632 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001633 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1634 return a suite which will run all three test methods. Using the specifier
1635 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1636 suite which will run only the :meth:`test_two` test method. The specifier
1637 can refer to modules and packages which have not been imported; they will
1638 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001639
1640 The method optionally resolves *name* relative to the given *module*.
1641
Robert Collins659dd622014-10-30 08:27:27 +13001642 .. versionchanged:: 3.5
1643 If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing
1644 *name* then a synthetic test that raises that error when run will be
1645 returned. These errors are included in the errors accumulated by
1646 self.errors.
1647
Benjamin Peterson52baa292009-03-24 00:56:30 +00001648
Georg Brandl7f01a132009-09-16 15:58:14 +00001649 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001650
1651 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1652 than a single name. The return value is a test suite which supports all
1653 the tests defined for each name.
1654
1655
1656 .. method:: getTestCaseNames(testCaseClass)
1657
1658 Return a sorted sequence of method names found within *testCaseClass*;
1659 this should be a subclass of :class:`TestCase`.
1660
Benjamin Petersond2397752009-06-27 23:45:02 +00001661
1662 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1663
Larry Hastings3732ed22014-03-15 21:13:56 -07001664 Find all the test modules by recursing into subdirectories from the
1665 specified start directory, and return a TestSuite object containing them.
1666 Only test files that match *pattern* will be loaded. (Using shell style
1667 pattern matching.) Only module names that are importable (i.e. are valid
1668 Python identifiers) will be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001669
1670 All test modules must be importable from the top level of the project. If
1671 the start directory is not the top level directory then the top level
1672 directory must be specified separately.
1673
Barry Warsawd78742a2014-09-08 14:21:37 -04001674 If importing a module fails, for example due to a syntax error, then
1675 this will be recorded as a single error and discovery will continue. If
1676 the import failure is due to :exc:`SkipTest` being raised, it will be
1677 recorded as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001678
Barry Warsawd78742a2014-09-08 14:21:37 -04001679 If a package (a directory containing a file named :file:`__init__.py`) is
1680 found, the package will be checked for a ``load_tests`` function. If this
Robert Collinsbf2bda32014-11-05 03:09:01 +13001681 exists then it will be called
1682 ``package.load_tests(loader, tests, pattern)``. Test discovery takes care
1683 to ensure that a package is only checked for tests once during an
1684 invocation, even if the load_tests function itself calls
1685 ``loader.discover``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001686
Barry Warsawd78742a2014-09-08 14:21:37 -04001687 If ``load_tests`` exists then discovery does *not* recurse into the
1688 package, ``load_tests`` is responsible for loading all tests in the
1689 package.
Benjamin Petersond2397752009-06-27 23:45:02 +00001690
1691 The pattern is deliberately not stored as a loader attribute so that
1692 packages can continue discovery themselves. *top_level_dir* is stored so
1693 ``load_tests`` does not need to pass this argument in to
1694 ``loader.discover()``.
1695
Benjamin Petersonb48af542010-04-11 20:43:16 +00001696 *start_dir* can be a dotted module name as well as a directory.
1697
Georg Brandl853947a2010-01-31 18:53:23 +00001698 .. versionadded:: 3.2
1699
Ezio Melottieae2b382013-03-01 14:47:50 +02001700 .. versionchanged:: 3.4
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001701 Modules that raise :exc:`SkipTest` on import are recorded as skips,
Larry Hastings3732ed22014-03-15 21:13:56 -07001702 not errors.
1703 Discovery works for :term:`namespace packages <namespace package>`.
1704 Paths are sorted before being imported so that execution order is
1705 the same even if the underlying file system's ordering is not
1706 dependent on file name.
Michael Foord80cbc9e2013-03-18 17:50:12 -07001707
Barry Warsawd78742a2014-09-08 14:21:37 -04001708 .. versionchanged:: 3.5
1709 Found packages are now checked for ``load_tests`` regardless of
1710 whether their path matches *pattern*, because it is impossible for
1711 a package name to match the default pattern.
1712
Benjamin Petersond2397752009-06-27 23:45:02 +00001713
Benjamin Peterson52baa292009-03-24 00:56:30 +00001714 The following attributes of a :class:`TestLoader` can be configured either by
1715 subclassing or assignment on an instance:
1716
1717
1718 .. attribute:: testMethodPrefix
1719
1720 String giving the prefix of method names which will be interpreted as test
1721 methods. The default value is ``'test'``.
1722
1723 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1724 methods.
1725
1726
1727 .. attribute:: sortTestMethodsUsing
1728
1729 Function to be used to compare method names when sorting them in
1730 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1731
1732
1733 .. attribute:: suiteClass
1734
1735 Callable object that constructs a test suite from a list of tests. No
1736 methods on the resulting object are needed. The default value is the
1737 :class:`TestSuite` class.
1738
1739 This affects all the :meth:`loadTestsFrom\*` methods.
1740
1741
Benjamin Peterson52baa292009-03-24 00:56:30 +00001742.. class:: TestResult
1743
1744 This class is used to compile information about which tests have succeeded
1745 and which have failed.
1746
1747 A :class:`TestResult` object stores the results of a set of tests. The
1748 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1749 properly recorded; test authors do not need to worry about recording the
1750 outcome of tests.
1751
1752 Testing frameworks built on top of :mod:`unittest` may want access to the
1753 :class:`TestResult` object generated by running a set of tests for reporting
1754 purposes; a :class:`TestResult` instance is returned by the
1755 :meth:`TestRunner.run` method for this purpose.
1756
1757 :class:`TestResult` instances have the following attributes that will be of
1758 interest when inspecting the results of running a set of tests:
1759
1760
1761 .. attribute:: errors
1762
1763 A list containing 2-tuples of :class:`TestCase` instances and strings
1764 holding formatted tracebacks. Each tuple represents a test which raised an
1765 unexpected exception.
1766
Benjamin Peterson52baa292009-03-24 00:56:30 +00001767 .. attribute:: failures
1768
1769 A list containing 2-tuples of :class:`TestCase` instances and strings
1770 holding formatted tracebacks. Each tuple represents a test where a failure
Ezio Melottie2202362013-09-07 15:19:30 +03001771 was explicitly signalled using the :meth:`TestCase.assert\*` methods.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001772
Benjamin Peterson52baa292009-03-24 00:56:30 +00001773 .. attribute:: skipped
1774
1775 A list containing 2-tuples of :class:`TestCase` instances and strings
1776 holding the reason for skipping the test.
1777
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001778 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001779
1780 .. attribute:: expectedFailures
1781
Georg Brandl6faee4e2010-09-21 14:48:28 +00001782 A list containing 2-tuples of :class:`TestCase` instances and strings
1783 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001784 of the test case.
1785
1786 .. attribute:: unexpectedSuccesses
1787
1788 A list containing :class:`TestCase` instances that were marked as expected
1789 failures, but succeeded.
1790
1791 .. attribute:: shouldStop
1792
1793 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1794
Benjamin Peterson52baa292009-03-24 00:56:30 +00001795 .. attribute:: testsRun
1796
1797 The total number of tests run so far.
1798
Georg Brandl12037202010-12-02 22:35:25 +00001799 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001800
1801 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1802 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1803 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1804 fails or errors. Any output is also attached to the failure / error message.
1805
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001806 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001807
Benjamin Petersonb48af542010-04-11 20:43:16 +00001808 .. attribute:: failfast
1809
1810 If set to true :meth:`stop` will be called on the first failure or error,
1811 halting the test run.
1812
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001813 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001814
Robert Collinsf0c819a2015-03-06 13:46:35 +13001815 .. attribute:: tb_locals
1816
1817 If set to true then local variables will be shown in tracebacks.
1818
1819 .. versionadded:: 3.5
Benjamin Petersonb48af542010-04-11 20:43:16 +00001820
Benjamin Peterson52baa292009-03-24 00:56:30 +00001821 .. method:: wasSuccessful()
1822
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001823 Return ``True`` if all tests run so far have passed, otherwise returns
1824 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001825
Gregory P. Smith5a6d4bf2014-01-20 01:11:18 -08001826 .. versionchanged:: 3.4
1827 Returns ``False`` if there were any :attr:`unexpectedSuccesses`
1828 from tests marked with the :func:`expectedFailure` decorator.
1829
Benjamin Peterson52baa292009-03-24 00:56:30 +00001830 .. method:: stop()
1831
1832 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001833 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001834 :class:`TestRunner` objects should respect this flag and return without
1835 running any additional tests.
1836
1837 For example, this feature is used by the :class:`TextTestRunner` class to
1838 stop the test framework when the user signals an interrupt from the
1839 keyboard. Interactive tools which provide :class:`TestRunner`
1840 implementations can use this in a similar manner.
1841
1842 The following methods of the :class:`TestResult` class are used to maintain
1843 the internal data structures, and may be extended in subclasses to support
1844 additional reporting requirements. This is particularly useful in building
1845 tools which support interactive reporting while tests are being run.
1846
1847
1848 .. method:: startTest(test)
1849
1850 Called when the test case *test* is about to be run.
1851
Benjamin Peterson52baa292009-03-24 00:56:30 +00001852 .. method:: stopTest(test)
1853
1854 Called after the test case *test* has been executed, regardless of the
1855 outcome.
1856
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001857 .. method:: startTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001858
1859 Called once before any tests are executed.
1860
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001861 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001862
1863
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001864 .. method:: stopTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001865
Ezio Melotti176d6c42010-01-27 20:58:07 +00001866 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001867
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001868 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001869
1870
Benjamin Peterson52baa292009-03-24 00:56:30 +00001871 .. method:: addError(test, err)
1872
Ezio Melottie64a91a2013-09-07 15:23:36 +03001873 Called when the test case *test* raises an unexpected exception. *err* is a
Benjamin Peterson52baa292009-03-24 00:56:30 +00001874 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1875 traceback)``.
1876
1877 The default implementation appends a tuple ``(test, formatted_err)`` to
1878 the instance's :attr:`errors` attribute, where *formatted_err* is a
1879 formatted traceback derived from *err*.
1880
1881
1882 .. method:: addFailure(test, err)
1883
Benjamin Petersond2397752009-06-27 23:45:02 +00001884 Called when the test case *test* signals a failure. *err* is a tuple of
1885 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001886
1887 The default implementation appends a tuple ``(test, formatted_err)`` to
1888 the instance's :attr:`failures` attribute, where *formatted_err* is a
1889 formatted traceback derived from *err*.
1890
1891
1892 .. method:: addSuccess(test)
1893
1894 Called when the test case *test* succeeds.
1895
1896 The default implementation does nothing.
1897
1898
1899 .. method:: addSkip(test, reason)
1900
1901 Called when the test case *test* is skipped. *reason* is the reason the
1902 test gave for skipping.
1903
1904 The default implementation appends a tuple ``(test, reason)`` to the
1905 instance's :attr:`skipped` attribute.
1906
1907
1908 .. method:: addExpectedFailure(test, err)
1909
1910 Called when the test case *test* fails, but was marked with the
1911 :func:`expectedFailure` decorator.
1912
1913 The default implementation appends a tuple ``(test, formatted_err)`` to
1914 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1915 is a formatted traceback derived from *err*.
1916
1917
1918 .. method:: addUnexpectedSuccess(test)
1919
1920 Called when the test case *test* was marked with the
1921 :func:`expectedFailure` decorator, but succeeded.
1922
1923 The default implementation appends the test to the instance's
1924 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001925
Georg Brandl67b21b72010-08-17 15:07:14 +00001926
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001927 .. method:: addSubTest(test, subtest, outcome)
1928
1929 Called when a subtest finishes. *test* is the test case
1930 corresponding to the test method. *subtest* is a custom
1931 :class:`TestCase` instance describing the subtest.
1932
1933 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
1934 it failed with an exception where *outcome* is a tuple of the form
1935 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1936
1937 The default implementation does nothing when the outcome is a
1938 success, and records subtest failures as normal failures.
1939
1940 .. versionadded:: 3.4
1941
1942
Michael Foord34c94622010-02-10 15:51:42 +00001943.. class:: TextTestResult(stream, descriptions, verbosity)
1944
Georg Brandl67b21b72010-08-17 15:07:14 +00001945 A concrete implementation of :class:`TestResult` used by the
1946 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001947
Georg Brandl67b21b72010-08-17 15:07:14 +00001948 .. versionadded:: 3.2
1949 This class was previously named ``_TextTestResult``. The old name still
1950 exists as an alias but is deprecated.
1951
Georg Brandl116aa622007-08-15 14:28:22 +00001952
1953.. data:: defaultTestLoader
1954
1955 Instance of the :class:`TestLoader` class intended to be shared. If no
1956 customization of the :class:`TestLoader` is needed, this instance can be used
1957 instead of repeatedly creating new instances.
1958
1959
Ezio Melotti9c939bc2013-05-07 09:46:30 +03001960.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \
Robert Collinsf0c819a2015-03-06 13:46:35 +13001961 buffer=False, resultclass=None, warnings=None, *, tb_locals=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001962
Michael Foordd218e952011-01-03 12:55:11 +00001963 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001964 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001965 has a few configurable parameters, but is essentially very simple. Graphical
Robert Collinsf0c819a2015-03-06 13:46:35 +13001966 applications which run test suites should provide alternate implementations. Such
1967 implementations should accept ``**kwargs`` as the interface to construct runners
1968 changes when features are added to unittest.
Georg Brandl116aa622007-08-15 14:28:22 +00001969
Ezio Melotti60901872010-12-01 00:56:10 +00001970 By default this runner shows :exc:`DeprecationWarning`,
Senthil Kumaran409ea5d2014-02-08 14:28:03 -08001971 :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and
Larry Hastingsad88d7a2014-02-10 04:26:10 -08001972 :exc:`ImportWarning` even if they are :ref:`ignored by default
1973 <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest
1974 methods <deprecated-aliases>` are also special-cased and, when the warning
1975 filters are ``'default'`` or ``'always'``, they will appear only once
1976 per-module, in order to avoid too many warning messages. This behavior can
1977 be overridden using the :option:`-Wd` or :option:`-Wa` options and leaving
1978 *warnings* to ``None``.
Ezio Melotti60901872010-12-01 00:56:10 +00001979
Michael Foordd218e952011-01-03 12:55:11 +00001980 .. versionchanged:: 3.2
1981 Added the ``warnings`` argument.
1982
1983 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001984 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001985 than import time.
1986
Robert Collinsf0c819a2015-03-06 13:46:35 +13001987 .. versionchanged:: 3.5
1988 Added the tb_locals parameter.
1989
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001990 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001991
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001992 This method returns the instance of ``TestResult`` used by :meth:`run`.
1993 It is not intended to be called directly, but can be overridden in
1994 subclasses to provide a custom ``TestResult``.
1995
Michael Foord34c94622010-02-10 15:51:42 +00001996 ``_makeResult()`` instantiates the class or callable passed in the
1997 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001998 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001999 The result class is instantiated with the following arguments::
2000
2001 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002002
Michael Foord4d1639f2013-12-29 23:38:55 +00002003 .. method:: run(test)
2004
2005 This method is the main public interface to the `TextTestRunner`. This
2006 method takes a :class:`TestSuite` or :class:`TestCase` instance. A
2007 :class:`TestResult` is created by calling
2008 :func:`_makeResult` and the test(s) are run and the
2009 results printed to stdout.
2010
Ezio Melotti60901872010-12-01 00:56:10 +00002011
Georg Brandl419e3de2010-12-01 15:44:25 +00002012.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02002013 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00002014 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002015
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002016 A command-line program that loads a set of tests from *module* and runs them;
2017 this is primarily for making test modules conveniently executable.
2018 The simplest use for this function is to include the following line at the
2019 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00002020
2021 if __name__ == '__main__':
2022 unittest.main()
2023
Benjamin Petersond2397752009-06-27 23:45:02 +00002024 You can run tests with more detailed information by passing in the verbosity
2025 argument::
2026
2027 if __name__ == '__main__':
2028 unittest.main(verbosity=2)
2029
R David Murray6e731b02014-01-02 13:43:02 -05002030 The *defaultTest* argument is either the name of a single test or an
2031 iterable of test names to run if no test names are specified via *argv*. If
2032 not specified or ``None`` and no test names are provided via *argv*, all
2033 tests found in *module* are run.
R David Murray12e930f2014-01-02 13:37:26 -05002034
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002035 The *argv* argument can be a list of options passed to the program, with the
2036 first element being the program name. If not specified or ``None``,
2037 the values of :data:`sys.argv` are used.
2038
Georg Brandl116aa622007-08-15 14:28:22 +00002039 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002040 created instance of it. By default ``main`` calls :func:`sys.exit` with
2041 an exit code indicating success or failure of the tests run.
2042
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002043 The *testLoader* argument has to be a :class:`TestLoader` instance,
2044 and defaults to :data:`defaultTestLoader`.
2045
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002046 ``main`` supports being used from the interactive interpreter by passing in the
2047 argument ``exit=False``. This displays the result on standard output without
2048 calling :func:`sys.exit`::
2049
2050 >>> from unittest import main
2051 >>> main(module='test_module', exit=False)
2052
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002053 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00002054 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002055
Ezio Melotti60901872010-12-01 00:56:10 +00002056 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
2057 that should be used while running the tests. If it's not specified, it will
2058 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
2059 otherwise it will be set to ``'default'``.
2060
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002061 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
2062 This stores the result of the tests run as the ``result`` attribute.
2063
Éric Araujo971dc012010-12-16 03:13:05 +00002064 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002065 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00002066
Georg Brandl853947a2010-01-31 18:53:23 +00002067 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002068 The *verbosity*, *failfast*, *catchbreak*, *buffer*
2069 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00002070
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08002071 .. versionchanged:: 3.4
2072 The *defaultTest* parameter was changed to also accept an iterable of
2073 test names.
2074
Benjamin Petersond2397752009-06-27 23:45:02 +00002075
2076load_tests Protocol
2077###################
2078
Georg Brandl853947a2010-01-31 18:53:23 +00002079.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002080
Benjamin Petersond2397752009-06-27 23:45:02 +00002081Modules or packages can customize how tests are loaded from them during normal
2082test runs or test discovery by implementing a function called ``load_tests``.
2083
2084If a test module defines ``load_tests`` it will be called by
2085:meth:`TestLoader.loadTestsFromModule` with the following arguments::
2086
Barry Warsawd78742a2014-09-08 14:21:37 -04002087 load_tests(loader, standard_tests, pattern)
2088
2089where *pattern* is passed straight through from ``loadTestsFromModule``. It
2090defaults to ``None``.
Benjamin Petersond2397752009-06-27 23:45:02 +00002091
2092It should return a :class:`TestSuite`.
2093
2094*loader* is the instance of :class:`TestLoader` doing the loading.
2095*standard_tests* are the tests that would be loaded by default from the
2096module. It is common for test modules to only want to add or remove tests
2097from the standard set of tests.
2098The third argument is used when loading packages as part of test discovery.
2099
2100A typical ``load_tests`` function that loads tests from a specific set of
2101:class:`TestCase` classes may look like::
2102
2103 test_cases = (TestCase1, TestCase2, TestCase3)
2104
2105 def load_tests(loader, tests, pattern):
2106 suite = TestSuite()
2107 for test_class in test_cases:
2108 tests = loader.loadTestsFromTestCase(test_class)
2109 suite.addTests(tests)
2110 return suite
2111
Barry Warsawd78742a2014-09-08 14:21:37 -04002112If discovery is started in a directory containing a package, either from the
2113command line or by calling :meth:`TestLoader.discover`, then the package
2114:file:`__init__.py` will be checked for ``load_tests``. If that function does
2115not exist, discovery will recurse into the package as though it were just
2116another directory. Otherwise, discovery of the package's tests will be left up
2117to ``load_tests`` which is called with the following arguments::
Benjamin Petersond2397752009-06-27 23:45:02 +00002118
2119 load_tests(loader, standard_tests, pattern)
2120
2121This should return a :class:`TestSuite` representing all the tests
2122from the package. (``standard_tests`` will only contain tests
2123collected from :file:`__init__.py`.)
2124
2125Because the pattern is passed into ``load_tests`` the package is free to
2126continue (and potentially modify) test discovery. A 'do nothing'
2127``load_tests`` function for a test package would look like::
2128
2129 def load_tests(loader, standard_tests, pattern):
2130 # top level directory cached on loader instance
2131 this_dir = os.path.dirname(__file__)
2132 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2133 standard_tests.addTests(package_tests)
2134 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002135
Barry Warsawd78742a2014-09-08 14:21:37 -04002136.. versionchanged:: 3.5
2137 Discovery no longer checks package names for matching *pattern* due to the
2138 impossibility of package names matching the default pattern.
2139
2140
Benjamin Petersonb48af542010-04-11 20:43:16 +00002141
2142Class and Module Fixtures
2143-------------------------
2144
2145Class and module level fixtures are implemented in :class:`TestSuite`. When
2146the test suite encounters a test from a new class then :meth:`tearDownClass`
2147from the previous class (if there is one) is called, followed by
2148:meth:`setUpClass` from the new class.
2149
2150Similarly if a test is from a different module from the previous test then
2151``tearDownModule`` from the previous module is run, followed by
2152``setUpModule`` from the new module.
2153
2154After all the tests have run the final ``tearDownClass`` and
2155``tearDownModule`` are run.
2156
2157Note that shared fixtures do not play well with [potential] features like test
2158parallelization and they break test isolation. They should be used with care.
2159
2160The default ordering of tests created by the unittest test loaders is to group
2161all tests from the same modules and classes together. This will lead to
2162``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2163module. If you randomize the order, so that tests from different modules and
2164classes are adjacent to each other, then these shared fixture functions may be
2165called multiple times in a single test run.
2166
2167Shared fixtures are not intended to work with suites with non-standard
2168ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2169support shared fixtures.
2170
2171If there are any exceptions raised during one of the shared fixture functions
2172the test is reported as an error. Because there is no corresponding test
2173instance an ``_ErrorHolder`` object (that has the same interface as a
2174:class:`TestCase`) is created to represent the error. If you are just using
2175the standard unittest test runner then this detail doesn't matter, but if you
2176are a framework author it may be relevant.
2177
2178
2179setUpClass and tearDownClass
2180~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2181
2182These must be implemented as class methods::
2183
2184 import unittest
2185
2186 class Test(unittest.TestCase):
2187 @classmethod
2188 def setUpClass(cls):
2189 cls._connection = createExpensiveConnectionObject()
2190
2191 @classmethod
2192 def tearDownClass(cls):
2193 cls._connection.destroy()
2194
2195If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2196then you must call up to them yourself. The implementations in
2197:class:`TestCase` are empty.
2198
2199If an exception is raised during a ``setUpClass`` then the tests in the class
2200are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002201have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002202:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002203instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002204
2205
2206setUpModule and tearDownModule
2207~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2208
2209These should be implemented as functions::
2210
2211 def setUpModule():
2212 createConnection()
2213
2214 def tearDownModule():
2215 closeConnection()
2216
2217If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002218module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002219:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002220instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002221
2222
2223Signal Handling
2224---------------
2225
Georg Brandl419e3de2010-12-01 15:44:25 +00002226.. versionadded:: 3.2
2227
Éric Araujo8acb67c2010-11-26 23:31:07 +00002228The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002229along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2230more friendly handling of control-C during a test run. With catch break
2231behavior enabled control-C will allow the currently running test to complete,
2232and the test run will then end and report all the results so far. A second
2233control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002234
Michael Foordde4ceab2010-04-25 19:53:49 +00002235The control-c handling signal handler attempts to remain compatible with code or
2236tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2237handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2238i.e. it has been replaced by the system under test and delegated to, then it
2239calls the default handler. This will normally be the expected behavior by code
2240that replaces an installed handler and delegates to it. For individual tests
2241that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2242decorator can be used.
2243
2244There are a few utility functions for framework authors to enable control-c
2245handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002246
2247.. function:: installHandler()
2248
2249 Install the control-c handler. When a :const:`signal.SIGINT` is received
2250 (usually in response to the user pressing control-c) all registered results
2251 have :meth:`~TestResult.stop` called.
2252
Michael Foord469b1f02010-04-26 23:41:26 +00002253
Benjamin Petersonb48af542010-04-11 20:43:16 +00002254.. function:: registerResult(result)
2255
2256 Register a :class:`TestResult` object for control-c handling. Registering a
2257 result stores a weak reference to it, so it doesn't prevent the result from
2258 being garbage collected.
2259
Michael Foordde4ceab2010-04-25 19:53:49 +00002260 Registering a :class:`TestResult` object has no side-effects if control-c
2261 handling is not enabled, so test frameworks can unconditionally register
2262 all results they create independently of whether or not handling is enabled.
2263
Michael Foord469b1f02010-04-26 23:41:26 +00002264
Benjamin Petersonb48af542010-04-11 20:43:16 +00002265.. function:: removeResult(result)
2266
2267 Remove a registered result. Once a result has been removed then
2268 :meth:`~TestResult.stop` will no longer be called on that result object in
2269 response to a control-c.
2270
Michael Foord469b1f02010-04-26 23:41:26 +00002271
Michael Foordde4ceab2010-04-25 19:53:49 +00002272.. function:: removeHandler(function=None)
2273
2274 When called without arguments this function removes the control-c handler
2275 if it has been installed. This function can also be used as a test decorator
2276 to temporarily remove the handler whilst the test is being executed::
2277
2278 @unittest.removeHandler
2279 def test_signal_handling(self):
2280 ...