blob: bdb18bc41fa351f9fc6b2400716962fa7fcb207b [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.
6.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
7.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9.. sectionauthor:: Raymond Hettinger <python@rcn.com>
10
Ezio Melotti22170ed2010-11-20 09:57:27 +000011(If you are already familiar with the basic concepts of testing, you might want
12to skip to :ref:`the list of assert methods <assert-methods>`.)
Georg Brandl116aa622007-08-15 14:28:22 +000013
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010014The :mod:`unittest` unit testing framework was originally inspired by JUnit
15and has a similar flavor as major unit testing frameworks in other
16languages. It supports test automation, sharing of setup and shutdown code
17for tests, aggregation of tests into collections, and independence of the
18tests from the reporting framework.
Georg Brandl116aa622007-08-15 14:28:22 +000019
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010020To achieve this, :mod:`unittest` supports some important concepts in an
21object-oriented way:
Georg Brandl116aa622007-08-15 14:28:22 +000022
23test fixture
24 A :dfn:`test fixture` represents the preparation needed to perform one or more
25 tests, and any associate cleanup actions. This may involve, for example,
26 creating temporary or proxy databases, directories, or starting a server
27 process.
28
29test case
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010030 A :dfn:`test case` is the individual unit of testing. It checks for a specific
Georg Brandl116aa622007-08-15 14:28:22 +000031 response to a particular set of inputs. :mod:`unittest` provides a base class,
32 :class:`TestCase`, which may be used to create new test cases.
33
34test suite
35 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
36 used to aggregate tests that should be executed together.
37
38test runner
39 A :dfn:`test runner` is a component which orchestrates the execution of tests
40 and provides the outcome to the user. The runner may use a graphical interface,
41 a textual interface, or return a special value to indicate the results of
42 executing the tests.
43
Georg Brandl116aa622007-08-15 14:28:22 +000044
45.. seealso::
46
47 Module :mod:`doctest`
48 Another test-support module with a very different flavor.
49
50 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000051 Kent Beck's original paper on testing frameworks using the pattern shared
52 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000053
Berker Peksaga1a14092014-12-28 18:48:33 +020054 `Nose <https://nose.readthedocs.org/en/latest/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000055 Third-party unittest frameworks with a lighter-weight syntax for writing
56 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000057
Georg Brandle73778c2014-10-29 08:36:35 +010058 `The Python Testing Tools Taxonomy <https://wiki.python.org/moin/PythonTestingToolsTaxonomy>`_
Benjamin Petersonb48af542010-04-11 20:43:16 +000059 An extensive list of Python testing tools including functional testing
60 frameworks and mock object libraries.
Benjamin Petersond2397752009-06-27 23:45:02 +000061
Benjamin Petersonb48af542010-04-11 20:43:16 +000062 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
63 A special-interest-group for discussion of testing, and testing tools,
64 in Python.
Benjamin Petersond2397752009-06-27 23:45:02 +000065
Michael Foord90efac72011-01-03 15:39:49 +000066 The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is
67 a GUI tool for test discovery and execution. This is intended largely for ease of use
Senthil Kumaran847c33c2012-10-27 11:04:55 -070068 for those new to unit testing. For production environments it is
69 recommended that tests be driven by a continuous integration system such as
Georg Brandl525d3552014-10-29 10:26:56 +010070 `Buildbot <http://buildbot.net/>`_, `Jenkins <http://jenkins-ci.org/>`_
Senthil Kumaran847c33c2012-10-27 11:04:55 -070071 or `Hudson <http://hudson-ci.org/>`_.
Michael Foord90efac72011-01-03 15:39:49 +000072
73
Georg Brandl116aa622007-08-15 14:28:22 +000074.. _unittest-minimal-example:
75
76Basic example
77-------------
78
79The :mod:`unittest` module provides a rich set of tools for constructing and
80running tests. This section demonstrates that a small subset of the tools
81suffice to meet the needs of most users.
82
Ezio Melotti2e3998f2015-03-24 12:42:41 +020083Here is a short script to test three string methods::
Georg Brandl116aa622007-08-15 14:28:22 +000084
Ezio Melotti2e3998f2015-03-24 12:42:41 +020085 import unittest
Georg Brandl116aa622007-08-15 14:28:22 +000086
Ezio Melotti2e3998f2015-03-24 12:42:41 +020087 class TestStringMethods(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +000088
Ezio Melotti2e3998f2015-03-24 12:42:41 +020089 def test_upper(self):
90 self.assertEqual('foo'.upper(), 'FOO')
Georg Brandl116aa622007-08-15 14:28:22 +000091
Ezio Melotti2e3998f2015-03-24 12:42:41 +020092 def test_isupper(self):
93 self.assertTrue('FOO'.isupper())
94 self.assertFalse('Foo'.isupper())
Georg Brandl116aa622007-08-15 14:28:22 +000095
Ezio Melotti2e3998f2015-03-24 12:42:41 +020096 def test_split(self):
97 s = 'hello world'
98 self.assertEqual(s.split(), ['hello', 'world'])
99 # check that s.split fails when the separator is not a string
100 with self.assertRaises(TypeError):
101 s.split(2)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000102
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200103 if __name__ == '__main__':
104 unittest.main()
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Benjamin Peterson52baa292009-03-24 00:56:30 +0000107A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000108individual tests are defined with methods whose names start with the letters
109``test``. This naming convention informs the test runner about which methods
110represent tests.
111
Benjamin Peterson52baa292009-03-24 00:56:30 +0000112The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200113expected result; :meth:`~TestCase.assertTrue` or :meth:`~TestCase.assertFalse`
114to verify a condition; or :meth:`~TestCase.assertRaises` to verify that a
115specific exception gets raised. These methods are used instead of the
116:keyword:`assert` statement so the test runner can accumulate all test results
117and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200119The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you
120to define instructions that will be executed before and after each test method.
121They are covered in more details in the section :ref:`organizing-tests`.
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000124provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000125line, the above script produces an output that looks like this::
126
127 ...
128 ----------------------------------------------------------------------
129 Ran 3 tests in 0.000s
130
131 OK
132
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100133Passing the ``-v`` option to your test script will instruct :func:`unittest.main`
134to enable a higher level of verbosity, and produce the following output::
Georg Brandl116aa622007-08-15 14:28:22 +0000135
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200136 test_isupper (__main__.TestStringMethods) ... ok
137 test_split (__main__.TestStringMethods) ... ok
138 test_upper (__main__.TestStringMethods) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140 ----------------------------------------------------------------------
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200141 Ran 3 tests in 0.001s
Georg Brandl116aa622007-08-15 14:28:22 +0000142
143 OK
144
145The above examples show the most commonly used :mod:`unittest` features which
146are sufficient to meet many everyday testing needs. The remainder of the
147documentation explores the full feature set from first principles.
148
Benjamin Petersonb48af542010-04-11 20:43:16 +0000149
150.. _unittest-command-line-interface:
151
Éric Araujo76338ec2010-11-26 23:46:18 +0000152Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000153----------------------
154
155The unittest module can be used from the command line to run tests from
156modules, classes or even individual test methods::
157
158 python -m unittest test_module1 test_module2
159 python -m unittest test_module.TestClass
160 python -m unittest test_module.TestClass.test_method
161
162You can pass in a list with any combination of module names, and fully
163qualified class or method names.
164
Michael Foord37d120a2010-12-04 01:11:21 +0000165Test modules can be specified by file path as well::
166
167 python -m unittest tests/test_something.py
168
169This allows you to use the shell filename completion to specify the test module.
170The file specified must still be importable as a module. The path is converted
171to a module name by removing the '.py' and converting path separators into '.'.
172If you want to execute a test file that isn't importable as a module you should
173execute the file directly instead.
174
Benjamin Petersonb48af542010-04-11 20:43:16 +0000175You can run tests with more detail (higher verbosity) by passing in the -v flag::
176
177 python -m unittest -v test_module
178
Michael Foord086f3082010-11-21 21:28:01 +0000179When executed without arguments :ref:`unittest-test-discovery` is started::
180
181 python -m unittest
182
Éric Araujo713d3032010-11-18 16:38:46 +0000183For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000184
185 python -m unittest -h
186
Georg Brandl67b21b72010-08-17 15:07:14 +0000187.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000188 In earlier versions it was only possible to run individual test methods and
189 not modules or classes.
190
191
Éric Araujo76338ec2010-11-26 23:46:18 +0000192Command-line options
193~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000194
Éric Araujod3309df2010-11-21 03:09:17 +0000195:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000196
Éric Araujo713d3032010-11-18 16:38:46 +0000197.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000198
Éric Araujo713d3032010-11-18 16:38:46 +0000199.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000200
Éric Araujo713d3032010-11-18 16:38:46 +0000201 The standard output and standard error streams are buffered during the test
202 run. Output during a passing test is discarded. Output is echoed normally
203 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000204
Éric Araujo713d3032010-11-18 16:38:46 +0000205.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000206
Éric Araujo713d3032010-11-18 16:38:46 +0000207 Control-C during the test run waits for the current test to end and then
208 reports all the results so far. A second control-C raises the normal
209 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000210
Éric Araujo713d3032010-11-18 16:38:46 +0000211 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000212
Éric Araujo713d3032010-11-18 16:38:46 +0000213.. cmdoption:: -f, --failfast
214
215 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000216
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000217.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000218 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000219
220The command line can also be used for test discovery, for running all of the
221tests in a project or just a subset.
222
223
224.. _unittest-test-discovery:
225
226Test Discovery
227--------------
228
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000229.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000230
Ezio Melotti3d995842011-03-08 16:17:35 +0200231Unittest supports simple test discovery. In order to be compatible with test
232discovery, all of the test files must be :ref:`modules <tut-modules>` or
Larry Hastings3732ed22014-03-15 21:13:56 -0700233:ref:`packages <tut-packages>` (including :term:`namespace packages
234<namespace package>`) importable from the top-level directory of
235the project (this means that their filenames must be valid :ref:`identifiers
236<identifiers>`).
Benjamin Petersonb48af542010-04-11 20:43:16 +0000237
238Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000239used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000240
241 cd project_directory
242 python -m unittest discover
243
Michael Foord086f3082010-11-21 21:28:01 +0000244.. note::
245
246 As a shortcut, ``python -m unittest`` is the equivalent of
247 ``python -m unittest discover``. If you want to pass arguments to test
Éric Araujo941afed2011-09-01 02:47:34 +0200248 discovery the ``discover`` sub-command must be used explicitly.
Michael Foord086f3082010-11-21 21:28:01 +0000249
Benjamin Petersonb48af542010-04-11 20:43:16 +0000250The ``discover`` sub-command has the following options:
251
Éric Araujo713d3032010-11-18 16:38:46 +0000252.. program:: unittest discover
253
254.. cmdoption:: -v, --verbose
255
256 Verbose output
257
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800258.. cmdoption:: -s, --start-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000259
Éric Araujo941afed2011-09-01 02:47:34 +0200260 Directory to start discovery (``.`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000261
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800262.. cmdoption:: -p, --pattern pattern
Éric Araujo713d3032010-11-18 16:38:46 +0000263
Éric Araujo941afed2011-09-01 02:47:34 +0200264 Pattern to match test files (``test*.py`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000265
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800266.. cmdoption:: -t, --top-level-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000267
268 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000269
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000270The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
271as positional arguments in that order. The following two command lines
272are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000273
274 python -m unittest discover -s project_directory -p '*_test.py'
275 python -m unittest discover project_directory '*_test.py'
276
Michael Foord16f3e902010-05-08 15:13:42 +0000277As well as being a path it is possible to pass a package name, for example
278``myproject.subpackage.test``, as the start directory. The package name you
279supply will then be imported and its location on the filesystem will be used
280as the start directory.
281
282.. caution::
283
Senthil Kumaran916bd382010-10-15 12:55:19 +0000284 Test discovery loads tests by importing them. Once test discovery has found
285 all the test files from the start directory you specify it turns the paths
286 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000287 imported as ``foo.bar.baz``.
288
289 If you have a package installed globally and attempt test discovery on
290 a different copy of the package then the import *could* happen from the
291 wrong place. If this happens test discovery will warn you and exit.
292
293 If you supply the start directory as a package name rather than a
294 path to a directory then discover assumes that whichever location it
295 imports from is the location you intended, so you will not get the
296 warning.
297
Benjamin Petersonb48af542010-04-11 20:43:16 +0000298Test modules and packages can customize test loading and discovery by through
299the `load_tests protocol`_.
300
Larry Hastings3732ed22014-03-15 21:13:56 -0700301.. versionchanged:: 3.4
302 Test discovery supports :term:`namespace packages <namespace package>`.
303
Benjamin Petersonb48af542010-04-11 20:43:16 +0000304
Georg Brandl116aa622007-08-15 14:28:22 +0000305.. _organizing-tests:
306
307Organizing test code
308--------------------
309
310The basic building blocks of unit testing are :dfn:`test cases` --- single
311scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000312test cases are represented by :class:`unittest.TestCase` instances.
313To make your own test cases you must write subclasses of
314:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000315
Georg Brandl116aa622007-08-15 14:28:22 +0000316The testing code of a :class:`TestCase` instance should be entirely self
317contained, such that it can be run either in isolation or in arbitrary
318combination with any number of other test cases.
319
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100320The simplest :class:`TestCase` subclass will simply implement a test method
321(i.e. a method whose name starts with ``test``) in order to perform specific
322testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000323
324 import unittest
325
326 class DefaultWidgetSizeTestCase(unittest.TestCase):
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100327 def test_default_widget_size(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000328 widget = Widget('The widget')
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100329 self.assertEqual(widget.size(), (50, 50))
Georg Brandl116aa622007-08-15 14:28:22 +0000330
Sandro Tosi41b24042012-01-21 10:59:37 +0100331Note that in order to test something, we use one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000332methods provided by the :class:`TestCase` base class. If the test fails, an
333exception will be raised, and :mod:`unittest` will identify the test case as a
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100334:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100336Tests can be numerous, and their set-up can be repetitive. Luckily, we
337can factor out set-up code by implementing a method called
338:meth:`~TestCase.setUp`, which the testing framework will automatically
339call for every single test we run::
Georg Brandl116aa622007-08-15 14:28:22 +0000340
341 import unittest
342
343 class SimpleWidgetTestCase(unittest.TestCase):
344 def setUp(self):
345 self.widget = Widget('The widget')
346
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100347 def test_default_widget_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000348 self.assertEqual(self.widget.size(), (50,50),
349 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000350
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100351 def test_widget_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000352 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000353 self.assertEqual(self.widget.size(), (100,150),
354 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100356.. note::
357 The order in which the various tests will be run is determined
358 by sorting the test method names with respect to the built-in
359 ordering for strings.
360
Benjamin Peterson52baa292009-03-24 00:56:30 +0000361If the :meth:`~TestCase.setUp` method raises an exception while the test is
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100362running, the framework will consider the test to have suffered an error, and
363the test method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000364
Benjamin Peterson52baa292009-03-24 00:56:30 +0000365Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100366after the test method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368 import unittest
369
370 class SimpleWidgetTestCase(unittest.TestCase):
371 def setUp(self):
372 self.widget = Widget('The widget')
373
374 def tearDown(self):
375 self.widget.dispose()
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100377If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be
378run whether the test method succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380Such a working environment for the testing code is called a :dfn:`fixture`.
381
Georg Brandl116aa622007-08-15 14:28:22 +0000382Test case instances are grouped together according to the features they test.
383:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100384represented by :mod:`unittest`'s :class:`TestSuite` class. In most cases,
385calling :func:`unittest.main` will do the right thing and collect all the
386module's test cases for you, and then execute them.
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100388However, should you want to customize the building of your test suite,
389you can do it yourself::
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391 def suite():
392 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000393 suite.addTest(WidgetTestCase('test_default_size'))
394 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000395 return suite
396
Georg Brandl116aa622007-08-15 14:28:22 +0000397You can place the definitions of test cases and test suites in the same modules
398as the code they are to test (such as :file:`widget.py`), but there are several
399advantages to placing the test code in a separate module, such as
400:file:`test_widget.py`:
401
402* The test module can be run standalone from the command line.
403
404* The test code can more easily be separated from shipped code.
405
406* There is less temptation to change test code to fit the code it tests without
407 a good reason.
408
409* Test code should be modified much less frequently than the code it tests.
410
411* Tested code can be refactored more easily.
412
413* Tests for modules written in C must be in separate modules anyway, so why not
414 be consistent?
415
416* If the testing strategy changes, there is no need to change the source code.
417
418
419.. _legacy-unit-tests:
420
421Re-using old test code
422----------------------
423
424Some users will find that they have existing test code that they would like to
425run from :mod:`unittest`, without converting every old test function to a
426:class:`TestCase` subclass.
427
428For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
429This subclass of :class:`TestCase` can be used to wrap an existing test
430function. Set-up and tear-down functions can also be provided.
431
432Given the following test function::
433
434 def testSomething():
435 something = makeSomething()
436 assert something.name is not None
437 # ...
438
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100439one can create an equivalent test case instance as follows, with optional
440set-up and tear-down methods::
Georg Brandl116aa622007-08-15 14:28:22 +0000441
442 testcase = unittest.FunctionTestCase(testSomething,
443 setUp=makeSomethingDB,
444 tearDown=deleteSomethingDB)
445
Georg Brandl116aa622007-08-15 14:28:22 +0000446.. note::
447
Benjamin Petersond2397752009-06-27 23:45:02 +0000448 Even though :class:`FunctionTestCase` can be used to quickly convert an
449 existing test base over to a :mod:`unittest`\ -based system, this approach is
450 not recommended. Taking the time to set up proper :class:`TestCase`
451 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000452
Benjamin Peterson52baa292009-03-24 00:56:30 +0000453In some cases, the existing tests may have been written using the :mod:`doctest`
454module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
455automatically build :class:`unittest.TestSuite` instances from the existing
456:mod:`doctest`\ -based tests.
457
Georg Brandl116aa622007-08-15 14:28:22 +0000458
Benjamin Peterson5254c042009-03-23 22:25:03 +0000459.. _unittest-skipping:
460
461Skipping tests and expected failures
462------------------------------------
463
Michael Foordf5c851a2010-02-05 21:48:03 +0000464.. versionadded:: 3.1
465
Benjamin Peterson5254c042009-03-23 22:25:03 +0000466Unittest supports skipping individual test methods and even whole classes of
467tests. In addition, it supports marking a test as a "expected failure," a test
468that is broken and will fail, but shouldn't be counted as a failure on a
469:class:`TestResult`.
470
471Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
472or one of its conditional variants.
473
Ezio Melottifed69ba2013-03-01 21:26:04 +0200474Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000475
476 class MyTestCase(unittest.TestCase):
477
478 @unittest.skip("demonstrating skipping")
479 def test_nothing(self):
480 self.fail("shouldn't happen")
481
Benjamin Petersond2397752009-06-27 23:45:02 +0000482 @unittest.skipIf(mylib.__version__ < (1, 3),
483 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000484 def test_format(self):
485 # Tests that work for only a certain version of the library.
486 pass
487
488 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
489 def test_windows_support(self):
490 # windows specific testing code
491 pass
492
Ezio Melottifed69ba2013-03-01 21:26:04 +0200493This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000494
Benjamin Petersonded31c42009-03-30 15:04:16 +0000495 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000496 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000497 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000498
499 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000500 Ran 3 tests in 0.005s
501
502 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000503
Ezio Melottifed69ba2013-03-01 21:26:04 +0200504Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000505
Sandro Tosi317075d2012-03-31 18:34:59 +0200506 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000507 class MySkippedTestCase(unittest.TestCase):
508 def test_not_run(self):
509 pass
510
Benjamin Peterson52baa292009-03-24 00:56:30 +0000511:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
512that needs to be set up is not available.
513
Benjamin Peterson5254c042009-03-23 22:25:03 +0000514Expected failures use the :func:`expectedFailure` decorator. ::
515
516 class ExpectedFailureTestCase(unittest.TestCase):
517 @unittest.expectedFailure
518 def test_fail(self):
519 self.assertEqual(1, 0, "broken")
520
521It's easy to roll your own skipping decorators by making a decorator that calls
522:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottifed69ba2013-03-01 21:26:04 +0200523the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000524
525 def skipUnlessHasattr(obj, attr):
526 if hasattr(obj, attr):
527 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200528 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000529
530The following decorators implement test skipping and expected failures:
531
Georg Brandl8a1caa22010-07-29 16:01:11 +0000532.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000533
534 Unconditionally skip the decorated test. *reason* should describe why the
535 test is being skipped.
536
Georg Brandl8a1caa22010-07-29 16:01:11 +0000537.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000538
539 Skip the decorated test if *condition* is true.
540
Georg Brandl8a1caa22010-07-29 16:01:11 +0000541.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000542
Georg Brandl6faee4e2010-09-21 14:48:28 +0000543 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000544
Georg Brandl8a1caa22010-07-29 16:01:11 +0000545.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000546
547 Mark the test as an expected failure. If the test fails when run, the test
548 is not counted as a failure.
549
Ezio Melotti265281a2013-03-27 20:11:55 +0200550.. exception:: SkipTest(reason)
551
552 This exception is raised to skip a test.
553
554 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
555 decorators instead of raising this directly.
556
R David Murray42fa1102014-01-03 13:03:36 -0500557Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them.
558Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run.
559Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000560
Benjamin Peterson5254c042009-03-23 22:25:03 +0000561
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100562.. _subtests:
563
564Distinguishing test iterations using subtests
565---------------------------------------------
566
567.. versionadded:: 3.4
568
569When some of your tests differ only by a some very small differences, for
570instance some parameters, unittest allows you to distinguish them inside
571the body of a test method using the :meth:`~TestCase.subTest` context manager.
572
573For example, the following test::
574
575 class NumbersTest(unittest.TestCase):
576
577 def test_even(self):
578 """
579 Test that numbers between 0 and 5 are all even.
580 """
581 for i in range(0, 6):
582 with self.subTest(i=i):
583 self.assertEqual(i % 2, 0)
584
585will produce the following output::
586
587 ======================================================================
588 FAIL: test_even (__main__.NumbersTest) (i=1)
589 ----------------------------------------------------------------------
590 Traceback (most recent call last):
591 File "subtests.py", line 32, in test_even
592 self.assertEqual(i % 2, 0)
593 AssertionError: 1 != 0
594
595 ======================================================================
596 FAIL: test_even (__main__.NumbersTest) (i=3)
597 ----------------------------------------------------------------------
598 Traceback (most recent call last):
599 File "subtests.py", line 32, in test_even
600 self.assertEqual(i % 2, 0)
601 AssertionError: 1 != 0
602
603 ======================================================================
604 FAIL: test_even (__main__.NumbersTest) (i=5)
605 ----------------------------------------------------------------------
606 Traceback (most recent call last):
607 File "subtests.py", line 32, in test_even
608 self.assertEqual(i % 2, 0)
609 AssertionError: 1 != 0
610
611Without using a subtest, execution would stop after the first failure,
612and the error would be less easy to diagnose because the value of ``i``
613wouldn't be displayed::
614
615 ======================================================================
616 FAIL: test_even (__main__.NumbersTest)
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
623
Georg Brandl116aa622007-08-15 14:28:22 +0000624.. _unittest-contents:
625
626Classes and functions
627---------------------
628
Benjamin Peterson52baa292009-03-24 00:56:30 +0000629This section describes in depth the API of :mod:`unittest`.
630
631
632.. _testcase-objects:
633
634Test cases
635~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000636
Georg Brandl7f01a132009-09-16 15:58:14 +0000637.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000638
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100639 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000640 in the :mod:`unittest` universe. This class is intended to be used as a base
641 class, with specific tests being implemented by concrete subclasses. This class
642 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100643 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000644 kinds of failure.
645
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100646 Each instance of :class:`TestCase` will run a single base method: the method
647 named *methodName*. However, the standard implementation of the default
648 *methodName*, ``runTest()``, will run every method starting with ``test``
649 as an individual test, and count successes and failures accordingly.
650 Therefore, in most uses of :class:`TestCase`, you will neither change
651 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Michael Foord1341bb02011-03-14 19:01:46 -0400653 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100654 :class:`TestCase` can be instantiated successfully without providing a
655 *methodName*. This makes it easier to experiment with :class:`TestCase`
656 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000657
658 :class:`TestCase` instances provide three groups of methods: one group used
659 to run the test, another used by the test implementation to check conditions
660 and report failures, and some inquiry methods allowing information about the
661 test itself to be gathered.
662
663 Methods in the first group (running the test) are:
664
Benjamin Peterson52baa292009-03-24 00:56:30 +0000665 .. method:: setUp()
666
667 Method called to prepare the test fixture. This is called immediately
Terry Jan Reedy7f84d1e2014-04-15 23:44:14 -0400668 before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`,
669 any exception raised by this method will be considered an error rather than
Terry Jan Reedy6ac42402014-04-15 23:38:18 -0400670 a test failure. The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000671
672
673 .. method:: tearDown()
674
675 Method called immediately after the test method has been called and the
676 result recorded. This is called even if the test method raised an
677 exception, so the implementation in subclasses may need to be particularly
Terry Jan Reedy7f84d1e2014-04-15 23:44:14 -0400678 careful about checking internal state. Any exception, other than :exc:`AssertionError`
679 or :exc:`SkipTest`, raised by this method will be considered an error rather than a
680 test failure. This method will only be called if the :meth:`setUp` succeeds,
Terry Jan Reedy6ac42402014-04-15 23:38:18 -0400681 regardless of the outcome of the test method. The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000682
683
Benjamin Petersonb48af542010-04-11 20:43:16 +0000684 .. method:: setUpClass()
685
686 A class method called before tests in an individual class run.
687 ``setUpClass`` is called with the class as the only argument
688 and must be decorated as a :func:`classmethod`::
689
690 @classmethod
691 def setUpClass(cls):
692 ...
693
694 See `Class and Module Fixtures`_ for more details.
695
696 .. versionadded:: 3.2
697
698
699 .. method:: tearDownClass()
700
701 A class method called after tests in an individual class have run.
702 ``tearDownClass`` is called with the class as the only argument
703 and must be decorated as a :meth:`classmethod`::
704
705 @classmethod
706 def tearDownClass(cls):
707 ...
708
709 See `Class and Module Fixtures`_ for more details.
710
711 .. versionadded:: 3.2
712
713
Georg Brandl7f01a132009-09-16 15:58:14 +0000714 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000715
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100716 Run the test, collecting the result into the :class:`TestResult` object
717 passed as *result*. If *result* is omitted or ``None``, a temporary
718 result object is created (by calling the :meth:`defaultTestResult`
719 method) and used. The result object is returned to :meth:`run`'s
720 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000721
722 The same effect may be had by simply calling the :class:`TestCase`
723 instance.
724
Michael Foord1341bb02011-03-14 19:01:46 -0400725 .. versionchanged:: 3.3
726 Previous versions of ``run`` did not return the result. Neither did
727 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000728
Benjamin Petersone549ead2009-03-28 21:42:05 +0000729 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000730
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000731 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000732 test. See :ref:`unittest-skipping` for more information.
733
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000734 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000735
Benjamin Peterson52baa292009-03-24 00:56:30 +0000736
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100737 .. method:: subTest(msg=None, **params)
738
739 Return a context manager which executes the enclosed code block as a
740 subtest. *msg* and *params* are optional, arbitrary values which are
741 displayed whenever a subtest fails, allowing you to identify them
742 clearly.
743
744 A test case can contain any number of subtest declarations, and
745 they can be arbitrarily nested.
746
747 See :ref:`subtests` for more information.
748
749 .. versionadded:: 3.4
750
751
Benjamin Peterson52baa292009-03-24 00:56:30 +0000752 .. method:: debug()
753
754 Run the test without collecting the result. This allows exceptions raised
755 by the test to be propagated to the caller, and can be used to support
756 running tests under a debugger.
757
Ezio Melotti22170ed2010-11-20 09:57:27 +0000758 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000759
Ezio Melotti4370b302010-11-03 20:39:14 +0000760 The :class:`TestCase` class provides a number of methods to check for and
761 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000762
Ezio Melotti4370b302010-11-03 20:39:14 +0000763 +-----------------------------------------+-----------------------------+---------------+
764 | Method | Checks that | New in |
765 +=========================================+=============================+===============+
766 | :meth:`assertEqual(a, b) | ``a == b`` | |
767 | <TestCase.assertEqual>` | | |
768 +-----------------------------------------+-----------------------------+---------------+
769 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
770 | <TestCase.assertNotEqual>` | | |
771 +-----------------------------------------+-----------------------------+---------------+
772 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
773 | <TestCase.assertTrue>` | | |
774 +-----------------------------------------+-----------------------------+---------------+
775 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
776 | <TestCase.assertFalse>` | | |
777 +-----------------------------------------+-----------------------------+---------------+
778 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
779 | <TestCase.assertIs>` | | |
780 +-----------------------------------------+-----------------------------+---------------+
781 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
782 | <TestCase.assertIsNot>` | | |
783 +-----------------------------------------+-----------------------------+---------------+
784 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
785 | <TestCase.assertIsNone>` | | |
786 +-----------------------------------------+-----------------------------+---------------+
787 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
788 | <TestCase.assertIsNotNone>` | | |
789 +-----------------------------------------+-----------------------------+---------------+
790 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
791 | <TestCase.assertIn>` | | |
792 +-----------------------------------------+-----------------------------+---------------+
793 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
794 | <TestCase.assertNotIn>` | | |
795 +-----------------------------------------+-----------------------------+---------------+
796 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
797 | <TestCase.assertIsInstance>` | | |
798 +-----------------------------------------+-----------------------------+---------------+
799 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
800 | <TestCase.assertNotIsInstance>` | | |
801 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000802
Ezio Melottib4dc2502011-05-06 15:01:41 +0300803 All the assert methods accept a *msg* argument that, if specified, is used
804 as the error message on failure (see also :data:`longMessage`).
805 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
806 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
807 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000808
Michael Foorde180d392011-01-28 19:51:48 +0000809 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000810
Michael Foorde180d392011-01-28 19:51:48 +0000811 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000812 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000813
Michael Foorde180d392011-01-28 19:51:48 +0000814 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000815 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200816 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000817 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000818 error message (see also the :ref:`list of type-specific methods
819 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000820
Raymond Hettinger35a88362009-04-09 00:08:24 +0000821 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200822 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000823
Michael Foord28a817e2010-02-09 00:03:57 +0000824 .. versionchanged:: 3.2
825 :meth:`assertMultiLineEqual` added as the default type equality
826 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000827
Benjamin Peterson52baa292009-03-24 00:56:30 +0000828
Michael Foorde180d392011-01-28 19:51:48 +0000829 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000830
Michael Foorde180d392011-01-28 19:51:48 +0000831 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000832 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000833
Ezio Melotti4370b302010-11-03 20:39:14 +0000834 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000835 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000836
Ezio Melotti4841fd62010-11-05 15:43:40 +0000837 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000838
Ezio Melotti4841fd62010-11-05 15:43:40 +0000839 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
840 is True`` (use ``assertIs(expr, True)`` for the latter). This method
841 should also be avoided when more specific methods are available (e.g.
842 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
843 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000844
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000845
Michael Foorde180d392011-01-28 19:51:48 +0000846 .. method:: assertIs(first, second, msg=None)
847 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000848
Michael Foorde180d392011-01-28 19:51:48 +0000849 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000850 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000851
Raymond Hettinger35a88362009-04-09 00:08:24 +0000852 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000853
854
Ezio Melotti4370b302010-11-03 20:39:14 +0000855 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000856 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000857
Ezio Melotti9794a262010-11-04 14:52:13 +0000858 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000859
Ezio Melotti4370b302010-11-03 20:39:14 +0000860 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000861
862
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000863 .. method:: assertIn(first, second, msg=None)
864 assertNotIn(first, second, msg=None)
865
Ezio Melotti4841fd62010-11-05 15:43:40 +0000866 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000867
Raymond Hettinger35a88362009-04-09 00:08:24 +0000868 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000869
870
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000871 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000872 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000873
Ezio Melotti9794a262010-11-04 14:52:13 +0000874 Test that *obj* is (or is not) an instance of *cls* (which can be a
875 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200876 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000877
Ezio Melotti4370b302010-11-03 20:39:14 +0000878 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000879
880
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000881
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200882 It is also possible to check the production of exceptions, warnings and
883 log messages using the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000884
Ezio Melotti4370b302010-11-03 20:39:14 +0000885 +---------------------------------------------------------+--------------------------------------+------------+
886 | Method | Checks that | New in |
887 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200888 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000889 | <TestCase.assertRaises>` | | |
890 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300891 | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
892 | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000893 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200894 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000895 | <TestCase.assertWarns>` | | |
896 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300897 | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
898 | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000899 +---------------------------------------------------------+--------------------------------------+------------+
Georg Brandled007d52013-11-24 16:09:26 +0100900 | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 |
901 | <TestCase.assertLogs>` | with minimum *level* | |
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200902 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000903
Georg Brandl7f01a132009-09-16 15:58:14 +0000904 .. method:: assertRaises(exception, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300905 assertRaises(exception, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000906
907 Test that an exception is raised when *callable* is called with any
908 positional or keyword arguments that are also passed to
909 :meth:`assertRaises`. The test passes if *exception* is raised, is an
910 error if another exception is raised, or fails if no exception is raised.
911 To catch any of a group of exceptions, a tuple containing the exception
912 classes may be passed as *exception*.
913
Ezio Melottib4dc2502011-05-06 15:01:41 +0300914 If only the *exception* and possibly the *msg* arguments are given,
915 return a context manager so that the code under test can be written
916 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000917
Michael Foord41531f22010-02-05 21:13:40 +0000918 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000919 do_something()
920
Ezio Melottib4dc2502011-05-06 15:01:41 +0300921 When used as a context manager, :meth:`assertRaises` accepts the
922 additional keyword argument *msg*.
923
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000924 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000925 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000926 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000927
Georg Brandl8a1caa22010-07-29 16:01:11 +0000928 with self.assertRaises(SomeException) as cm:
929 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000930
Georg Brandl8a1caa22010-07-29 16:01:11 +0000931 the_exception = cm.exception
932 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000933
Ezio Melotti49008232010-02-08 21:57:48 +0000934 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000935 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000936
Ezio Melotti49008232010-02-08 21:57:48 +0000937 .. versionchanged:: 3.2
938 Added the :attr:`exception` attribute.
939
Ezio Melottib4dc2502011-05-06 15:01:41 +0300940 .. versionchanged:: 3.3
941 Added the *msg* keyword argument when used as a context manager.
942
Benjamin Peterson52baa292009-03-24 00:56:30 +0000943
Ezio Melottied3a7d22010-12-01 02:32:32 +0000944 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300945 assertRaisesRegex(exception, regex, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000946
Ezio Melottied3a7d22010-12-01 02:32:32 +0000947 Like :meth:`assertRaises` but also tests that *regex* matches
948 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000949 a regular expression object or a string containing a regular expression
950 suitable for use by :func:`re.search`. Examples::
951
Terry Jan Reedyc4565a92013-06-29 13:15:43 -0400952 self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
Ezio Melottied3a7d22010-12-01 02:32:32 +0000953 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000954
955 or::
956
Ezio Melottied3a7d22010-12-01 02:32:32 +0000957 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000958 int('XYZ')
959
Georg Brandl419e3de2010-12-01 15:44:25 +0000960 .. versionadded:: 3.1
961 under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +0300962
Ezio Melottied3a7d22010-12-01 02:32:32 +0000963 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +0000964 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000965
Ezio Melottib4dc2502011-05-06 15:01:41 +0300966 .. versionchanged:: 3.3
967 Added the *msg* keyword argument when used as a context manager.
968
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000969
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000970 .. method:: assertWarns(warning, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300971 assertWarns(warning, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000972
973 Test that a warning is triggered when *callable* is called with any
974 positional or keyword arguments that are also passed to
975 :meth:`assertWarns`. The test passes if *warning* is triggered and
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400976 fails if it isn't. Any exception is an error.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000977 To catch any of a group of warnings, a tuple containing the warning
978 classes may be passed as *warnings*.
979
Ezio Melottib4dc2502011-05-06 15:01:41 +0300980 If only the *warning* and possibly the *msg* arguments are given,
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400981 return a context manager so that the code under test can be written
Ezio Melottib4dc2502011-05-06 15:01:41 +0300982 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000983
984 with self.assertWarns(SomeWarning):
985 do_something()
986
Terry Jan Reedy9eda66d2013-07-27 16:15:29 -0400987 When used as a context manager, :meth:`assertWarns` accepts the
Ezio Melottib4dc2502011-05-06 15:01:41 +0300988 additional keyword argument *msg*.
989
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000990 The context manager will store the caught warning object in its
991 :attr:`warning` attribute, and the source line which triggered the
992 warnings in the :attr:`filename` and :attr:`lineno` attributes.
993 This can be useful if the intention is to perform additional checks
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400994 on the warning caught::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000995
996 with self.assertWarns(SomeWarning) as cm:
997 do_something()
998
999 self.assertIn('myfile.py', cm.filename)
1000 self.assertEqual(320, cm.lineno)
1001
1002 This method works regardless of the warning filters in place when it
1003 is called.
1004
1005 .. versionadded:: 3.2
1006
Ezio Melottib4dc2502011-05-06 15:01:41 +03001007 .. versionchanged:: 3.3
1008 Added the *msg* keyword argument when used as a context manager.
1009
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001010
Ezio Melottied3a7d22010-12-01 02:32:32 +00001011 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001012 assertWarnsRegex(warning, regex, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001013
Ezio Melottied3a7d22010-12-01 02:32:32 +00001014 Like :meth:`assertWarns` but also tests that *regex* matches on the
1015 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001016 object or a string containing a regular expression suitable for use
1017 by :func:`re.search`. Example::
1018
Ezio Melottied3a7d22010-12-01 02:32:32 +00001019 self.assertWarnsRegex(DeprecationWarning,
1020 r'legacy_function\(\) is deprecated',
1021 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001022
1023 or::
1024
Ezio Melottied3a7d22010-12-01 02:32:32 +00001025 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001026 frobnicate('/etc/passwd')
1027
1028 .. versionadded:: 3.2
1029
Ezio Melottib4dc2502011-05-06 15:01:41 +03001030 .. versionchanged:: 3.3
1031 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001032
Antoine Pitrou0715b9f2013-09-14 19:45:47 +02001033 .. method:: assertLogs(logger=None, level=None)
1034
1035 A context manager to test that at least one message is logged on
1036 the *logger* or one of its children, with at least the given
1037 *level*.
1038
1039 If given, *logger* should be a :class:`logging.Logger` object or a
1040 :class:`str` giving the name of a logger. The default is the root
1041 logger, which will catch all messages.
1042
1043 If given, *level* should be either a numeric logging level or
1044 its string equivalent (for example either ``"ERROR"`` or
1045 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`.
1046
1047 The test passes if at least one message emitted inside the ``with``
1048 block matches the *logger* and *level* conditions, otherwise it fails.
1049
1050 The object returned by the context manager is a recording helper
1051 which keeps tracks of the matching log messages. It has two
1052 attributes:
1053
1054 .. attribute:: records
1055
1056 A list of :class:`logging.LogRecord` objects of the matching
1057 log messages.
1058
1059 .. attribute:: output
1060
1061 A list of :class:`str` objects with the formatted output of
1062 matching messages.
1063
1064 Example::
1065
1066 with self.assertLogs('foo', level='INFO') as cm:
1067 logging.getLogger('foo').info('first message')
1068 logging.getLogger('foo.bar').error('second message')
1069 self.assertEqual(cm.output, ['INFO:foo:first message',
1070 'ERROR:foo.bar:second message'])
1071
1072 .. versionadded:: 3.4
1073
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001074
Ezio Melotti4370b302010-11-03 20:39:14 +00001075 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001076
Ezio Melotti4370b302010-11-03 20:39:14 +00001077 +---------------------------------------+--------------------------------+--------------+
1078 | Method | Checks that | New in |
1079 +=======================================+================================+==============+
1080 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1081 | <TestCase.assertAlmostEqual>` | | |
1082 +---------------------------------------+--------------------------------+--------------+
1083 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1084 | <TestCase.assertNotAlmostEqual>` | | |
1085 +---------------------------------------+--------------------------------+--------------+
1086 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1087 | <TestCase.assertGreater>` | | |
1088 +---------------------------------------+--------------------------------+--------------+
1089 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1090 | <TestCase.assertGreaterEqual>` | | |
1091 +---------------------------------------+--------------------------------+--------------+
1092 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1093 | <TestCase.assertLess>` | | |
1094 +---------------------------------------+--------------------------------+--------------+
1095 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1096 | <TestCase.assertLessEqual>` | | |
1097 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001098 | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001099 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001100 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001101 | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001102 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001103 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001104 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001105 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001106 | | regardless of their order | |
1107 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001108
1109
Michael Foorde180d392011-01-28 19:51:48 +00001110 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1111 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001112
Michael Foorde180d392011-01-28 19:51:48 +00001113 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001114 equal by computing the difference, rounding to the given number of
1115 decimal *places* (default 7), and comparing to zero. Note that these
1116 methods round the values to the given number of *decimal places* (i.e.
1117 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001118
Ezio Melotti4370b302010-11-03 20:39:14 +00001119 If *delta* is supplied instead of *places* then the difference
Ezio Melottid51914c2013-08-11 13:04:50 +03001120 between *first* and *second* must be less or equal to (or greater than) *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001121
Ezio Melotti4370b302010-11-03 20:39:14 +00001122 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001123
Ezio Melotti4370b302010-11-03 20:39:14 +00001124 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001125 :meth:`assertAlmostEqual` automatically considers almost equal objects
1126 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1127 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001128
Ezio Melotti4370b302010-11-03 20:39:14 +00001129
Michael Foorde180d392011-01-28 19:51:48 +00001130 .. method:: assertGreater(first, second, msg=None)
1131 assertGreaterEqual(first, second, msg=None)
1132 assertLess(first, second, msg=None)
1133 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001134
Michael Foorde180d392011-01-28 19:51:48 +00001135 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001136 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001137
1138 >>> self.assertGreaterEqual(3, 4)
1139 AssertionError: "3" unexpectedly not greater than or equal to "4"
1140
1141 .. versionadded:: 3.1
1142
1143
Ezio Melottied3a7d22010-12-01 02:32:32 +00001144 .. method:: assertRegex(text, regex, msg=None)
1145 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001146
Ezio Melottied3a7d22010-12-01 02:32:32 +00001147 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001148 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001149 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001150 may be a regular expression object or a string containing a regular
1151 expression suitable for use by :func:`re.search`.
1152
Georg Brandl419e3de2010-12-01 15:44:25 +00001153 .. versionadded:: 3.1
1154 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001155 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001156 The method ``assertRegexpMatches()`` has been renamed to
1157 :meth:`.assertRegex`.
1158 .. versionadded:: 3.2
1159 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001160
1161
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001162 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001163
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001164 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001165 regardless of their order. When they don't, an error message listing the
1166 differences between the sequences will be generated.
1167
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001168 Duplicate elements are *not* ignored when comparing *first* and
1169 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001170 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001171 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001172 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001173
Ezio Melotti4370b302010-11-03 20:39:14 +00001174 .. versionadded:: 3.2
1175
Ezio Melotti4370b302010-11-03 20:39:14 +00001176
Ezio Melotti22170ed2010-11-20 09:57:27 +00001177 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001178
Ezio Melotti22170ed2010-11-20 09:57:27 +00001179 The :meth:`assertEqual` method dispatches the equality check for objects of
1180 the same type to different type-specific methods. These methods are already
1181 implemented for most of the built-in types, but it's also possible to
1182 register new methods using :meth:`addTypeEqualityFunc`:
1183
1184 .. method:: addTypeEqualityFunc(typeobj, function)
1185
1186 Registers a type-specific method called by :meth:`assertEqual` to check
1187 if two objects of exactly the same *typeobj* (not subclasses) compare
1188 equal. *function* must take two positional arguments and a third msg=None
1189 keyword argument just as :meth:`assertEqual` does. It must raise
1190 :data:`self.failureException(msg) <failureException>` when inequality
1191 between the first two parameters is detected -- possibly providing useful
1192 information and explaining the inequalities in details in the error
1193 message.
1194
1195 .. versionadded:: 3.1
1196
1197 The list of type-specific methods automatically used by
1198 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1199 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001200
1201 +-----------------------------------------+-----------------------------+--------------+
1202 | Method | Used to compare | New in |
1203 +=========================================+=============================+==============+
1204 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1205 | <TestCase.assertMultiLineEqual>` | | |
1206 +-----------------------------------------+-----------------------------+--------------+
1207 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1208 | <TestCase.assertSequenceEqual>` | | |
1209 +-----------------------------------------+-----------------------------+--------------+
1210 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1211 | <TestCase.assertListEqual>` | | |
1212 +-----------------------------------------+-----------------------------+--------------+
1213 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1214 | <TestCase.assertTupleEqual>` | | |
1215 +-----------------------------------------+-----------------------------+--------------+
1216 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1217 | <TestCase.assertSetEqual>` | | |
1218 +-----------------------------------------+-----------------------------+--------------+
1219 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1220 | <TestCase.assertDictEqual>` | | |
1221 +-----------------------------------------+-----------------------------+--------------+
1222
1223
1224
Michael Foorde180d392011-01-28 19:51:48 +00001225 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001226
Michael Foorde180d392011-01-28 19:51:48 +00001227 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001228 When not equal a diff of the two strings highlighting the differences
1229 will be included in the error message. This method is used by default
1230 when comparing strings with :meth:`assertEqual`.
1231
Ezio Melotti4370b302010-11-03 20:39:14 +00001232 .. versionadded:: 3.1
1233
1234
Michael Foorde180d392011-01-28 19:51:48 +00001235 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001236
1237 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001238 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001239 be raised. If the sequences are different an error message is
1240 constructed that shows the difference between the two.
1241
Ezio Melotti22170ed2010-11-20 09:57:27 +00001242 This method is not called directly by :meth:`assertEqual`, but
1243 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001244 :meth:`assertTupleEqual`.
1245
1246 .. versionadded:: 3.1
1247
1248
Michael Foorde180d392011-01-28 19:51:48 +00001249 .. method:: assertListEqual(first, second, msg=None)
1250 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001251
Ezio Melotti49ccd512012-08-29 17:50:42 +03001252 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001253 constructed that shows only the differences between the two. An error
1254 is also raised if either of the parameters are of the wrong type.
1255 These methods are used by default when comparing lists or tuples with
1256 :meth:`assertEqual`.
1257
Ezio Melotti4370b302010-11-03 20:39:14 +00001258 .. versionadded:: 3.1
1259
1260
Michael Foorde180d392011-01-28 19:51:48 +00001261 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001262
1263 Tests that two sets are equal. If not, an error message is constructed
1264 that lists the differences between the sets. This method is used by
1265 default when comparing sets or frozensets with :meth:`assertEqual`.
1266
Michael Foorde180d392011-01-28 19:51:48 +00001267 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001268 method.
1269
Ezio Melotti4370b302010-11-03 20:39:14 +00001270 .. versionadded:: 3.1
1271
1272
Michael Foorde180d392011-01-28 19:51:48 +00001273 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001274
1275 Test that two dictionaries are equal. If not, an error message is
1276 constructed that shows the differences in the dictionaries. This
1277 method will be used by default to compare dictionaries in
1278 calls to :meth:`assertEqual`.
1279
Ezio Melotti4370b302010-11-03 20:39:14 +00001280 .. versionadded:: 3.1
1281
1282
1283
Ezio Melotti22170ed2010-11-20 09:57:27 +00001284 .. _other-methods-and-attrs:
1285
Ezio Melotti4370b302010-11-03 20:39:14 +00001286 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001287
Benjamin Peterson52baa292009-03-24 00:56:30 +00001288
Georg Brandl7f01a132009-09-16 15:58:14 +00001289 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001290
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001291 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001292 the error message.
1293
1294
1295 .. attribute:: failureException
1296
1297 This class attribute gives the exception raised by the test method. If a
1298 test framework needs to use a specialized exception, possibly to carry
1299 additional information, it must subclass this exception in order to "play
1300 fair" with the framework. The initial value of this attribute is
1301 :exc:`AssertionError`.
1302
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001303
1304 .. attribute:: longMessage
1305
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001306 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001307 :ref:`assert methods <assert-methods>` will be appended to the end of the
1308 normal failure message. The normal messages contain useful information
1309 about the objects involved, for example the message from assertEqual
1310 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001311 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001312 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001313
Michael Foord5074df62010-12-03 00:53:09 +00001314 This attribute defaults to ``True``. If set to False then a custom message
1315 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001316
1317 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001318 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001319
Raymond Hettinger35a88362009-04-09 00:08:24 +00001320 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001321
1322
Michael Foord98b3e762010-06-05 21:59:55 +00001323 .. attribute:: maxDiff
1324
1325 This attribute controls the maximum length of diffs output by assert
1326 methods that report diffs on failure. It defaults to 80*8 characters.
1327 Assert methods affected by this attribute are
1328 :meth:`assertSequenceEqual` (including all the sequence comparison
1329 methods that delegate to it), :meth:`assertDictEqual` and
1330 :meth:`assertMultiLineEqual`.
1331
1332 Setting ``maxDiff`` to None means that there is no maximum length of
1333 diffs.
1334
1335 .. versionadded:: 3.2
1336
1337
Benjamin Peterson52baa292009-03-24 00:56:30 +00001338 Testing frameworks can use the following methods to collect information on
1339 the test:
1340
1341
1342 .. method:: countTestCases()
1343
1344 Return the number of tests represented by this test object. For
1345 :class:`TestCase` instances, this will always be ``1``.
1346
1347
1348 .. method:: defaultTestResult()
1349
1350 Return an instance of the test result class that should be used for this
1351 test case class (if no other result instance is provided to the
1352 :meth:`run` method).
1353
1354 For :class:`TestCase` instances, this will always be an instance of
1355 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1356 as necessary.
1357
1358
1359 .. method:: id()
1360
1361 Return a string identifying the specific test case. This is usually the
1362 full name of the test method, including the module and class name.
1363
1364
1365 .. method:: shortDescription()
1366
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001367 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001368 has been provided. The default implementation of this method
1369 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001370 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001371
Georg Brandl419e3de2010-12-01 15:44:25 +00001372 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001373 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001374 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001375 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001376 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001377
Georg Brandl116aa622007-08-15 14:28:22 +00001378
Georg Brandl7f01a132009-09-16 15:58:14 +00001379 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001380
1381 Add a function to be called after :meth:`tearDown` to cleanup resources
1382 used during the test. Functions will be called in reverse order to the
1383 order they are added (LIFO). They are called with any arguments and
1384 keyword arguments passed into :meth:`addCleanup` when they are
1385 added.
1386
1387 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1388 then any cleanup functions added will still be called.
1389
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001390 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001391
1392
1393 .. method:: doCleanups()
1394
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001395 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001396 after :meth:`setUp` if :meth:`setUp` raises an exception.
1397
1398 It is responsible for calling all the cleanup functions added by
1399 :meth:`addCleanup`. If you need cleanup functions to be called
1400 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1401 yourself.
1402
1403 :meth:`doCleanups` pops methods off the stack of cleanup
1404 functions one at a time, so it can be called at any time.
1405
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001406 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001407
1408
Georg Brandl7f01a132009-09-16 15:58:14 +00001409.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001410
1411 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001412 allows the test runner to drive the test, but does not provide the methods
1413 which test code can use to check and report errors. This is used to create
1414 test cases using legacy test code, allowing it to be integrated into a
1415 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001416
1417
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001418.. _deprecated-aliases:
1419
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001420Deprecated aliases
1421##################
1422
1423For historical reasons, some of the :class:`TestCase` methods had one or more
1424aliases that are now deprecated. The following table lists the correct names
1425along with their deprecated aliases:
1426
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001427 ============================== ====================== ======================
1428 Method Name Deprecated alias Deprecated alias
1429 ============================== ====================== ======================
1430 :meth:`.assertEqual` failUnlessEqual assertEquals
1431 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1432 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001433 :meth:`.assertFalse` failIf
1434 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001435 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1436 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001437 :meth:`.assertRegex` assertRegexpMatches
1438 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001439 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001440
Ezio Melotti361467e2011-04-03 17:37:58 +03001441 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001442 the fail* aliases listed in the second column.
1443 .. deprecated:: 3.2
1444 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001445 .. deprecated:: 3.2
1446 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1447 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001448
1449
Benjamin Peterson52baa292009-03-24 00:56:30 +00001450.. _testsuite-objects:
1451
Benjamin Peterson52baa292009-03-24 00:56:30 +00001452Grouping tests
1453~~~~~~~~~~~~~~
1454
Georg Brandl7f01a132009-09-16 15:58:14 +00001455.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001456
1457 This class represents an aggregation of individual tests cases and test suites.
1458 The class presents the interface needed by the test runner to allow it to be run
1459 as any other test case. Running a :class:`TestSuite` instance is the same as
1460 iterating over the suite, running each test individually.
1461
1462 If *tests* is given, it must be an iterable of individual test cases or other
1463 test suites that will be used to build the suite initially. Additional methods
1464 are provided to add test cases and suites to the collection later on.
1465
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001466 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1467 they do not actually implement a test. Instead, they are used to aggregate
1468 tests into groups of tests that should be run together. Some additional
1469 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001470
1471
1472 .. method:: TestSuite.addTest(test)
1473
1474 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1475
1476
1477 .. method:: TestSuite.addTests(tests)
1478
1479 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1480 instances to this test suite.
1481
Benjamin Petersond2397752009-06-27 23:45:02 +00001482 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1483 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001484
1485 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1486
1487
1488 .. method:: run(result)
1489
1490 Run the tests associated with this suite, collecting the result into the
1491 test result object passed as *result*. Note that unlike
1492 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1493 be passed in.
1494
1495
1496 .. method:: debug()
1497
1498 Run the tests associated with this suite without collecting the
1499 result. This allows exceptions raised by the test to be propagated to the
1500 caller and can be used to support running tests under a debugger.
1501
1502
1503 .. method:: countTestCases()
1504
1505 Return the number of tests represented by this test object, including all
1506 individual tests and sub-suites.
1507
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001508
1509 .. method:: __iter__()
1510
1511 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1512 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
Andrew Svetloveb973682013-08-28 21:28:38 +03001513 that this method may be called several times on a single suite (for
1514 example when counting tests or comparing for equality) so the tests
1515 returned by repeated iterations before :meth:`TestSuite.run` must be the
1516 same for each call iteration. After :meth:`TestSuite.run`, callers should
1517 not rely on the tests returned by this method unless the caller uses a
1518 subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
1519 test references.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001520
Georg Brandl853947a2010-01-31 18:53:23 +00001521 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001522 In earlier versions the :class:`TestSuite` accessed tests directly rather
1523 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1524 for providing tests.
1525
Andrew Svetloveb973682013-08-28 21:28:38 +03001526 .. versionchanged:: 3.4
1527 In earlier versions the :class:`TestSuite` held references to each
1528 :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
1529 that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
1530
Benjamin Peterson52baa292009-03-24 00:56:30 +00001531 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1532 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1533
1534
Benjamin Peterson52baa292009-03-24 00:56:30 +00001535Loading and running tests
1536~~~~~~~~~~~~~~~~~~~~~~~~~
1537
Georg Brandl116aa622007-08-15 14:28:22 +00001538.. class:: TestLoader()
1539
Benjamin Peterson52baa292009-03-24 00:56:30 +00001540 The :class:`TestLoader` class is used to create test suites from classes and
1541 modules. Normally, there is no need to create an instance of this class; the
1542 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001543 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1544 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001545
1546 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001547
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001548
Benjamin Peterson52baa292009-03-24 00:56:30 +00001549 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001550
Benjamin Peterson52baa292009-03-24 00:56:30 +00001551 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1552 :class:`testCaseClass`.
1553
1554
1555 .. method:: loadTestsFromModule(module)
1556
1557 Return a suite of all tests cases contained in the given module. This
1558 method searches *module* for classes derived from :class:`TestCase` and
1559 creates an instance of the class for each test method defined for the
1560 class.
1561
Georg Brandle720c0a2009-04-27 16:20:50 +00001562 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001563
1564 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1565 convenient in sharing fixtures and helper functions, defining test
1566 methods on base classes that are not intended to be instantiated
1567 directly does not play well with this method. Doing so, however, can
1568 be useful when the fixtures are different and defined in subclasses.
1569
Benjamin Petersond2397752009-06-27 23:45:02 +00001570 If a module provides a ``load_tests`` function it will be called to
1571 load the tests. This allows modules to customize test loading.
1572 This is the `load_tests protocol`_.
1573
Georg Brandl853947a2010-01-31 18:53:23 +00001574 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001575 Support for ``load_tests`` added.
1576
Benjamin Peterson52baa292009-03-24 00:56:30 +00001577
Georg Brandl7f01a132009-09-16 15:58:14 +00001578 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001579
1580 Return a suite of all tests cases given a string specifier.
1581
1582 The specifier *name* is a "dotted name" that may resolve either to a
1583 module, a test case class, a test method within a test case class, a
1584 :class:`TestSuite` instance, or a callable object which returns a
1585 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1586 applied in the order listed here; that is, a method on a possible test
1587 case class will be picked up as "a test method within a test case class",
1588 rather than "a callable object".
1589
1590 For example, if you have a module :mod:`SampleTests` containing a
1591 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1592 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001593 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1594 return a suite which will run all three test methods. Using the specifier
1595 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1596 suite which will run only the :meth:`test_two` test method. The specifier
1597 can refer to modules and packages which have not been imported; they will
1598 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001599
1600 The method optionally resolves *name* relative to the given *module*.
1601
1602
Georg Brandl7f01a132009-09-16 15:58:14 +00001603 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001604
1605 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1606 than a single name. The return value is a test suite which supports all
1607 the tests defined for each name.
1608
1609
1610 .. method:: getTestCaseNames(testCaseClass)
1611
1612 Return a sorted sequence of method names found within *testCaseClass*;
1613 this should be a subclass of :class:`TestCase`.
1614
Benjamin Petersond2397752009-06-27 23:45:02 +00001615
1616 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1617
Larry Hastings3732ed22014-03-15 21:13:56 -07001618 Find all the test modules by recursing into subdirectories from the
1619 specified start directory, and return a TestSuite object containing them.
1620 Only test files that match *pattern* will be loaded. (Using shell style
1621 pattern matching.) Only module names that are importable (i.e. are valid
1622 Python identifiers) will be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001623
1624 All test modules must be importable from the top level of the project. If
1625 the start directory is not the top level directory then the top level
1626 directory must be specified separately.
1627
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001628 If importing a module fails, for example due to a syntax error, then this
Ezio Melottieae2b382013-03-01 14:47:50 +02001629 will be recorded as a single error and discovery will continue. If the
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001630 import failure is due to :exc:`SkipTest` being raised, it will be recorded
Ezio Melottieae2b382013-03-01 14:47:50 +02001631 as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001632
Benjamin Petersond2397752009-06-27 23:45:02 +00001633 If a test package name (directory with :file:`__init__.py`) matches the
1634 pattern then the package will be checked for a ``load_tests``
1635 function. If this exists then it will be called with *loader*, *tests*,
1636 *pattern*.
1637
Georg Brandl3f1ef9e2014-10-02 12:37:50 +02001638 If ``load_tests`` exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001639 ``load_tests`` is responsible for loading all tests in the package.
1640
1641 The pattern is deliberately not stored as a loader attribute so that
1642 packages can continue discovery themselves. *top_level_dir* is stored so
1643 ``load_tests`` does not need to pass this argument in to
1644 ``loader.discover()``.
1645
Benjamin Petersonb48af542010-04-11 20:43:16 +00001646 *start_dir* can be a dotted module name as well as a directory.
1647
Georg Brandl853947a2010-01-31 18:53:23 +00001648 .. versionadded:: 3.2
1649
Ezio Melottieae2b382013-03-01 14:47:50 +02001650 .. versionchanged:: 3.4
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001651 Modules that raise :exc:`SkipTest` on import are recorded as skips,
Larry Hastings3732ed22014-03-15 21:13:56 -07001652 not errors.
1653 Discovery works for :term:`namespace packages <namespace package>`.
1654 Paths are sorted before being imported so that execution order is
1655 the same even if the underlying file system's ordering is not
1656 dependent on file name.
Michael Foord80cbc9e2013-03-18 17:50:12 -07001657
Benjamin Petersond2397752009-06-27 23:45:02 +00001658
Benjamin Peterson52baa292009-03-24 00:56:30 +00001659 The following attributes of a :class:`TestLoader` can be configured either by
1660 subclassing or assignment on an instance:
1661
1662
1663 .. attribute:: testMethodPrefix
1664
1665 String giving the prefix of method names which will be interpreted as test
1666 methods. The default value is ``'test'``.
1667
1668 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1669 methods.
1670
1671
1672 .. attribute:: sortTestMethodsUsing
1673
1674 Function to be used to compare method names when sorting them in
1675 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1676
1677
1678 .. attribute:: suiteClass
1679
1680 Callable object that constructs a test suite from a list of tests. No
1681 methods on the resulting object are needed. The default value is the
1682 :class:`TestSuite` class.
1683
1684 This affects all the :meth:`loadTestsFrom\*` methods.
1685
1686
Benjamin Peterson52baa292009-03-24 00:56:30 +00001687.. class:: TestResult
1688
1689 This class is used to compile information about which tests have succeeded
1690 and which have failed.
1691
1692 A :class:`TestResult` object stores the results of a set of tests. The
1693 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1694 properly recorded; test authors do not need to worry about recording the
1695 outcome of tests.
1696
1697 Testing frameworks built on top of :mod:`unittest` may want access to the
1698 :class:`TestResult` object generated by running a set of tests for reporting
1699 purposes; a :class:`TestResult` instance is returned by the
1700 :meth:`TestRunner.run` method for this purpose.
1701
1702 :class:`TestResult` instances have the following attributes that will be of
1703 interest when inspecting the results of running a set of tests:
1704
1705
1706 .. attribute:: errors
1707
1708 A list containing 2-tuples of :class:`TestCase` instances and strings
1709 holding formatted tracebacks. Each tuple represents a test which raised an
1710 unexpected exception.
1711
Benjamin Peterson52baa292009-03-24 00:56:30 +00001712 .. attribute:: failures
1713
1714 A list containing 2-tuples of :class:`TestCase` instances and strings
1715 holding formatted tracebacks. Each tuple represents a test where a failure
Ezio Melottie2202362013-09-07 15:19:30 +03001716 was explicitly signalled using the :meth:`TestCase.assert\*` methods.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001717
Benjamin Peterson52baa292009-03-24 00:56:30 +00001718 .. attribute:: skipped
1719
1720 A list containing 2-tuples of :class:`TestCase` instances and strings
1721 holding the reason for skipping the test.
1722
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001723 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001724
1725 .. attribute:: expectedFailures
1726
Georg Brandl6faee4e2010-09-21 14:48:28 +00001727 A list containing 2-tuples of :class:`TestCase` instances and strings
1728 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001729 of the test case.
1730
1731 .. attribute:: unexpectedSuccesses
1732
1733 A list containing :class:`TestCase` instances that were marked as expected
1734 failures, but succeeded.
1735
1736 .. attribute:: shouldStop
1737
1738 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1739
1740
1741 .. attribute:: testsRun
1742
1743 The total number of tests run so far.
1744
1745
Georg Brandl12037202010-12-02 22:35:25 +00001746 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001747
1748 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1749 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1750 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1751 fails or errors. Any output is also attached to the failure / error message.
1752
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001753 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001754
1755
1756 .. attribute:: failfast
1757
1758 If set to true :meth:`stop` will be called on the first failure or error,
1759 halting the test run.
1760
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001761 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001762
1763
Benjamin Peterson52baa292009-03-24 00:56:30 +00001764 .. method:: wasSuccessful()
1765
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001766 Return ``True`` if all tests run so far have passed, otherwise returns
1767 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001768
Gregory P. Smith5a6d4bf2014-01-20 01:11:18 -08001769 .. versionchanged:: 3.4
1770 Returns ``False`` if there were any :attr:`unexpectedSuccesses`
1771 from tests marked with the :func:`expectedFailure` decorator.
1772
Benjamin Peterson52baa292009-03-24 00:56:30 +00001773
1774 .. method:: stop()
1775
1776 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001777 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001778 :class:`TestRunner` objects should respect this flag and return without
1779 running any additional tests.
1780
1781 For example, this feature is used by the :class:`TextTestRunner` class to
1782 stop the test framework when the user signals an interrupt from the
1783 keyboard. Interactive tools which provide :class:`TestRunner`
1784 implementations can use this in a similar manner.
1785
1786 The following methods of the :class:`TestResult` class are used to maintain
1787 the internal data structures, and may be extended in subclasses to support
1788 additional reporting requirements. This is particularly useful in building
1789 tools which support interactive reporting while tests are being run.
1790
1791
1792 .. method:: startTest(test)
1793
1794 Called when the test case *test* is about to be run.
1795
Benjamin Peterson52baa292009-03-24 00:56:30 +00001796 .. method:: stopTest(test)
1797
1798 Called after the test case *test* has been executed, regardless of the
1799 outcome.
1800
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001801 .. method:: startTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001802
1803 Called once before any tests are executed.
1804
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001805 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001806
1807
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001808 .. method:: stopTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001809
Ezio Melotti176d6c42010-01-27 20:58:07 +00001810 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001811
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001812 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001813
1814
Benjamin Peterson52baa292009-03-24 00:56:30 +00001815 .. method:: addError(test, err)
1816
Ezio Melottie64a91a2013-09-07 15:23:36 +03001817 Called when the test case *test* raises an unexpected exception. *err* is a
Benjamin Peterson52baa292009-03-24 00:56:30 +00001818 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1819 traceback)``.
1820
1821 The default implementation appends a tuple ``(test, formatted_err)`` to
1822 the instance's :attr:`errors` attribute, where *formatted_err* is a
1823 formatted traceback derived from *err*.
1824
1825
1826 .. method:: addFailure(test, err)
1827
Benjamin Petersond2397752009-06-27 23:45:02 +00001828 Called when the test case *test* signals a failure. *err* is a tuple of
1829 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001830
1831 The default implementation appends a tuple ``(test, formatted_err)`` to
1832 the instance's :attr:`failures` attribute, where *formatted_err* is a
1833 formatted traceback derived from *err*.
1834
1835
1836 .. method:: addSuccess(test)
1837
1838 Called when the test case *test* succeeds.
1839
1840 The default implementation does nothing.
1841
1842
1843 .. method:: addSkip(test, reason)
1844
1845 Called when the test case *test* is skipped. *reason* is the reason the
1846 test gave for skipping.
1847
1848 The default implementation appends a tuple ``(test, reason)`` to the
1849 instance's :attr:`skipped` attribute.
1850
1851
1852 .. method:: addExpectedFailure(test, err)
1853
1854 Called when the test case *test* fails, but was marked with the
1855 :func:`expectedFailure` decorator.
1856
1857 The default implementation appends a tuple ``(test, formatted_err)`` to
1858 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1859 is a formatted traceback derived from *err*.
1860
1861
1862 .. method:: addUnexpectedSuccess(test)
1863
1864 Called when the test case *test* was marked with the
1865 :func:`expectedFailure` decorator, but succeeded.
1866
1867 The default implementation appends the test to the instance's
1868 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001869
Georg Brandl67b21b72010-08-17 15:07:14 +00001870
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001871 .. method:: addSubTest(test, subtest, outcome)
1872
1873 Called when a subtest finishes. *test* is the test case
1874 corresponding to the test method. *subtest* is a custom
1875 :class:`TestCase` instance describing the subtest.
1876
1877 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
1878 it failed with an exception where *outcome* is a tuple of the form
1879 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1880
1881 The default implementation does nothing when the outcome is a
1882 success, and records subtest failures as normal failures.
1883
1884 .. versionadded:: 3.4
1885
1886
Michael Foord34c94622010-02-10 15:51:42 +00001887.. class:: TextTestResult(stream, descriptions, verbosity)
1888
Georg Brandl67b21b72010-08-17 15:07:14 +00001889 A concrete implementation of :class:`TestResult` used by the
1890 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001891
Georg Brandl67b21b72010-08-17 15:07:14 +00001892 .. versionadded:: 3.2
1893 This class was previously named ``_TextTestResult``. The old name still
1894 exists as an alias but is deprecated.
1895
Georg Brandl116aa622007-08-15 14:28:22 +00001896
1897.. data:: defaultTestLoader
1898
1899 Instance of the :class:`TestLoader` class intended to be shared. If no
1900 customization of the :class:`TestLoader` is needed, this instance can be used
1901 instead of repeatedly creating new instances.
1902
1903
Ezio Melotti9c939bc2013-05-07 09:46:30 +03001904.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \
1905 buffer=False, resultclass=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001906
Michael Foordd218e952011-01-03 12:55:11 +00001907 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001908 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001909 has a few configurable parameters, but is essentially very simple. Graphical
1910 applications which run test suites should provide alternate implementations.
1911
Ezio Melotti60901872010-12-01 00:56:10 +00001912 By default this runner shows :exc:`DeprecationWarning`,
Senthil Kumaran409ea5d2014-02-08 14:28:03 -08001913 :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and
Larry Hastingsad88d7a2014-02-10 04:26:10 -08001914 :exc:`ImportWarning` even if they are :ref:`ignored by default
1915 <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest
1916 methods <deprecated-aliases>` are also special-cased and, when the warning
1917 filters are ``'default'`` or ``'always'``, they will appear only once
1918 per-module, in order to avoid too many warning messages. This behavior can
1919 be overridden using the :option:`-Wd` or :option:`-Wa` options and leaving
1920 *warnings* to ``None``.
Ezio Melotti60901872010-12-01 00:56:10 +00001921
Michael Foordd218e952011-01-03 12:55:11 +00001922 .. versionchanged:: 3.2
1923 Added the ``warnings`` argument.
1924
1925 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001926 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001927 than import time.
1928
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001929 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001930
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001931 This method returns the instance of ``TestResult`` used by :meth:`run`.
1932 It is not intended to be called directly, but can be overridden in
1933 subclasses to provide a custom ``TestResult``.
1934
Michael Foord34c94622010-02-10 15:51:42 +00001935 ``_makeResult()`` instantiates the class or callable passed in the
1936 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001937 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001938 The result class is instantiated with the following arguments::
1939
1940 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001941
Michael Foord4d1639f2013-12-29 23:38:55 +00001942 .. method:: run(test)
1943
1944 This method is the main public interface to the `TextTestRunner`. This
1945 method takes a :class:`TestSuite` or :class:`TestCase` instance. A
1946 :class:`TestResult` is created by calling
1947 :func:`_makeResult` and the test(s) are run and the
1948 results printed to stdout.
1949
Ezio Melotti60901872010-12-01 00:56:10 +00001950
Georg Brandl419e3de2010-12-01 15:44:25 +00001951.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02001952 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00001953 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001954
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001955 A command-line program that loads a set of tests from *module* and runs them;
1956 this is primarily for making test modules conveniently executable.
1957 The simplest use for this function is to include the following line at the
1958 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00001959
1960 if __name__ == '__main__':
1961 unittest.main()
1962
Benjamin Petersond2397752009-06-27 23:45:02 +00001963 You can run tests with more detailed information by passing in the verbosity
1964 argument::
1965
1966 if __name__ == '__main__':
1967 unittest.main(verbosity=2)
1968
R David Murray6e731b02014-01-02 13:43:02 -05001969 The *defaultTest* argument is either the name of a single test or an
1970 iterable of test names to run if no test names are specified via *argv*. If
1971 not specified or ``None`` and no test names are provided via *argv*, all
1972 tests found in *module* are run.
R David Murray12e930f2014-01-02 13:37:26 -05001973
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001974 The *argv* argument can be a list of options passed to the program, with the
1975 first element being the program name. If not specified or ``None``,
1976 the values of :data:`sys.argv` are used.
1977
Georg Brandl116aa622007-08-15 14:28:22 +00001978 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001979 created instance of it. By default ``main`` calls :func:`sys.exit` with
1980 an exit code indicating success or failure of the tests run.
1981
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001982 The *testLoader* argument has to be a :class:`TestLoader` instance,
1983 and defaults to :data:`defaultTestLoader`.
1984
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001985 ``main`` supports being used from the interactive interpreter by passing in the
1986 argument ``exit=False``. This displays the result on standard output without
1987 calling :func:`sys.exit`::
1988
1989 >>> from unittest import main
1990 >>> main(module='test_module', exit=False)
1991
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001992 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00001993 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001994
Ezio Melotti60901872010-12-01 00:56:10 +00001995 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
1996 that should be used while running the tests. If it's not specified, it will
1997 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
1998 otherwise it will be set to ``'default'``.
1999
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002000 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
2001 This stores the result of the tests run as the ``result`` attribute.
2002
Éric Araujo971dc012010-12-16 03:13:05 +00002003 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002004 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00002005
Georg Brandl853947a2010-01-31 18:53:23 +00002006 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002007 The *verbosity*, *failfast*, *catchbreak*, *buffer*
2008 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00002009
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08002010 .. versionchanged:: 3.4
2011 The *defaultTest* parameter was changed to also accept an iterable of
2012 test names.
2013
Benjamin Petersond2397752009-06-27 23:45:02 +00002014
2015load_tests Protocol
2016###################
2017
Georg Brandl853947a2010-01-31 18:53:23 +00002018.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002019
Benjamin Petersond2397752009-06-27 23:45:02 +00002020Modules or packages can customize how tests are loaded from them during normal
2021test runs or test discovery by implementing a function called ``load_tests``.
2022
2023If a test module defines ``load_tests`` it will be called by
2024:meth:`TestLoader.loadTestsFromModule` with the following arguments::
2025
2026 load_tests(loader, standard_tests, None)
2027
2028It should return a :class:`TestSuite`.
2029
2030*loader* is the instance of :class:`TestLoader` doing the loading.
2031*standard_tests* are the tests that would be loaded by default from the
2032module. It is common for test modules to only want to add or remove tests
2033from the standard set of tests.
2034The third argument is used when loading packages as part of test discovery.
2035
2036A typical ``load_tests`` function that loads tests from a specific set of
2037:class:`TestCase` classes may look like::
2038
2039 test_cases = (TestCase1, TestCase2, TestCase3)
2040
2041 def load_tests(loader, tests, pattern):
2042 suite = TestSuite()
2043 for test_class in test_cases:
2044 tests = loader.loadTestsFromTestCase(test_class)
2045 suite.addTests(tests)
2046 return suite
2047
2048If discovery is started, either from the command line or by calling
2049:meth:`TestLoader.discover`, with a pattern that matches a package
2050name then the package :file:`__init__.py` will be checked for ``load_tests``.
2051
2052.. note::
2053
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02002054 The default pattern is ``'test*.py'``. This matches all Python files
2055 that start with ``'test'`` but *won't* match any test directories.
Benjamin Petersond2397752009-06-27 23:45:02 +00002056
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02002057 A pattern like ``'test*'`` will match test packages as well as
Benjamin Petersond2397752009-06-27 23:45:02 +00002058 modules.
2059
2060If the package :file:`__init__.py` defines ``load_tests`` then it will be
2061called and discovery not continued into the package. ``load_tests``
2062is called with the following arguments::
2063
2064 load_tests(loader, standard_tests, pattern)
2065
2066This should return a :class:`TestSuite` representing all the tests
2067from the package. (``standard_tests`` will only contain tests
2068collected from :file:`__init__.py`.)
2069
2070Because the pattern is passed into ``load_tests`` the package is free to
2071continue (and potentially modify) test discovery. A 'do nothing'
2072``load_tests`` function for a test package would look like::
2073
2074 def load_tests(loader, standard_tests, pattern):
2075 # top level directory cached on loader instance
2076 this_dir = os.path.dirname(__file__)
2077 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2078 standard_tests.addTests(package_tests)
2079 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002080
2081
2082Class and Module Fixtures
2083-------------------------
2084
2085Class and module level fixtures are implemented in :class:`TestSuite`. When
2086the test suite encounters a test from a new class then :meth:`tearDownClass`
2087from the previous class (if there is one) is called, followed by
2088:meth:`setUpClass` from the new class.
2089
2090Similarly if a test is from a different module from the previous test then
2091``tearDownModule`` from the previous module is run, followed by
2092``setUpModule`` from the new module.
2093
2094After all the tests have run the final ``tearDownClass`` and
2095``tearDownModule`` are run.
2096
2097Note that shared fixtures do not play well with [potential] features like test
2098parallelization and they break test isolation. They should be used with care.
2099
2100The default ordering of tests created by the unittest test loaders is to group
2101all tests from the same modules and classes together. This will lead to
2102``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2103module. If you randomize the order, so that tests from different modules and
2104classes are adjacent to each other, then these shared fixture functions may be
2105called multiple times in a single test run.
2106
2107Shared fixtures are not intended to work with suites with non-standard
2108ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2109support shared fixtures.
2110
2111If there are any exceptions raised during one of the shared fixture functions
2112the test is reported as an error. Because there is no corresponding test
2113instance an ``_ErrorHolder`` object (that has the same interface as a
2114:class:`TestCase`) is created to represent the error. If you are just using
2115the standard unittest test runner then this detail doesn't matter, but if you
2116are a framework author it may be relevant.
2117
2118
2119setUpClass and tearDownClass
2120~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2121
2122These must be implemented as class methods::
2123
2124 import unittest
2125
2126 class Test(unittest.TestCase):
2127 @classmethod
2128 def setUpClass(cls):
2129 cls._connection = createExpensiveConnectionObject()
2130
2131 @classmethod
2132 def tearDownClass(cls):
2133 cls._connection.destroy()
2134
2135If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2136then you must call up to them yourself. The implementations in
2137:class:`TestCase` are empty.
2138
2139If an exception is raised during a ``setUpClass`` then the tests in the class
2140are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002141have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002142:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002143instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002144
2145
2146setUpModule and tearDownModule
2147~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2148
2149These should be implemented as functions::
2150
2151 def setUpModule():
2152 createConnection()
2153
2154 def tearDownModule():
2155 closeConnection()
2156
2157If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002158module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002159:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002160instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002161
2162
2163Signal Handling
2164---------------
2165
Georg Brandl419e3de2010-12-01 15:44:25 +00002166.. versionadded:: 3.2
2167
Éric Araujo8acb67c2010-11-26 23:31:07 +00002168The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002169along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2170more friendly handling of control-C during a test run. With catch break
2171behavior enabled control-C will allow the currently running test to complete,
2172and the test run will then end and report all the results so far. A second
2173control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002174
Michael Foordde4ceab2010-04-25 19:53:49 +00002175The control-c handling signal handler attempts to remain compatible with code or
2176tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2177handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2178i.e. it has been replaced by the system under test and delegated to, then it
2179calls the default handler. This will normally be the expected behavior by code
2180that replaces an installed handler and delegates to it. For individual tests
2181that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2182decorator can be used.
2183
2184There are a few utility functions for framework authors to enable control-c
2185handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002186
2187.. function:: installHandler()
2188
2189 Install the control-c handler. When a :const:`signal.SIGINT` is received
2190 (usually in response to the user pressing control-c) all registered results
2191 have :meth:`~TestResult.stop` called.
2192
Michael Foord469b1f02010-04-26 23:41:26 +00002193
Benjamin Petersonb48af542010-04-11 20:43:16 +00002194.. function:: registerResult(result)
2195
2196 Register a :class:`TestResult` object for control-c handling. Registering a
2197 result stores a weak reference to it, so it doesn't prevent the result from
2198 being garbage collected.
2199
Michael Foordde4ceab2010-04-25 19:53:49 +00002200 Registering a :class:`TestResult` object has no side-effects if control-c
2201 handling is not enabled, so test frameworks can unconditionally register
2202 all results they create independently of whether or not handling is enabled.
2203
Michael Foord469b1f02010-04-26 23:41:26 +00002204
Benjamin Petersonb48af542010-04-11 20:43:16 +00002205.. function:: removeResult(result)
2206
2207 Remove a registered result. Once a result has been removed then
2208 :meth:`~TestResult.stop` will no longer be called on that result object in
2209 response to a control-c.
2210
Michael Foord469b1f02010-04-26 23:41:26 +00002211
Michael Foordde4ceab2010-04-25 19:53:49 +00002212.. function:: removeHandler(function=None)
2213
2214 When called without arguments this function removes the control-c handler
2215 if it has been installed. This function can also be used as a test decorator
2216 to temporarily remove the handler whilst the test is being executed::
2217
2218 @unittest.removeHandler
2219 def test_signal_handling(self):
2220 ...