blob: 52f6e3f41eb719e914ac719e35fe68d5da534ed9 [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
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000054 `Nose <http://code.google.com/p/python-nose/>`_ 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
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010058 `The Python Testing Tools Taxonomy <http://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
70 `Buildbot <http://buildbot.net/trac>`_, `Jenkins <http://jenkins-ci.org>`_
71 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
83Here is a short script to test three functions from the :mod:`random` module::
84
85 import random
86 import unittest
87
88 class TestSequenceFunctions(unittest.TestCase):
89
90 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +000091 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +000092
Benjamin Peterson52baa292009-03-24 00:56:30 +000093 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +000094 # make sure the shuffled sequence does not lose any elements
95 random.shuffle(self.seq)
96 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +000097 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +000098
Benjamin Peterson847a4112010-03-14 15:04:17 +000099 # should raise an exception for an immutable sequence
100 self.assertRaises(TypeError, random.shuffle, (1,2,3))
101
Benjamin Peterson52baa292009-03-24 00:56:30 +0000102 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000103 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000104 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Benjamin Peterson52baa292009-03-24 00:56:30 +0000106 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000107 with self.assertRaises(ValueError):
108 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000109 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000110 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112 if __name__ == '__main__':
113 unittest.main()
114
Benjamin Peterson52baa292009-03-24 00:56:30 +0000115A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000116individual tests are defined with methods whose names start with the letters
117``test``. This naming convention informs the test runner about which methods
118represent tests.
119
Benjamin Peterson52baa292009-03-24 00:56:30 +0000120The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000121expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000122:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
123These methods are used instead of the :keyword:`assert` statement so the test
124runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000125
Benjamin Peterson52baa292009-03-24 00:56:30 +0000126When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
127method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
128defined, the test runner will invoke that method after each test. In the
129example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
130test.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000133provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000134line, the above script produces an output that looks like this::
135
136 ...
137 ----------------------------------------------------------------------
138 Ran 3 tests in 0.000s
139
140 OK
141
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100142Passing the ``-v`` option to your test script will instruct :func:`unittest.main`
143to enable a higher level of verbosity, and produce the following output::
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Ezio Melottid59e44a2010-02-28 03:46:13 +0000145 test_choice (__main__.TestSequenceFunctions) ... ok
146 test_sample (__main__.TestSequenceFunctions) ... ok
147 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149 ----------------------------------------------------------------------
150 Ran 3 tests in 0.110s
151
152 OK
153
154The above examples show the most commonly used :mod:`unittest` features which
155are sufficient to meet many everyday testing needs. The remainder of the
156documentation explores the full feature set from first principles.
157
Benjamin Petersonb48af542010-04-11 20:43:16 +0000158
159.. _unittest-command-line-interface:
160
Éric Araujo76338ec2010-11-26 23:46:18 +0000161Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000162----------------------
163
164The unittest module can be used from the command line to run tests from
165modules, classes or even individual test methods::
166
167 python -m unittest test_module1 test_module2
168 python -m unittest test_module.TestClass
169 python -m unittest test_module.TestClass.test_method
170
171You can pass in a list with any combination of module names, and fully
172qualified class or method names.
173
Michael Foord37d120a2010-12-04 01:11:21 +0000174Test modules can be specified by file path as well::
175
176 python -m unittest tests/test_something.py
177
178This allows you to use the shell filename completion to specify the test module.
179The file specified must still be importable as a module. The path is converted
180to a module name by removing the '.py' and converting path separators into '.'.
181If you want to execute a test file that isn't importable as a module you should
182execute the file directly instead.
183
Benjamin Petersonb48af542010-04-11 20:43:16 +0000184You can run tests with more detail (higher verbosity) by passing in the -v flag::
185
186 python -m unittest -v test_module
187
Michael Foord086f3082010-11-21 21:28:01 +0000188When executed without arguments :ref:`unittest-test-discovery` is started::
189
190 python -m unittest
191
Éric Araujo713d3032010-11-18 16:38:46 +0000192For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000193
194 python -m unittest -h
195
Georg Brandl67b21b72010-08-17 15:07:14 +0000196.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000197 In earlier versions it was only possible to run individual test methods and
198 not modules or classes.
199
200
Éric Araujo76338ec2010-11-26 23:46:18 +0000201Command-line options
202~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000203
Éric Araujod3309df2010-11-21 03:09:17 +0000204:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000205
Éric Araujo713d3032010-11-18 16:38:46 +0000206.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000207
Éric Araujo713d3032010-11-18 16:38:46 +0000208.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000209
Éric Araujo713d3032010-11-18 16:38:46 +0000210 The standard output and standard error streams are buffered during the test
211 run. Output during a passing test is discarded. Output is echoed normally
212 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000213
Éric Araujo713d3032010-11-18 16:38:46 +0000214.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000215
Éric Araujo713d3032010-11-18 16:38:46 +0000216 Control-C during the test run waits for the current test to end and then
217 reports all the results so far. A second control-C raises the normal
218 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000219
Éric Araujo713d3032010-11-18 16:38:46 +0000220 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000221
Éric Araujo713d3032010-11-18 16:38:46 +0000222.. cmdoption:: -f, --failfast
223
224 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000225
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000226.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000227 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000228
229The command line can also be used for test discovery, for running all of the
230tests in a project or just a subset.
231
232
233.. _unittest-test-discovery:
234
235Test Discovery
236--------------
237
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000238.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000239
Ezio Melotti3d995842011-03-08 16:17:35 +0200240Unittest supports simple test discovery. In order to be compatible with test
241discovery, all of the test files must be :ref:`modules <tut-modules>` or
Larry Hastings3732ed22014-03-15 21:13:56 -0700242:ref:`packages <tut-packages>` (including :term:`namespace packages
243<namespace package>`) importable from the top-level directory of
244the project (this means that their filenames must be valid :ref:`identifiers
245<identifiers>`).
Benjamin Petersonb48af542010-04-11 20:43:16 +0000246
247Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000248used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000249
250 cd project_directory
251 python -m unittest discover
252
Michael Foord086f3082010-11-21 21:28:01 +0000253.. note::
254
255 As a shortcut, ``python -m unittest`` is the equivalent of
256 ``python -m unittest discover``. If you want to pass arguments to test
Éric Araujo941afed2011-09-01 02:47:34 +0200257 discovery the ``discover`` sub-command must be used explicitly.
Michael Foord086f3082010-11-21 21:28:01 +0000258
Benjamin Petersonb48af542010-04-11 20:43:16 +0000259The ``discover`` sub-command has the following options:
260
Éric Araujo713d3032010-11-18 16:38:46 +0000261.. program:: unittest discover
262
263.. cmdoption:: -v, --verbose
264
265 Verbose output
266
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800267.. cmdoption:: -s, --start-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000268
Éric Araujo941afed2011-09-01 02:47:34 +0200269 Directory to start discovery (``.`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000270
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800271.. cmdoption:: -p, --pattern pattern
Éric Araujo713d3032010-11-18 16:38:46 +0000272
Éric Araujo941afed2011-09-01 02:47:34 +0200273 Pattern to match test files (``test*.py`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000274
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800275.. cmdoption:: -t, --top-level-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000276
277 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000278
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000279The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
280as positional arguments in that order. The following two command lines
281are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000282
283 python -m unittest discover -s project_directory -p '*_test.py'
284 python -m unittest discover project_directory '*_test.py'
285
Michael Foord16f3e902010-05-08 15:13:42 +0000286As well as being a path it is possible to pass a package name, for example
287``myproject.subpackage.test``, as the start directory. The package name you
288supply will then be imported and its location on the filesystem will be used
289as the start directory.
290
291.. caution::
292
Senthil Kumaran916bd382010-10-15 12:55:19 +0000293 Test discovery loads tests by importing them. Once test discovery has found
294 all the test files from the start directory you specify it turns the paths
295 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000296 imported as ``foo.bar.baz``.
297
298 If you have a package installed globally and attempt test discovery on
299 a different copy of the package then the import *could* happen from the
300 wrong place. If this happens test discovery will warn you and exit.
301
302 If you supply the start directory as a package name rather than a
303 path to a directory then discover assumes that whichever location it
304 imports from is the location you intended, so you will not get the
305 warning.
306
Benjamin Petersonb48af542010-04-11 20:43:16 +0000307Test modules and packages can customize test loading and discovery by through
308the `load_tests protocol`_.
309
Larry Hastings3732ed22014-03-15 21:13:56 -0700310.. versionchanged:: 3.4
311 Test discovery supports :term:`namespace packages <namespace package>`.
312
Benjamin Petersonb48af542010-04-11 20:43:16 +0000313
Georg Brandl116aa622007-08-15 14:28:22 +0000314.. _organizing-tests:
315
316Organizing test code
317--------------------
318
319The basic building blocks of unit testing are :dfn:`test cases` --- single
320scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000321test cases are represented by :class:`unittest.TestCase` instances.
322To make your own test cases you must write subclasses of
323:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000324
Georg Brandl116aa622007-08-15 14:28:22 +0000325The testing code of a :class:`TestCase` instance should be entirely self
326contained, such that it can be run either in isolation or in arbitrary
327combination with any number of other test cases.
328
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100329The simplest :class:`TestCase` subclass will simply implement a test method
330(i.e. a method whose name starts with ``test``) in order to perform specific
331testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000332
333 import unittest
334
335 class DefaultWidgetSizeTestCase(unittest.TestCase):
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100336 def test_default_widget_size(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000337 widget = Widget('The widget')
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100338 self.assertEqual(widget.size(), (50, 50))
Georg Brandl116aa622007-08-15 14:28:22 +0000339
Sandro Tosi41b24042012-01-21 10:59:37 +0100340Note that in order to test something, we use one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000341methods provided by the :class:`TestCase` base class. If the test fails, an
342exception will be raised, and :mod:`unittest` will identify the test case as a
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100343:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`.
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100345Tests can be numerous, and their set-up can be repetitive. Luckily, we
346can factor out set-up code by implementing a method called
347:meth:`~TestCase.setUp`, which the testing framework will automatically
348call for every single test we run::
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350 import unittest
351
352 class SimpleWidgetTestCase(unittest.TestCase):
353 def setUp(self):
354 self.widget = Widget('The widget')
355
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100356 def test_default_widget_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000357 self.assertEqual(self.widget.size(), (50,50),
358 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100360 def test_widget_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000361 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000362 self.assertEqual(self.widget.size(), (100,150),
363 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000364
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100365.. note::
366 The order in which the various tests will be run is determined
367 by sorting the test method names with respect to the built-in
368 ordering for strings.
369
Benjamin Peterson52baa292009-03-24 00:56:30 +0000370If the :meth:`~TestCase.setUp` method raises an exception while the test is
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100371running, the framework will consider the test to have suffered an error, and
372the test method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000373
Benjamin Peterson52baa292009-03-24 00:56:30 +0000374Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100375after the test method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000376
377 import unittest
378
379 class SimpleWidgetTestCase(unittest.TestCase):
380 def setUp(self):
381 self.widget = Widget('The widget')
382
383 def tearDown(self):
384 self.widget.dispose()
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100386If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be
387run whether the test method succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000388
389Such a working environment for the testing code is called a :dfn:`fixture`.
390
Georg Brandl116aa622007-08-15 14:28:22 +0000391Test case instances are grouped together according to the features they test.
392:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100393represented by :mod:`unittest`'s :class:`TestSuite` class. In most cases,
394calling :func:`unittest.main` will do the right thing and collect all the
395module's test cases for you, and then execute them.
Georg Brandl116aa622007-08-15 14:28:22 +0000396
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100397However, should you want to customize the building of your test suite,
398you can do it yourself::
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400 def suite():
401 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000402 suite.addTest(WidgetTestCase('test_default_size'))
403 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000404 return suite
405
Georg Brandl116aa622007-08-15 14:28:22 +0000406You can place the definitions of test cases and test suites in the same modules
407as the code they are to test (such as :file:`widget.py`), but there are several
408advantages to placing the test code in a separate module, such as
409:file:`test_widget.py`:
410
411* The test module can be run standalone from the command line.
412
413* The test code can more easily be separated from shipped code.
414
415* There is less temptation to change test code to fit the code it tests without
416 a good reason.
417
418* Test code should be modified much less frequently than the code it tests.
419
420* Tested code can be refactored more easily.
421
422* Tests for modules written in C must be in separate modules anyway, so why not
423 be consistent?
424
425* If the testing strategy changes, there is no need to change the source code.
426
427
428.. _legacy-unit-tests:
429
430Re-using old test code
431----------------------
432
433Some users will find that they have existing test code that they would like to
434run from :mod:`unittest`, without converting every old test function to a
435:class:`TestCase` subclass.
436
437For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
438This subclass of :class:`TestCase` can be used to wrap an existing test
439function. Set-up and tear-down functions can also be provided.
440
441Given the following test function::
442
443 def testSomething():
444 something = makeSomething()
445 assert something.name is not None
446 # ...
447
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100448one can create an equivalent test case instance as follows, with optional
449set-up and tear-down methods::
Georg Brandl116aa622007-08-15 14:28:22 +0000450
451 testcase = unittest.FunctionTestCase(testSomething,
452 setUp=makeSomethingDB,
453 tearDown=deleteSomethingDB)
454
Georg Brandl116aa622007-08-15 14:28:22 +0000455.. note::
456
Benjamin Petersond2397752009-06-27 23:45:02 +0000457 Even though :class:`FunctionTestCase` can be used to quickly convert an
458 existing test base over to a :mod:`unittest`\ -based system, this approach is
459 not recommended. Taking the time to set up proper :class:`TestCase`
460 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000461
Benjamin Peterson52baa292009-03-24 00:56:30 +0000462In some cases, the existing tests may have been written using the :mod:`doctest`
463module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
464automatically build :class:`unittest.TestSuite` instances from the existing
465:mod:`doctest`\ -based tests.
466
Georg Brandl116aa622007-08-15 14:28:22 +0000467
Benjamin Peterson5254c042009-03-23 22:25:03 +0000468.. _unittest-skipping:
469
470Skipping tests and expected failures
471------------------------------------
472
Michael Foordf5c851a2010-02-05 21:48:03 +0000473.. versionadded:: 3.1
474
Benjamin Peterson5254c042009-03-23 22:25:03 +0000475Unittest supports skipping individual test methods and even whole classes of
476tests. In addition, it supports marking a test as a "expected failure," a test
477that is broken and will fail, but shouldn't be counted as a failure on a
478:class:`TestResult`.
479
480Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
481or one of its conditional variants.
482
Ezio Melottifed69ba2013-03-01 21:26:04 +0200483Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000484
485 class MyTestCase(unittest.TestCase):
486
487 @unittest.skip("demonstrating skipping")
488 def test_nothing(self):
489 self.fail("shouldn't happen")
490
Benjamin Petersond2397752009-06-27 23:45:02 +0000491 @unittest.skipIf(mylib.__version__ < (1, 3),
492 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000493 def test_format(self):
494 # Tests that work for only a certain version of the library.
495 pass
496
497 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
498 def test_windows_support(self):
499 # windows specific testing code
500 pass
501
Ezio Melottifed69ba2013-03-01 21:26:04 +0200502This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000503
Benjamin Petersonded31c42009-03-30 15:04:16 +0000504 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000505 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000506 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000507
508 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000509 Ran 3 tests in 0.005s
510
511 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000512
Ezio Melottifed69ba2013-03-01 21:26:04 +0200513Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000514
Sandro Tosi317075d2012-03-31 18:34:59 +0200515 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000516 class MySkippedTestCase(unittest.TestCase):
517 def test_not_run(self):
518 pass
519
Benjamin Peterson52baa292009-03-24 00:56:30 +0000520:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
521that needs to be set up is not available.
522
Benjamin Peterson5254c042009-03-23 22:25:03 +0000523Expected failures use the :func:`expectedFailure` decorator. ::
524
525 class ExpectedFailureTestCase(unittest.TestCase):
526 @unittest.expectedFailure
527 def test_fail(self):
528 self.assertEqual(1, 0, "broken")
529
530It's easy to roll your own skipping decorators by making a decorator that calls
531:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottifed69ba2013-03-01 21:26:04 +0200532the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000533
534 def skipUnlessHasattr(obj, attr):
535 if hasattr(obj, attr):
536 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200537 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000538
539The following decorators implement test skipping and expected failures:
540
Georg Brandl8a1caa22010-07-29 16:01:11 +0000541.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000542
543 Unconditionally skip the decorated test. *reason* should describe why the
544 test is being skipped.
545
Georg Brandl8a1caa22010-07-29 16:01:11 +0000546.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000547
548 Skip the decorated test if *condition* is true.
549
Georg Brandl8a1caa22010-07-29 16:01:11 +0000550.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000551
Georg Brandl6faee4e2010-09-21 14:48:28 +0000552 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000553
Georg Brandl8a1caa22010-07-29 16:01:11 +0000554.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000555
556 Mark the test as an expected failure. If the test fails when run, the test
557 is not counted as a failure.
558
Ezio Melotti265281a2013-03-27 20:11:55 +0200559.. exception:: SkipTest(reason)
560
561 This exception is raised to skip a test.
562
563 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
564 decorators instead of raising this directly.
565
R David Murray42fa1102014-01-03 13:03:36 -0500566Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them.
567Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run.
568Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000569
Benjamin Peterson5254c042009-03-23 22:25:03 +0000570
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100571.. _subtests:
572
573Distinguishing test iterations using subtests
574---------------------------------------------
575
576.. versionadded:: 3.4
577
578When some of your tests differ only by a some very small differences, for
579instance some parameters, unittest allows you to distinguish them inside
580the body of a test method using the :meth:`~TestCase.subTest` context manager.
581
582For example, the following test::
583
584 class NumbersTest(unittest.TestCase):
585
586 def test_even(self):
587 """
588 Test that numbers between 0 and 5 are all even.
589 """
590 for i in range(0, 6):
591 with self.subTest(i=i):
592 self.assertEqual(i % 2, 0)
593
594will produce the following output::
595
596 ======================================================================
597 FAIL: test_even (__main__.NumbersTest) (i=1)
598 ----------------------------------------------------------------------
599 Traceback (most recent call last):
600 File "subtests.py", line 32, in test_even
601 self.assertEqual(i % 2, 0)
602 AssertionError: 1 != 0
603
604 ======================================================================
605 FAIL: test_even (__main__.NumbersTest) (i=3)
606 ----------------------------------------------------------------------
607 Traceback (most recent call last):
608 File "subtests.py", line 32, in test_even
609 self.assertEqual(i % 2, 0)
610 AssertionError: 1 != 0
611
612 ======================================================================
613 FAIL: test_even (__main__.NumbersTest) (i=5)
614 ----------------------------------------------------------------------
615 Traceback (most recent call last):
616 File "subtests.py", line 32, in test_even
617 self.assertEqual(i % 2, 0)
618 AssertionError: 1 != 0
619
620Without using a subtest, execution would stop after the first failure,
621and the error would be less easy to diagnose because the value of ``i``
622wouldn't be displayed::
623
624 ======================================================================
625 FAIL: test_even (__main__.NumbersTest)
626 ----------------------------------------------------------------------
627 Traceback (most recent call last):
628 File "subtests.py", line 32, in test_even
629 self.assertEqual(i % 2, 0)
630 AssertionError: 1 != 0
631
632
Georg Brandl116aa622007-08-15 14:28:22 +0000633.. _unittest-contents:
634
635Classes and functions
636---------------------
637
Benjamin Peterson52baa292009-03-24 00:56:30 +0000638This section describes in depth the API of :mod:`unittest`.
639
640
641.. _testcase-objects:
642
643Test cases
644~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Georg Brandl7f01a132009-09-16 15:58:14 +0000646.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000647
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100648 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000649 in the :mod:`unittest` universe. This class is intended to be used as a base
650 class, with specific tests being implemented by concrete subclasses. This class
651 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100652 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000653 kinds of failure.
654
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100655 Each instance of :class:`TestCase` will run a single base method: the method
656 named *methodName*. However, the standard implementation of the default
657 *methodName*, ``runTest()``, will run every method starting with ``test``
658 as an individual test, and count successes and failures accordingly.
659 Therefore, in most uses of :class:`TestCase`, you will neither change
660 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000661
Michael Foord1341bb02011-03-14 19:01:46 -0400662 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100663 :class:`TestCase` can be instantiated successfully without providing a
664 *methodName*. This makes it easier to experiment with :class:`TestCase`
665 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000666
667 :class:`TestCase` instances provide three groups of methods: one group used
668 to run the test, another used by the test implementation to check conditions
669 and report failures, and some inquiry methods allowing information about the
670 test itself to be gathered.
671
672 Methods in the first group (running the test) are:
673
Benjamin Peterson52baa292009-03-24 00:56:30 +0000674 .. method:: setUp()
675
676 Method called to prepare the test fixture. This is called immediately
Terry Jan Reedy7f84d1e2014-04-15 23:44:14 -0400677 before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`,
678 any exception raised by this method will be considered an error rather than
Terry Jan Reedy6ac42402014-04-15 23:38:18 -0400679 a test failure. The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000680
681
682 .. method:: tearDown()
683
684 Method called immediately after the test method has been called and the
685 result recorded. This is called even if the test method raised an
686 exception, so the implementation in subclasses may need to be particularly
Terry Jan Reedy7f84d1e2014-04-15 23:44:14 -0400687 careful about checking internal state. Any exception, other than :exc:`AssertionError`
688 or :exc:`SkipTest`, raised by this method will be considered an error rather than a
689 test failure. This method will only be called if the :meth:`setUp` succeeds,
Terry Jan Reedy6ac42402014-04-15 23:38:18 -0400690 regardless of the outcome of the test method. The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000691
692
Benjamin Petersonb48af542010-04-11 20:43:16 +0000693 .. method:: setUpClass()
694
695 A class method called before tests in an individual class run.
696 ``setUpClass`` is called with the class as the only argument
697 and must be decorated as a :func:`classmethod`::
698
699 @classmethod
700 def setUpClass(cls):
701 ...
702
703 See `Class and Module Fixtures`_ for more details.
704
705 .. versionadded:: 3.2
706
707
708 .. method:: tearDownClass()
709
710 A class method called after tests in an individual class have run.
711 ``tearDownClass`` is called with the class as the only argument
712 and must be decorated as a :meth:`classmethod`::
713
714 @classmethod
715 def tearDownClass(cls):
716 ...
717
718 See `Class and Module Fixtures`_ for more details.
719
720 .. versionadded:: 3.2
721
722
Georg Brandl7f01a132009-09-16 15:58:14 +0000723 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000724
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100725 Run the test, collecting the result into the :class:`TestResult` object
726 passed as *result*. If *result* is omitted or ``None``, a temporary
727 result object is created (by calling the :meth:`defaultTestResult`
728 method) and used. The result object is returned to :meth:`run`'s
729 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000730
731 The same effect may be had by simply calling the :class:`TestCase`
732 instance.
733
Michael Foord1341bb02011-03-14 19:01:46 -0400734 .. versionchanged:: 3.3
735 Previous versions of ``run`` did not return the result. Neither did
736 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000737
Benjamin Petersone549ead2009-03-28 21:42:05 +0000738 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000739
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000740 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000741 test. See :ref:`unittest-skipping` for more information.
742
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000743 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000744
Benjamin Peterson52baa292009-03-24 00:56:30 +0000745
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100746 .. method:: subTest(msg=None, **params)
747
748 Return a context manager which executes the enclosed code block as a
749 subtest. *msg* and *params* are optional, arbitrary values which are
750 displayed whenever a subtest fails, allowing you to identify them
751 clearly.
752
753 A test case can contain any number of subtest declarations, and
754 they can be arbitrarily nested.
755
756 See :ref:`subtests` for more information.
757
758 .. versionadded:: 3.4
759
760
Benjamin Peterson52baa292009-03-24 00:56:30 +0000761 .. method:: debug()
762
763 Run the test without collecting the result. This allows exceptions raised
764 by the test to be propagated to the caller, and can be used to support
765 running tests under a debugger.
766
Ezio Melotti22170ed2010-11-20 09:57:27 +0000767 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000768
Ezio Melotti4370b302010-11-03 20:39:14 +0000769 The :class:`TestCase` class provides a number of methods to check for and
770 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000771
Ezio Melotti4370b302010-11-03 20:39:14 +0000772 +-----------------------------------------+-----------------------------+---------------+
773 | Method | Checks that | New in |
774 +=========================================+=============================+===============+
775 | :meth:`assertEqual(a, b) | ``a == b`` | |
776 | <TestCase.assertEqual>` | | |
777 +-----------------------------------------+-----------------------------+---------------+
778 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
779 | <TestCase.assertNotEqual>` | | |
780 +-----------------------------------------+-----------------------------+---------------+
781 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
782 | <TestCase.assertTrue>` | | |
783 +-----------------------------------------+-----------------------------+---------------+
784 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
785 | <TestCase.assertFalse>` | | |
786 +-----------------------------------------+-----------------------------+---------------+
787 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
788 | <TestCase.assertIs>` | | |
789 +-----------------------------------------+-----------------------------+---------------+
790 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
791 | <TestCase.assertIsNot>` | | |
792 +-----------------------------------------+-----------------------------+---------------+
793 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
794 | <TestCase.assertIsNone>` | | |
795 +-----------------------------------------+-----------------------------+---------------+
796 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
797 | <TestCase.assertIsNotNone>` | | |
798 +-----------------------------------------+-----------------------------+---------------+
799 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
800 | <TestCase.assertIn>` | | |
801 +-----------------------------------------+-----------------------------+---------------+
802 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
803 | <TestCase.assertNotIn>` | | |
804 +-----------------------------------------+-----------------------------+---------------+
805 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
806 | <TestCase.assertIsInstance>` | | |
807 +-----------------------------------------+-----------------------------+---------------+
808 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
809 | <TestCase.assertNotIsInstance>` | | |
810 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000811
Ezio Melottib4dc2502011-05-06 15:01:41 +0300812 All the assert methods accept a *msg* argument that, if specified, is used
813 as the error message on failure (see also :data:`longMessage`).
814 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
815 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
816 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000817
Michael Foorde180d392011-01-28 19:51:48 +0000818 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000819
Michael Foorde180d392011-01-28 19:51:48 +0000820 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000821 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000822
Michael Foorde180d392011-01-28 19:51:48 +0000823 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000824 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200825 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000826 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000827 error message (see also the :ref:`list of type-specific methods
828 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000829
Raymond Hettinger35a88362009-04-09 00:08:24 +0000830 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200831 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000832
Michael Foord28a817e2010-02-09 00:03:57 +0000833 .. versionchanged:: 3.2
834 :meth:`assertMultiLineEqual` added as the default type equality
835 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000836
Benjamin Peterson52baa292009-03-24 00:56:30 +0000837
Michael Foorde180d392011-01-28 19:51:48 +0000838 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000839
Michael Foorde180d392011-01-28 19:51:48 +0000840 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000841 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000842
Ezio Melotti4370b302010-11-03 20:39:14 +0000843 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000844 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000845
Ezio Melotti4841fd62010-11-05 15:43:40 +0000846 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000847
Ezio Melotti4841fd62010-11-05 15:43:40 +0000848 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
849 is True`` (use ``assertIs(expr, True)`` for the latter). This method
850 should also be avoided when more specific methods are available (e.g.
851 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
852 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000853
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000854
Michael Foorde180d392011-01-28 19:51:48 +0000855 .. method:: assertIs(first, second, msg=None)
856 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000857
Michael Foorde180d392011-01-28 19:51:48 +0000858 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000859 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000860
Raymond Hettinger35a88362009-04-09 00:08:24 +0000861 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000862
863
Ezio Melotti4370b302010-11-03 20:39:14 +0000864 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000865 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000866
Ezio Melotti9794a262010-11-04 14:52:13 +0000867 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000868
Ezio Melotti4370b302010-11-03 20:39:14 +0000869 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000870
871
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000872 .. method:: assertIn(first, second, msg=None)
873 assertNotIn(first, second, msg=None)
874
Ezio Melotti4841fd62010-11-05 15:43:40 +0000875 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000876
Raymond Hettinger35a88362009-04-09 00:08:24 +0000877 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000878
879
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000880 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000881 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000882
Ezio Melotti9794a262010-11-04 14:52:13 +0000883 Test that *obj* is (or is not) an instance of *cls* (which can be a
884 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200885 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000886
Ezio Melotti4370b302010-11-03 20:39:14 +0000887 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000888
889
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000890
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200891 It is also possible to check the production of exceptions, warnings and
892 log messages using the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000893
Ezio Melotti4370b302010-11-03 20:39:14 +0000894 +---------------------------------------------------------+--------------------------------------+------------+
895 | Method | Checks that | New in |
896 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200897 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000898 | <TestCase.assertRaises>` | | |
899 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300900 | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
901 | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000902 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200903 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000904 | <TestCase.assertWarns>` | | |
905 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300906 | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
907 | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000908 +---------------------------------------------------------+--------------------------------------+------------+
Georg Brandled007d52013-11-24 16:09:26 +0100909 | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 |
910 | <TestCase.assertLogs>` | with minimum *level* | |
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200911 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000912
Georg Brandl7f01a132009-09-16 15:58:14 +0000913 .. method:: assertRaises(exception, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300914 assertRaises(exception, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000915
916 Test that an exception is raised when *callable* is called with any
917 positional or keyword arguments that are also passed to
918 :meth:`assertRaises`. The test passes if *exception* is raised, is an
919 error if another exception is raised, or fails if no exception is raised.
920 To catch any of a group of exceptions, a tuple containing the exception
921 classes may be passed as *exception*.
922
Ezio Melottib4dc2502011-05-06 15:01:41 +0300923 If only the *exception* and possibly the *msg* arguments are given,
924 return a context manager so that the code under test can be written
925 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000926
Michael Foord41531f22010-02-05 21:13:40 +0000927 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000928 do_something()
929
Ezio Melottib4dc2502011-05-06 15:01:41 +0300930 When used as a context manager, :meth:`assertRaises` accepts the
931 additional keyword argument *msg*.
932
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000933 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000934 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000935 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000936
Georg Brandl8a1caa22010-07-29 16:01:11 +0000937 with self.assertRaises(SomeException) as cm:
938 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000939
Georg Brandl8a1caa22010-07-29 16:01:11 +0000940 the_exception = cm.exception
941 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000942
Ezio Melotti49008232010-02-08 21:57:48 +0000943 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000944 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000945
Ezio Melotti49008232010-02-08 21:57:48 +0000946 .. versionchanged:: 3.2
947 Added the :attr:`exception` attribute.
948
Ezio Melottib4dc2502011-05-06 15:01:41 +0300949 .. versionchanged:: 3.3
950 Added the *msg* keyword argument when used as a context manager.
951
Benjamin Peterson52baa292009-03-24 00:56:30 +0000952
Ezio Melottied3a7d22010-12-01 02:32:32 +0000953 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300954 assertRaisesRegex(exception, regex, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000955
Ezio Melottied3a7d22010-12-01 02:32:32 +0000956 Like :meth:`assertRaises` but also tests that *regex* matches
957 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000958 a regular expression object or a string containing a regular expression
959 suitable for use by :func:`re.search`. Examples::
960
Terry Jan Reedyc4565a92013-06-29 13:15:43 -0400961 self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
Ezio Melottied3a7d22010-12-01 02:32:32 +0000962 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000963
964 or::
965
Ezio Melottied3a7d22010-12-01 02:32:32 +0000966 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000967 int('XYZ')
968
Georg Brandl419e3de2010-12-01 15:44:25 +0000969 .. versionadded:: 3.1
970 under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +0300971
Ezio Melottied3a7d22010-12-01 02:32:32 +0000972 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +0000973 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000974
Ezio Melottib4dc2502011-05-06 15:01:41 +0300975 .. versionchanged:: 3.3
976 Added the *msg* keyword argument when used as a context manager.
977
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000978
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000979 .. method:: assertWarns(warning, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300980 assertWarns(warning, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000981
982 Test that a warning is triggered when *callable* is called with any
983 positional or keyword arguments that are also passed to
984 :meth:`assertWarns`. The test passes if *warning* is triggered and
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400985 fails if it isn't. Any exception is an error.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000986 To catch any of a group of warnings, a tuple containing the warning
987 classes may be passed as *warnings*.
988
Ezio Melottib4dc2502011-05-06 15:01:41 +0300989 If only the *warning* and possibly the *msg* arguments are given,
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400990 return a context manager so that the code under test can be written
Ezio Melottib4dc2502011-05-06 15:01:41 +0300991 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000992
993 with self.assertWarns(SomeWarning):
994 do_something()
995
Terry Jan Reedy9eda66d2013-07-27 16:15:29 -0400996 When used as a context manager, :meth:`assertWarns` accepts the
Ezio Melottib4dc2502011-05-06 15:01:41 +0300997 additional keyword argument *msg*.
998
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000999 The context manager will store the caught warning object in its
1000 :attr:`warning` attribute, and the source line which triggered the
1001 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1002 This can be useful if the intention is to perform additional checks
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001003 on the warning caught::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001004
1005 with self.assertWarns(SomeWarning) as cm:
1006 do_something()
1007
1008 self.assertIn('myfile.py', cm.filename)
1009 self.assertEqual(320, cm.lineno)
1010
1011 This method works regardless of the warning filters in place when it
1012 is called.
1013
1014 .. versionadded:: 3.2
1015
Ezio Melottib4dc2502011-05-06 15:01:41 +03001016 .. versionchanged:: 3.3
1017 Added the *msg* keyword argument when used as a context manager.
1018
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001019
Ezio Melottied3a7d22010-12-01 02:32:32 +00001020 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001021 assertWarnsRegex(warning, regex, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001022
Ezio Melottied3a7d22010-12-01 02:32:32 +00001023 Like :meth:`assertWarns` but also tests that *regex* matches on the
1024 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001025 object or a string containing a regular expression suitable for use
1026 by :func:`re.search`. Example::
1027
Ezio Melottied3a7d22010-12-01 02:32:32 +00001028 self.assertWarnsRegex(DeprecationWarning,
1029 r'legacy_function\(\) is deprecated',
1030 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001031
1032 or::
1033
Ezio Melottied3a7d22010-12-01 02:32:32 +00001034 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001035 frobnicate('/etc/passwd')
1036
1037 .. versionadded:: 3.2
1038
Ezio Melottib4dc2502011-05-06 15:01:41 +03001039 .. versionchanged:: 3.3
1040 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001041
Antoine Pitrou0715b9f2013-09-14 19:45:47 +02001042 .. method:: assertLogs(logger=None, level=None)
1043
1044 A context manager to test that at least one message is logged on
1045 the *logger* or one of its children, with at least the given
1046 *level*.
1047
1048 If given, *logger* should be a :class:`logging.Logger` object or a
1049 :class:`str` giving the name of a logger. The default is the root
1050 logger, which will catch all messages.
1051
1052 If given, *level* should be either a numeric logging level or
1053 its string equivalent (for example either ``"ERROR"`` or
1054 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`.
1055
1056 The test passes if at least one message emitted inside the ``with``
1057 block matches the *logger* and *level* conditions, otherwise it fails.
1058
1059 The object returned by the context manager is a recording helper
1060 which keeps tracks of the matching log messages. It has two
1061 attributes:
1062
1063 .. attribute:: records
1064
1065 A list of :class:`logging.LogRecord` objects of the matching
1066 log messages.
1067
1068 .. attribute:: output
1069
1070 A list of :class:`str` objects with the formatted output of
1071 matching messages.
1072
1073 Example::
1074
1075 with self.assertLogs('foo', level='INFO') as cm:
1076 logging.getLogger('foo').info('first message')
1077 logging.getLogger('foo.bar').error('second message')
1078 self.assertEqual(cm.output, ['INFO:foo:first message',
1079 'ERROR:foo.bar:second message'])
1080
1081 .. versionadded:: 3.4
1082
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001083
Ezio Melotti4370b302010-11-03 20:39:14 +00001084 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001085
Ezio Melotti4370b302010-11-03 20:39:14 +00001086 +---------------------------------------+--------------------------------+--------------+
1087 | Method | Checks that | New in |
1088 +=======================================+================================+==============+
1089 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1090 | <TestCase.assertAlmostEqual>` | | |
1091 +---------------------------------------+--------------------------------+--------------+
1092 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1093 | <TestCase.assertNotAlmostEqual>` | | |
1094 +---------------------------------------+--------------------------------+--------------+
1095 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1096 | <TestCase.assertGreater>` | | |
1097 +---------------------------------------+--------------------------------+--------------+
1098 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1099 | <TestCase.assertGreaterEqual>` | | |
1100 +---------------------------------------+--------------------------------+--------------+
1101 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1102 | <TestCase.assertLess>` | | |
1103 +---------------------------------------+--------------------------------+--------------+
1104 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1105 | <TestCase.assertLessEqual>` | | |
1106 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001107 | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001108 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001109 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001110 | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001111 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001112 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001113 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001114 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001115 | | regardless of their order | |
1116 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001117
1118
Michael Foorde180d392011-01-28 19:51:48 +00001119 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1120 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001121
Michael Foorde180d392011-01-28 19:51:48 +00001122 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001123 equal by computing the difference, rounding to the given number of
1124 decimal *places* (default 7), and comparing to zero. Note that these
1125 methods round the values to the given number of *decimal places* (i.e.
1126 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001127
Ezio Melotti4370b302010-11-03 20:39:14 +00001128 If *delta* is supplied instead of *places* then the difference
Ezio Melottid51914c2013-08-11 13:04:50 +03001129 between *first* and *second* must be less or equal to (or greater than) *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001130
Ezio Melotti4370b302010-11-03 20:39:14 +00001131 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001132
Ezio Melotti4370b302010-11-03 20:39:14 +00001133 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001134 :meth:`assertAlmostEqual` automatically considers almost equal objects
1135 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1136 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001137
Ezio Melotti4370b302010-11-03 20:39:14 +00001138
Michael Foorde180d392011-01-28 19:51:48 +00001139 .. method:: assertGreater(first, second, msg=None)
1140 assertGreaterEqual(first, second, msg=None)
1141 assertLess(first, second, msg=None)
1142 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001143
Michael Foorde180d392011-01-28 19:51:48 +00001144 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001145 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001146
1147 >>> self.assertGreaterEqual(3, 4)
1148 AssertionError: "3" unexpectedly not greater than or equal to "4"
1149
1150 .. versionadded:: 3.1
1151
1152
Ezio Melottied3a7d22010-12-01 02:32:32 +00001153 .. method:: assertRegex(text, regex, msg=None)
1154 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001155
Ezio Melottied3a7d22010-12-01 02:32:32 +00001156 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001157 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001158 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001159 may be a regular expression object or a string containing a regular
1160 expression suitable for use by :func:`re.search`.
1161
Georg Brandl419e3de2010-12-01 15:44:25 +00001162 .. versionadded:: 3.1
1163 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001164 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001165 The method ``assertRegexpMatches()`` has been renamed to
1166 :meth:`.assertRegex`.
1167 .. versionadded:: 3.2
1168 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001169
1170
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001171 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001172
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001173 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001174 regardless of their order. When they don't, an error message listing the
1175 differences between the sequences will be generated.
1176
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001177 Duplicate elements are *not* ignored when comparing *first* and
1178 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001179 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001180 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001181 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001182
Ezio Melotti4370b302010-11-03 20:39:14 +00001183 .. versionadded:: 3.2
1184
Ezio Melotti4370b302010-11-03 20:39:14 +00001185
Ezio Melotti22170ed2010-11-20 09:57:27 +00001186 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001187
Ezio Melotti22170ed2010-11-20 09:57:27 +00001188 The :meth:`assertEqual` method dispatches the equality check for objects of
1189 the same type to different type-specific methods. These methods are already
1190 implemented for most of the built-in types, but it's also possible to
1191 register new methods using :meth:`addTypeEqualityFunc`:
1192
1193 .. method:: addTypeEqualityFunc(typeobj, function)
1194
1195 Registers a type-specific method called by :meth:`assertEqual` to check
1196 if two objects of exactly the same *typeobj* (not subclasses) compare
1197 equal. *function* must take two positional arguments and a third msg=None
1198 keyword argument just as :meth:`assertEqual` does. It must raise
1199 :data:`self.failureException(msg) <failureException>` when inequality
1200 between the first two parameters is detected -- possibly providing useful
1201 information and explaining the inequalities in details in the error
1202 message.
1203
1204 .. versionadded:: 3.1
1205
1206 The list of type-specific methods automatically used by
1207 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1208 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001209
1210 +-----------------------------------------+-----------------------------+--------------+
1211 | Method | Used to compare | New in |
1212 +=========================================+=============================+==============+
1213 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1214 | <TestCase.assertMultiLineEqual>` | | |
1215 +-----------------------------------------+-----------------------------+--------------+
1216 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1217 | <TestCase.assertSequenceEqual>` | | |
1218 +-----------------------------------------+-----------------------------+--------------+
1219 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1220 | <TestCase.assertListEqual>` | | |
1221 +-----------------------------------------+-----------------------------+--------------+
1222 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1223 | <TestCase.assertTupleEqual>` | | |
1224 +-----------------------------------------+-----------------------------+--------------+
1225 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1226 | <TestCase.assertSetEqual>` | | |
1227 +-----------------------------------------+-----------------------------+--------------+
1228 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1229 | <TestCase.assertDictEqual>` | | |
1230 +-----------------------------------------+-----------------------------+--------------+
1231
1232
1233
Michael Foorde180d392011-01-28 19:51:48 +00001234 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001235
Michael Foorde180d392011-01-28 19:51:48 +00001236 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001237 When not equal a diff of the two strings highlighting the differences
1238 will be included in the error message. This method is used by default
1239 when comparing strings with :meth:`assertEqual`.
1240
Ezio Melotti4370b302010-11-03 20:39:14 +00001241 .. versionadded:: 3.1
1242
1243
Michael Foorde180d392011-01-28 19:51:48 +00001244 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001245
1246 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001247 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001248 be raised. If the sequences are different an error message is
1249 constructed that shows the difference between the two.
1250
Ezio Melotti22170ed2010-11-20 09:57:27 +00001251 This method is not called directly by :meth:`assertEqual`, but
1252 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001253 :meth:`assertTupleEqual`.
1254
1255 .. versionadded:: 3.1
1256
1257
Michael Foorde180d392011-01-28 19:51:48 +00001258 .. method:: assertListEqual(first, second, msg=None)
1259 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001260
Ezio Melotti49ccd512012-08-29 17:50:42 +03001261 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001262 constructed that shows only the differences between the two. An error
1263 is also raised if either of the parameters are of the wrong type.
1264 These methods are used by default when comparing lists or tuples with
1265 :meth:`assertEqual`.
1266
Ezio Melotti4370b302010-11-03 20:39:14 +00001267 .. versionadded:: 3.1
1268
1269
Michael Foorde180d392011-01-28 19:51:48 +00001270 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001271
1272 Tests that two sets are equal. If not, an error message is constructed
1273 that lists the differences between the sets. This method is used by
1274 default when comparing sets or frozensets with :meth:`assertEqual`.
1275
Michael Foorde180d392011-01-28 19:51:48 +00001276 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001277 method.
1278
Ezio Melotti4370b302010-11-03 20:39:14 +00001279 .. versionadded:: 3.1
1280
1281
Michael Foorde180d392011-01-28 19:51:48 +00001282 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001283
1284 Test that two dictionaries are equal. If not, an error message is
1285 constructed that shows the differences in the dictionaries. This
1286 method will be used by default to compare dictionaries in
1287 calls to :meth:`assertEqual`.
1288
Ezio Melotti4370b302010-11-03 20:39:14 +00001289 .. versionadded:: 3.1
1290
1291
1292
Ezio Melotti22170ed2010-11-20 09:57:27 +00001293 .. _other-methods-and-attrs:
1294
Ezio Melotti4370b302010-11-03 20:39:14 +00001295 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001296
Benjamin Peterson52baa292009-03-24 00:56:30 +00001297
Georg Brandl7f01a132009-09-16 15:58:14 +00001298 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001299
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001300 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001301 the error message.
1302
1303
1304 .. attribute:: failureException
1305
1306 This class attribute gives the exception raised by the test method. If a
1307 test framework needs to use a specialized exception, possibly to carry
1308 additional information, it must subclass this exception in order to "play
1309 fair" with the framework. The initial value of this attribute is
1310 :exc:`AssertionError`.
1311
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001312
1313 .. attribute:: longMessage
1314
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001315 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001316 :ref:`assert methods <assert-methods>` will be appended to the end of the
1317 normal failure message. The normal messages contain useful information
1318 about the objects involved, for example the message from assertEqual
1319 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001320 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001321 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001322
Michael Foord5074df62010-12-03 00:53:09 +00001323 This attribute defaults to ``True``. If set to False then a custom message
1324 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001325
1326 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001327 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001328
Raymond Hettinger35a88362009-04-09 00:08:24 +00001329 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001330
1331
Michael Foord98b3e762010-06-05 21:59:55 +00001332 .. attribute:: maxDiff
1333
1334 This attribute controls the maximum length of diffs output by assert
1335 methods that report diffs on failure. It defaults to 80*8 characters.
1336 Assert methods affected by this attribute are
1337 :meth:`assertSequenceEqual` (including all the sequence comparison
1338 methods that delegate to it), :meth:`assertDictEqual` and
1339 :meth:`assertMultiLineEqual`.
1340
1341 Setting ``maxDiff`` to None means that there is no maximum length of
1342 diffs.
1343
1344 .. versionadded:: 3.2
1345
1346
Benjamin Peterson52baa292009-03-24 00:56:30 +00001347 Testing frameworks can use the following methods to collect information on
1348 the test:
1349
1350
1351 .. method:: countTestCases()
1352
1353 Return the number of tests represented by this test object. For
1354 :class:`TestCase` instances, this will always be ``1``.
1355
1356
1357 .. method:: defaultTestResult()
1358
1359 Return an instance of the test result class that should be used for this
1360 test case class (if no other result instance is provided to the
1361 :meth:`run` method).
1362
1363 For :class:`TestCase` instances, this will always be an instance of
1364 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1365 as necessary.
1366
1367
1368 .. method:: id()
1369
1370 Return a string identifying the specific test case. This is usually the
1371 full name of the test method, including the module and class name.
1372
1373
1374 .. method:: shortDescription()
1375
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001376 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001377 has been provided. The default implementation of this method
1378 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001379 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001380
Georg Brandl419e3de2010-12-01 15:44:25 +00001381 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001382 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001383 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001384 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001385 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001386
Georg Brandl116aa622007-08-15 14:28:22 +00001387
Georg Brandl7f01a132009-09-16 15:58:14 +00001388 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001389
1390 Add a function to be called after :meth:`tearDown` to cleanup resources
1391 used during the test. Functions will be called in reverse order to the
1392 order they are added (LIFO). They are called with any arguments and
1393 keyword arguments passed into :meth:`addCleanup` when they are
1394 added.
1395
1396 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1397 then any cleanup functions added will still be called.
1398
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001399 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001400
1401
1402 .. method:: doCleanups()
1403
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001404 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001405 after :meth:`setUp` if :meth:`setUp` raises an exception.
1406
1407 It is responsible for calling all the cleanup functions added by
1408 :meth:`addCleanup`. If you need cleanup functions to be called
1409 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1410 yourself.
1411
1412 :meth:`doCleanups` pops methods off the stack of cleanup
1413 functions one at a time, so it can be called at any time.
1414
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001415 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001416
1417
Georg Brandl7f01a132009-09-16 15:58:14 +00001418.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001419
1420 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001421 allows the test runner to drive the test, but does not provide the methods
1422 which test code can use to check and report errors. This is used to create
1423 test cases using legacy test code, allowing it to be integrated into a
1424 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001425
1426
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001427.. _deprecated-aliases:
1428
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001429Deprecated aliases
1430##################
1431
1432For historical reasons, some of the :class:`TestCase` methods had one or more
1433aliases that are now deprecated. The following table lists the correct names
1434along with their deprecated aliases:
1435
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001436 ============================== ====================== ======================
1437 Method Name Deprecated alias Deprecated alias
1438 ============================== ====================== ======================
1439 :meth:`.assertEqual` failUnlessEqual assertEquals
1440 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1441 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001442 :meth:`.assertFalse` failIf
1443 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001444 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1445 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001446 :meth:`.assertRegex` assertRegexpMatches
1447 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001448 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001449
Ezio Melotti361467e2011-04-03 17:37:58 +03001450 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001451 the fail* aliases listed in the second column.
1452 .. deprecated:: 3.2
1453 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001454 .. deprecated:: 3.2
1455 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1456 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001457
1458
Benjamin Peterson52baa292009-03-24 00:56:30 +00001459.. _testsuite-objects:
1460
Benjamin Peterson52baa292009-03-24 00:56:30 +00001461Grouping tests
1462~~~~~~~~~~~~~~
1463
Georg Brandl7f01a132009-09-16 15:58:14 +00001464.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001465
1466 This class represents an aggregation of individual tests cases and test suites.
1467 The class presents the interface needed by the test runner to allow it to be run
1468 as any other test case. Running a :class:`TestSuite` instance is the same as
1469 iterating over the suite, running each test individually.
1470
1471 If *tests* is given, it must be an iterable of individual test cases or other
1472 test suites that will be used to build the suite initially. Additional methods
1473 are provided to add test cases and suites to the collection later on.
1474
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001475 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1476 they do not actually implement a test. Instead, they are used to aggregate
1477 tests into groups of tests that should be run together. Some additional
1478 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001479
1480
1481 .. method:: TestSuite.addTest(test)
1482
1483 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1484
1485
1486 .. method:: TestSuite.addTests(tests)
1487
1488 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1489 instances to this test suite.
1490
Benjamin Petersond2397752009-06-27 23:45:02 +00001491 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1492 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001493
1494 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1495
1496
1497 .. method:: run(result)
1498
1499 Run the tests associated with this suite, collecting the result into the
1500 test result object passed as *result*. Note that unlike
1501 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1502 be passed in.
1503
1504
1505 .. method:: debug()
1506
1507 Run the tests associated with this suite without collecting the
1508 result. This allows exceptions raised by the test to be propagated to the
1509 caller and can be used to support running tests under a debugger.
1510
1511
1512 .. method:: countTestCases()
1513
1514 Return the number of tests represented by this test object, including all
1515 individual tests and sub-suites.
1516
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001517
1518 .. method:: __iter__()
1519
1520 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1521 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
Andrew Svetloveb973682013-08-28 21:28:38 +03001522 that this method may be called several times on a single suite (for
1523 example when counting tests or comparing for equality) so the tests
1524 returned by repeated iterations before :meth:`TestSuite.run` must be the
1525 same for each call iteration. After :meth:`TestSuite.run`, callers should
1526 not rely on the tests returned by this method unless the caller uses a
1527 subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
1528 test references.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001529
Georg Brandl853947a2010-01-31 18:53:23 +00001530 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001531 In earlier versions the :class:`TestSuite` accessed tests directly rather
1532 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1533 for providing tests.
1534
Andrew Svetloveb973682013-08-28 21:28:38 +03001535 .. versionchanged:: 3.4
1536 In earlier versions the :class:`TestSuite` held references to each
1537 :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
1538 that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
1539
Benjamin Peterson52baa292009-03-24 00:56:30 +00001540 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1541 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1542
1543
Benjamin Peterson52baa292009-03-24 00:56:30 +00001544Loading and running tests
1545~~~~~~~~~~~~~~~~~~~~~~~~~
1546
Georg Brandl116aa622007-08-15 14:28:22 +00001547.. class:: TestLoader()
1548
Benjamin Peterson52baa292009-03-24 00:56:30 +00001549 The :class:`TestLoader` class is used to create test suites from classes and
1550 modules. Normally, there is no need to create an instance of this class; the
1551 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001552 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1553 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001554
1555 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001556
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001557
Benjamin Peterson52baa292009-03-24 00:56:30 +00001558 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001559
Benjamin Peterson52baa292009-03-24 00:56:30 +00001560 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1561 :class:`testCaseClass`.
1562
1563
1564 .. method:: loadTestsFromModule(module)
1565
1566 Return a suite of all tests cases contained in the given module. This
1567 method searches *module* for classes derived from :class:`TestCase` and
1568 creates an instance of the class for each test method defined for the
1569 class.
1570
Georg Brandle720c0a2009-04-27 16:20:50 +00001571 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001572
1573 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1574 convenient in sharing fixtures and helper functions, defining test
1575 methods on base classes that are not intended to be instantiated
1576 directly does not play well with this method. Doing so, however, can
1577 be useful when the fixtures are different and defined in subclasses.
1578
Benjamin Petersond2397752009-06-27 23:45:02 +00001579 If a module provides a ``load_tests`` function it will be called to
1580 load the tests. This allows modules to customize test loading.
1581 This is the `load_tests protocol`_.
1582
Georg Brandl853947a2010-01-31 18:53:23 +00001583 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001584 Support for ``load_tests`` added.
1585
Benjamin Peterson52baa292009-03-24 00:56:30 +00001586
Georg Brandl7f01a132009-09-16 15:58:14 +00001587 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001588
1589 Return a suite of all tests cases given a string specifier.
1590
1591 The specifier *name* is a "dotted name" that may resolve either to a
1592 module, a test case class, a test method within a test case class, a
1593 :class:`TestSuite` instance, or a callable object which returns a
1594 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1595 applied in the order listed here; that is, a method on a possible test
1596 case class will be picked up as "a test method within a test case class",
1597 rather than "a callable object".
1598
1599 For example, if you have a module :mod:`SampleTests` containing a
1600 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1601 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001602 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1603 return a suite which will run all three test methods. Using the specifier
1604 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1605 suite which will run only the :meth:`test_two` test method. The specifier
1606 can refer to modules and packages which have not been imported; they will
1607 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001608
1609 The method optionally resolves *name* relative to the given *module*.
1610
1611
Georg Brandl7f01a132009-09-16 15:58:14 +00001612 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001613
1614 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1615 than a single name. The return value is a test suite which supports all
1616 the tests defined for each name.
1617
1618
1619 .. method:: getTestCaseNames(testCaseClass)
1620
1621 Return a sorted sequence of method names found within *testCaseClass*;
1622 this should be a subclass of :class:`TestCase`.
1623
Benjamin Petersond2397752009-06-27 23:45:02 +00001624
1625 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1626
Larry Hastings3732ed22014-03-15 21:13:56 -07001627 Find all the test modules by recursing into subdirectories from the
1628 specified start directory, and return a TestSuite object containing them.
1629 Only test files that match *pattern* will be loaded. (Using shell style
1630 pattern matching.) Only module names that are importable (i.e. are valid
1631 Python identifiers) will be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001632
1633 All test modules must be importable from the top level of the project. If
1634 the start directory is not the top level directory then the top level
1635 directory must be specified separately.
1636
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001637 If importing a module fails, for example due to a syntax error, then this
Ezio Melottieae2b382013-03-01 14:47:50 +02001638 will be recorded as a single error and discovery will continue. If the
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001639 import failure is due to :exc:`SkipTest` being raised, it will be recorded
Ezio Melottieae2b382013-03-01 14:47:50 +02001640 as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001641
Benjamin Petersond2397752009-06-27 23:45:02 +00001642 If a test package name (directory with :file:`__init__.py`) matches the
1643 pattern then the package will be checked for a ``load_tests``
1644 function. If this exists then it will be called with *loader*, *tests*,
1645 *pattern*.
1646
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001647 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001648 ``load_tests`` is responsible for loading all tests in the package.
1649
1650 The pattern is deliberately not stored as a loader attribute so that
1651 packages can continue discovery themselves. *top_level_dir* is stored so
1652 ``load_tests`` does not need to pass this argument in to
1653 ``loader.discover()``.
1654
Benjamin Petersonb48af542010-04-11 20:43:16 +00001655 *start_dir* can be a dotted module name as well as a directory.
1656
Georg Brandl853947a2010-01-31 18:53:23 +00001657 .. versionadded:: 3.2
1658
Ezio Melottieae2b382013-03-01 14:47:50 +02001659 .. versionchanged:: 3.4
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001660 Modules that raise :exc:`SkipTest` on import are recorded as skips,
Larry Hastings3732ed22014-03-15 21:13:56 -07001661 not errors.
1662 Discovery works for :term:`namespace packages <namespace package>`.
1663 Paths are sorted before being imported so that execution order is
1664 the same even if the underlying file system's ordering is not
1665 dependent on file name.
Michael Foord80cbc9e2013-03-18 17:50:12 -07001666
Benjamin Petersond2397752009-06-27 23:45:02 +00001667
Benjamin Peterson52baa292009-03-24 00:56:30 +00001668 The following attributes of a :class:`TestLoader` can be configured either by
1669 subclassing or assignment on an instance:
1670
1671
1672 .. attribute:: testMethodPrefix
1673
1674 String giving the prefix of method names which will be interpreted as test
1675 methods. The default value is ``'test'``.
1676
1677 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1678 methods.
1679
1680
1681 .. attribute:: sortTestMethodsUsing
1682
1683 Function to be used to compare method names when sorting them in
1684 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1685
1686
1687 .. attribute:: suiteClass
1688
1689 Callable object that constructs a test suite from a list of tests. No
1690 methods on the resulting object are needed. The default value is the
1691 :class:`TestSuite` class.
1692
1693 This affects all the :meth:`loadTestsFrom\*` methods.
1694
1695
Benjamin Peterson52baa292009-03-24 00:56:30 +00001696.. class:: TestResult
1697
1698 This class is used to compile information about which tests have succeeded
1699 and which have failed.
1700
1701 A :class:`TestResult` object stores the results of a set of tests. The
1702 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1703 properly recorded; test authors do not need to worry about recording the
1704 outcome of tests.
1705
1706 Testing frameworks built on top of :mod:`unittest` may want access to the
1707 :class:`TestResult` object generated by running a set of tests for reporting
1708 purposes; a :class:`TestResult` instance is returned by the
1709 :meth:`TestRunner.run` method for this purpose.
1710
1711 :class:`TestResult` instances have the following attributes that will be of
1712 interest when inspecting the results of running a set of tests:
1713
1714
1715 .. attribute:: errors
1716
1717 A list containing 2-tuples of :class:`TestCase` instances and strings
1718 holding formatted tracebacks. Each tuple represents a test which raised an
1719 unexpected exception.
1720
Benjamin Peterson52baa292009-03-24 00:56:30 +00001721 .. attribute:: failures
1722
1723 A list containing 2-tuples of :class:`TestCase` instances and strings
1724 holding formatted tracebacks. Each tuple represents a test where a failure
Ezio Melottie2202362013-09-07 15:19:30 +03001725 was explicitly signalled using the :meth:`TestCase.assert\*` methods.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001726
Benjamin Peterson52baa292009-03-24 00:56:30 +00001727 .. attribute:: skipped
1728
1729 A list containing 2-tuples of :class:`TestCase` instances and strings
1730 holding the reason for skipping the test.
1731
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001732 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001733
1734 .. attribute:: expectedFailures
1735
Georg Brandl6faee4e2010-09-21 14:48:28 +00001736 A list containing 2-tuples of :class:`TestCase` instances and strings
1737 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001738 of the test case.
1739
1740 .. attribute:: unexpectedSuccesses
1741
1742 A list containing :class:`TestCase` instances that were marked as expected
1743 failures, but succeeded.
1744
1745 .. attribute:: shouldStop
1746
1747 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1748
1749
1750 .. attribute:: testsRun
1751
1752 The total number of tests run so far.
1753
1754
Georg Brandl12037202010-12-02 22:35:25 +00001755 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001756
1757 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1758 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1759 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1760 fails or errors. Any output is also attached to the failure / error message.
1761
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001762 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001763
1764
1765 .. attribute:: failfast
1766
1767 If set to true :meth:`stop` will be called on the first failure or error,
1768 halting the test run.
1769
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001770 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001771
1772
Benjamin Peterson52baa292009-03-24 00:56:30 +00001773 .. method:: wasSuccessful()
1774
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001775 Return ``True`` if all tests run so far have passed, otherwise returns
1776 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001777
Gregory P. Smith5a6d4bf2014-01-20 01:11:18 -08001778 .. versionchanged:: 3.4
1779 Returns ``False`` if there were any :attr:`unexpectedSuccesses`
1780 from tests marked with the :func:`expectedFailure` decorator.
1781
Benjamin Peterson52baa292009-03-24 00:56:30 +00001782
1783 .. method:: stop()
1784
1785 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001786 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001787 :class:`TestRunner` objects should respect this flag and return without
1788 running any additional tests.
1789
1790 For example, this feature is used by the :class:`TextTestRunner` class to
1791 stop the test framework when the user signals an interrupt from the
1792 keyboard. Interactive tools which provide :class:`TestRunner`
1793 implementations can use this in a similar manner.
1794
1795 The following methods of the :class:`TestResult` class are used to maintain
1796 the internal data structures, and may be extended in subclasses to support
1797 additional reporting requirements. This is particularly useful in building
1798 tools which support interactive reporting while tests are being run.
1799
1800
1801 .. method:: startTest(test)
1802
1803 Called when the test case *test* is about to be run.
1804
Benjamin Peterson52baa292009-03-24 00:56:30 +00001805 .. method:: stopTest(test)
1806
1807 Called after the test case *test* has been executed, regardless of the
1808 outcome.
1809
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001810 .. method:: startTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001811
1812 Called once before any tests are executed.
1813
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001814 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001815
1816
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001817 .. method:: stopTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001818
Ezio Melotti176d6c42010-01-27 20:58:07 +00001819 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001820
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001821 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001822
1823
Benjamin Peterson52baa292009-03-24 00:56:30 +00001824 .. method:: addError(test, err)
1825
Ezio Melottie64a91a2013-09-07 15:23:36 +03001826 Called when the test case *test* raises an unexpected exception. *err* is a
Benjamin Peterson52baa292009-03-24 00:56:30 +00001827 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1828 traceback)``.
1829
1830 The default implementation appends a tuple ``(test, formatted_err)`` to
1831 the instance's :attr:`errors` attribute, where *formatted_err* is a
1832 formatted traceback derived from *err*.
1833
1834
1835 .. method:: addFailure(test, err)
1836
Benjamin Petersond2397752009-06-27 23:45:02 +00001837 Called when the test case *test* signals a failure. *err* is a tuple of
1838 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001839
1840 The default implementation appends a tuple ``(test, formatted_err)`` to
1841 the instance's :attr:`failures` attribute, where *formatted_err* is a
1842 formatted traceback derived from *err*.
1843
1844
1845 .. method:: addSuccess(test)
1846
1847 Called when the test case *test* succeeds.
1848
1849 The default implementation does nothing.
1850
1851
1852 .. method:: addSkip(test, reason)
1853
1854 Called when the test case *test* is skipped. *reason* is the reason the
1855 test gave for skipping.
1856
1857 The default implementation appends a tuple ``(test, reason)`` to the
1858 instance's :attr:`skipped` attribute.
1859
1860
1861 .. method:: addExpectedFailure(test, err)
1862
1863 Called when the test case *test* fails, but was marked with the
1864 :func:`expectedFailure` decorator.
1865
1866 The default implementation appends a tuple ``(test, formatted_err)`` to
1867 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1868 is a formatted traceback derived from *err*.
1869
1870
1871 .. method:: addUnexpectedSuccess(test)
1872
1873 Called when the test case *test* was marked with the
1874 :func:`expectedFailure` decorator, but succeeded.
1875
1876 The default implementation appends the test to the instance's
1877 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001878
Georg Brandl67b21b72010-08-17 15:07:14 +00001879
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001880 .. method:: addSubTest(test, subtest, outcome)
1881
1882 Called when a subtest finishes. *test* is the test case
1883 corresponding to the test method. *subtest* is a custom
1884 :class:`TestCase` instance describing the subtest.
1885
1886 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
1887 it failed with an exception where *outcome* is a tuple of the form
1888 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1889
1890 The default implementation does nothing when the outcome is a
1891 success, and records subtest failures as normal failures.
1892
1893 .. versionadded:: 3.4
1894
1895
Michael Foord34c94622010-02-10 15:51:42 +00001896.. class:: TextTestResult(stream, descriptions, verbosity)
1897
Georg Brandl67b21b72010-08-17 15:07:14 +00001898 A concrete implementation of :class:`TestResult` used by the
1899 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001900
Georg Brandl67b21b72010-08-17 15:07:14 +00001901 .. versionadded:: 3.2
1902 This class was previously named ``_TextTestResult``. The old name still
1903 exists as an alias but is deprecated.
1904
Georg Brandl116aa622007-08-15 14:28:22 +00001905
1906.. data:: defaultTestLoader
1907
1908 Instance of the :class:`TestLoader` class intended to be shared. If no
1909 customization of the :class:`TestLoader` is needed, this instance can be used
1910 instead of repeatedly creating new instances.
1911
1912
Ezio Melotti9c939bc2013-05-07 09:46:30 +03001913.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \
1914 buffer=False, resultclass=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001915
Michael Foordd218e952011-01-03 12:55:11 +00001916 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001917 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001918 has a few configurable parameters, but is essentially very simple. Graphical
1919 applications which run test suites should provide alternate implementations.
1920
Ezio Melotti60901872010-12-01 00:56:10 +00001921 By default this runner shows :exc:`DeprecationWarning`,
Senthil Kumaran409ea5d2014-02-08 14:28:03 -08001922 :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and
Larry Hastingsad88d7a2014-02-10 04:26:10 -08001923 :exc:`ImportWarning` even if they are :ref:`ignored by default
1924 <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest
1925 methods <deprecated-aliases>` are also special-cased and, when the warning
1926 filters are ``'default'`` or ``'always'``, they will appear only once
1927 per-module, in order to avoid too many warning messages. This behavior can
1928 be overridden using the :option:`-Wd` or :option:`-Wa` options and leaving
1929 *warnings* to ``None``.
Ezio Melotti60901872010-12-01 00:56:10 +00001930
Michael Foordd218e952011-01-03 12:55:11 +00001931 .. versionchanged:: 3.2
1932 Added the ``warnings`` argument.
1933
1934 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001935 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001936 than import time.
1937
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001938 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001939
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001940 This method returns the instance of ``TestResult`` used by :meth:`run`.
1941 It is not intended to be called directly, but can be overridden in
1942 subclasses to provide a custom ``TestResult``.
1943
Michael Foord34c94622010-02-10 15:51:42 +00001944 ``_makeResult()`` instantiates the class or callable passed in the
1945 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001946 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001947 The result class is instantiated with the following arguments::
1948
1949 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001950
Michael Foord4d1639f2013-12-29 23:38:55 +00001951 .. method:: run(test)
1952
1953 This method is the main public interface to the `TextTestRunner`. This
1954 method takes a :class:`TestSuite` or :class:`TestCase` instance. A
1955 :class:`TestResult` is created by calling
1956 :func:`_makeResult` and the test(s) are run and the
1957 results printed to stdout.
1958
Ezio Melotti60901872010-12-01 00:56:10 +00001959
Georg Brandl419e3de2010-12-01 15:44:25 +00001960.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02001961 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00001962 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001963
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001964 A command-line program that loads a set of tests from *module* and runs them;
1965 this is primarily for making test modules conveniently executable.
1966 The simplest use for this function is to include the following line at the
1967 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00001968
1969 if __name__ == '__main__':
1970 unittest.main()
1971
Benjamin Petersond2397752009-06-27 23:45:02 +00001972 You can run tests with more detailed information by passing in the verbosity
1973 argument::
1974
1975 if __name__ == '__main__':
1976 unittest.main(verbosity=2)
1977
R David Murray6e731b02014-01-02 13:43:02 -05001978 The *defaultTest* argument is either the name of a single test or an
1979 iterable of test names to run if no test names are specified via *argv*. If
1980 not specified or ``None`` and no test names are provided via *argv*, all
1981 tests found in *module* are run.
R David Murray12e930f2014-01-02 13:37:26 -05001982
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001983 The *argv* argument can be a list of options passed to the program, with the
1984 first element being the program name. If not specified or ``None``,
1985 the values of :data:`sys.argv` are used.
1986
Georg Brandl116aa622007-08-15 14:28:22 +00001987 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001988 created instance of it. By default ``main`` calls :func:`sys.exit` with
1989 an exit code indicating success or failure of the tests run.
1990
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001991 The *testLoader* argument has to be a :class:`TestLoader` instance,
1992 and defaults to :data:`defaultTestLoader`.
1993
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001994 ``main`` supports being used from the interactive interpreter by passing in the
1995 argument ``exit=False``. This displays the result on standard output without
1996 calling :func:`sys.exit`::
1997
1998 >>> from unittest import main
1999 >>> main(module='test_module', exit=False)
2000
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002001 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00002002 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002003
Ezio Melotti60901872010-12-01 00:56:10 +00002004 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
2005 that should be used while running the tests. If it's not specified, it will
2006 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
2007 otherwise it will be set to ``'default'``.
2008
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002009 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
2010 This stores the result of the tests run as the ``result`` attribute.
2011
Éric Araujo971dc012010-12-16 03:13:05 +00002012 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002013 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00002014
Georg Brandl853947a2010-01-31 18:53:23 +00002015 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002016 The *verbosity*, *failfast*, *catchbreak*, *buffer*
2017 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00002018
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08002019 .. versionchanged:: 3.4
2020 The *defaultTest* parameter was changed to also accept an iterable of
2021 test names.
2022
Benjamin Petersond2397752009-06-27 23:45:02 +00002023
2024load_tests Protocol
2025###################
2026
Georg Brandl853947a2010-01-31 18:53:23 +00002027.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002028
Benjamin Petersond2397752009-06-27 23:45:02 +00002029Modules or packages can customize how tests are loaded from them during normal
2030test runs or test discovery by implementing a function called ``load_tests``.
2031
2032If a test module defines ``load_tests`` it will be called by
2033:meth:`TestLoader.loadTestsFromModule` with the following arguments::
2034
2035 load_tests(loader, standard_tests, None)
2036
2037It should return a :class:`TestSuite`.
2038
2039*loader* is the instance of :class:`TestLoader` doing the loading.
2040*standard_tests* are the tests that would be loaded by default from the
2041module. It is common for test modules to only want to add or remove tests
2042from the standard set of tests.
2043The third argument is used when loading packages as part of test discovery.
2044
2045A typical ``load_tests`` function that loads tests from a specific set of
2046:class:`TestCase` classes may look like::
2047
2048 test_cases = (TestCase1, TestCase2, TestCase3)
2049
2050 def load_tests(loader, tests, pattern):
2051 suite = TestSuite()
2052 for test_class in test_cases:
2053 tests = loader.loadTestsFromTestCase(test_class)
2054 suite.addTests(tests)
2055 return suite
2056
2057If discovery is started, either from the command line or by calling
2058:meth:`TestLoader.discover`, with a pattern that matches a package
2059name then the package :file:`__init__.py` will be checked for ``load_tests``.
2060
2061.. note::
2062
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02002063 The default pattern is ``'test*.py'``. This matches all Python files
2064 that start with ``'test'`` but *won't* match any test directories.
Benjamin Petersond2397752009-06-27 23:45:02 +00002065
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02002066 A pattern like ``'test*'`` will match test packages as well as
Benjamin Petersond2397752009-06-27 23:45:02 +00002067 modules.
2068
2069If the package :file:`__init__.py` defines ``load_tests`` then it will be
2070called and discovery not continued into the package. ``load_tests``
2071is called with the following arguments::
2072
2073 load_tests(loader, standard_tests, pattern)
2074
2075This should return a :class:`TestSuite` representing all the tests
2076from the package. (``standard_tests`` will only contain tests
2077collected from :file:`__init__.py`.)
2078
2079Because the pattern is passed into ``load_tests`` the package is free to
2080continue (and potentially modify) test discovery. A 'do nothing'
2081``load_tests`` function for a test package would look like::
2082
2083 def load_tests(loader, standard_tests, pattern):
2084 # top level directory cached on loader instance
2085 this_dir = os.path.dirname(__file__)
2086 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2087 standard_tests.addTests(package_tests)
2088 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002089
2090
2091Class and Module Fixtures
2092-------------------------
2093
2094Class and module level fixtures are implemented in :class:`TestSuite`. When
2095the test suite encounters a test from a new class then :meth:`tearDownClass`
2096from the previous class (if there is one) is called, followed by
2097:meth:`setUpClass` from the new class.
2098
2099Similarly if a test is from a different module from the previous test then
2100``tearDownModule`` from the previous module is run, followed by
2101``setUpModule`` from the new module.
2102
2103After all the tests have run the final ``tearDownClass`` and
2104``tearDownModule`` are run.
2105
2106Note that shared fixtures do not play well with [potential] features like test
2107parallelization and they break test isolation. They should be used with care.
2108
2109The default ordering of tests created by the unittest test loaders is to group
2110all tests from the same modules and classes together. This will lead to
2111``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2112module. If you randomize the order, so that tests from different modules and
2113classes are adjacent to each other, then these shared fixture functions may be
2114called multiple times in a single test run.
2115
2116Shared fixtures are not intended to work with suites with non-standard
2117ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2118support shared fixtures.
2119
2120If there are any exceptions raised during one of the shared fixture functions
2121the test is reported as an error. Because there is no corresponding test
2122instance an ``_ErrorHolder`` object (that has the same interface as a
2123:class:`TestCase`) is created to represent the error. If you are just using
2124the standard unittest test runner then this detail doesn't matter, but if you
2125are a framework author it may be relevant.
2126
2127
2128setUpClass and tearDownClass
2129~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2130
2131These must be implemented as class methods::
2132
2133 import unittest
2134
2135 class Test(unittest.TestCase):
2136 @classmethod
2137 def setUpClass(cls):
2138 cls._connection = createExpensiveConnectionObject()
2139
2140 @classmethod
2141 def tearDownClass(cls):
2142 cls._connection.destroy()
2143
2144If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2145then you must call up to them yourself. The implementations in
2146:class:`TestCase` are empty.
2147
2148If an exception is raised during a ``setUpClass`` then the tests in the class
2149are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002150have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002151:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002152instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002153
2154
2155setUpModule and tearDownModule
2156~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2157
2158These should be implemented as functions::
2159
2160 def setUpModule():
2161 createConnection()
2162
2163 def tearDownModule():
2164 closeConnection()
2165
2166If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002167module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002168:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002169instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002170
2171
2172Signal Handling
2173---------------
2174
Georg Brandl419e3de2010-12-01 15:44:25 +00002175.. versionadded:: 3.2
2176
Éric Araujo8acb67c2010-11-26 23:31:07 +00002177The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002178along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2179more friendly handling of control-C during a test run. With catch break
2180behavior enabled control-C will allow the currently running test to complete,
2181and the test run will then end and report all the results so far. A second
2182control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002183
Michael Foordde4ceab2010-04-25 19:53:49 +00002184The control-c handling signal handler attempts to remain compatible with code or
2185tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2186handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2187i.e. it has been replaced by the system under test and delegated to, then it
2188calls the default handler. This will normally be the expected behavior by code
2189that replaces an installed handler and delegates to it. For individual tests
2190that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2191decorator can be used.
2192
2193There are a few utility functions for framework authors to enable control-c
2194handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002195
2196.. function:: installHandler()
2197
2198 Install the control-c handler. When a :const:`signal.SIGINT` is received
2199 (usually in response to the user pressing control-c) all registered results
2200 have :meth:`~TestResult.stop` called.
2201
Michael Foord469b1f02010-04-26 23:41:26 +00002202
Benjamin Petersonb48af542010-04-11 20:43:16 +00002203.. function:: registerResult(result)
2204
2205 Register a :class:`TestResult` object for control-c handling. Registering a
2206 result stores a weak reference to it, so it doesn't prevent the result from
2207 being garbage collected.
2208
Michael Foordde4ceab2010-04-25 19:53:49 +00002209 Registering a :class:`TestResult` object has no side-effects if control-c
2210 handling is not enabled, so test frameworks can unconditionally register
2211 all results they create independently of whether or not handling is enabled.
2212
Michael Foord469b1f02010-04-26 23:41:26 +00002213
Benjamin Petersonb48af542010-04-11 20:43:16 +00002214.. function:: removeResult(result)
2215
2216 Remove a registered result. Once a result has been removed then
2217 :meth:`~TestResult.stop` will no longer be called on that result object in
2218 response to a control-c.
2219
Michael Foord469b1f02010-04-26 23:41:26 +00002220
Michael Foordde4ceab2010-04-25 19:53:49 +00002221.. function:: removeHandler(function=None)
2222
2223 When called without arguments this function removes the control-c handler
2224 if it has been installed. This function can also be used as a test decorator
2225 to temporarily remove the handler whilst the test is being executed::
2226
2227 @unittest.removeHandler
2228 def test_signal_handling(self):
2229 ...