blob: b3372f99bb528575f416af47dffcebb0f99c2078 [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
Georg Brandl116aa622007-08-15 14:28:22 +000014The Python unit testing framework, sometimes referred to as "PyUnit," is a
15Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
16turn, a Java version of Kent's Smalltalk testing framework. Each is the de
17facto standard unit testing framework for its respective language.
18
19:mod:`unittest` supports test automation, sharing of setup and shutdown code for
20tests, aggregation of tests into collections, and independence of the tests from
21the reporting framework. The :mod:`unittest` module provides classes that make
22it easy to support these qualities for a set of tests.
23
24To achieve this, :mod:`unittest` supports some important concepts:
25
26test fixture
27 A :dfn:`test fixture` represents the preparation needed to perform one or more
28 tests, and any associate cleanup actions. This may involve, for example,
29 creating temporary or proxy databases, directories, or starting a server
30 process.
31
32test case
33 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
34 response to a particular set of inputs. :mod:`unittest` provides a base class,
35 :class:`TestCase`, which may be used to create new test cases.
36
37test suite
38 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
39 used to aggregate tests that should be executed together.
40
41test runner
42 A :dfn:`test runner` is a component which orchestrates the execution of tests
43 and provides the outcome to the user. The runner may use a graphical interface,
44 a textual interface, or return a special value to indicate the results of
45 executing the tests.
46
47The test case and test fixture concepts are supported through the
48:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
49used when creating new tests, and the latter can be used when integrating
50existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson52baa292009-03-24 00:56:30 +000051fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
52:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
53and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
54can be passed to the constructor for these purposes. When the test is run, the
55fixture initialization is run first; if it succeeds, the cleanup method is run
56after the test has been executed, regardless of the outcome of the test. Each
57instance of the :class:`TestCase` will only be used to run a single test method,
58so a new fixture is created for each test.
Georg Brandl116aa622007-08-15 14:28:22 +000059
60Test suites are implemented by the :class:`TestSuite` class. This class allows
61individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson14a3dd72009-05-25 00:51:58 +000062all tests added directly to the suite and in "child" test suites are run.
Georg Brandl116aa622007-08-15 14:28:22 +000063
Benjamin Peterson52baa292009-03-24 00:56:30 +000064A test runner is an object that provides a single method,
65:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
66object as a parameter, and returns a result object. The class
67:class:`TestResult` is provided for use as the result object. :mod:`unittest`
68provides the :class:`TextTestRunner` as an example test runner which reports
69test results on the standard error stream by default. Alternate runners can be
70implemented for other environments (such as graphical environments) without any
71need to derive from a specific class.
Georg Brandl116aa622007-08-15 14:28:22 +000072
73
74.. seealso::
75
76 Module :mod:`doctest`
77 Another test-support module with a very different flavor.
78
Benjamin Petersonb48af542010-04-11 20:43:16 +000079 `unittest2: A backport of new unittest features for Python 2.4-2.6 <http://pypi.python.org/pypi/unittest2>`_
80 Many new features were added to unittest in Python 2.7, including test
81 discovery. unittest2 allows you to use these features with earlier
82 versions of Python.
83
Georg Brandl116aa622007-08-15 14:28:22 +000084 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000085 Kent Beck's original paper on testing frameworks using the pattern shared
86 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000087
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000088 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000089 Third-party unittest frameworks with a lighter-weight syntax for writing
90 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000091
Benjamin Petersonb48af542010-04-11 20:43:16 +000092 `The Python Testing Tools Taxonomy <http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy>`_
93 An extensive list of Python testing tools including functional testing
94 frameworks and mock object libraries.
Benjamin Petersond2397752009-06-27 23:45:02 +000095
Benjamin Petersonb48af542010-04-11 20:43:16 +000096 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
97 A special-interest-group for discussion of testing, and testing tools,
98 in Python.
Benjamin Petersond2397752009-06-27 23:45:02 +000099
Michael Foord90efac72011-01-03 15:39:49 +0000100 The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is
101 a GUI tool for test discovery and execution. This is intended largely for ease of use
Senthil Kumaran847c33c2012-10-27 11:04:55 -0700102 for those new to unit testing. For production environments it is
103 recommended that tests be driven by a continuous integration system such as
104 `Buildbot <http://buildbot.net/trac>`_, `Jenkins <http://jenkins-ci.org>`_
105 or `Hudson <http://hudson-ci.org/>`_.
Michael Foord90efac72011-01-03 15:39:49 +0000106
107
Georg Brandl116aa622007-08-15 14:28:22 +0000108.. _unittest-minimal-example:
109
110Basic example
111-------------
112
113The :mod:`unittest` module provides a rich set of tools for constructing and
114running tests. This section demonstrates that a small subset of the tools
115suffice to meet the needs of most users.
116
117Here is a short script to test three functions from the :mod:`random` module::
118
119 import random
120 import unittest
121
122 class TestSequenceFunctions(unittest.TestCase):
123
124 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000125 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Benjamin Peterson52baa292009-03-24 00:56:30 +0000127 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000128 # make sure the shuffled sequence does not lose any elements
129 random.shuffle(self.seq)
130 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000131 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +0000132
Benjamin Peterson847a4112010-03-14 15:04:17 +0000133 # should raise an exception for an immutable sequence
134 self.assertRaises(TypeError, random.shuffle, (1,2,3))
135
Benjamin Peterson52baa292009-03-24 00:56:30 +0000136 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000137 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000138 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Benjamin Peterson52baa292009-03-24 00:56:30 +0000140 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000141 with self.assertRaises(ValueError):
142 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000143 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000144 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146 if __name__ == '__main__':
147 unittest.main()
148
Benjamin Peterson52baa292009-03-24 00:56:30 +0000149A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000150individual tests are defined with methods whose names start with the letters
151``test``. This naming convention informs the test runner about which methods
152represent tests.
153
Benjamin Peterson52baa292009-03-24 00:56:30 +0000154The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000155expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000156:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
157These methods are used instead of the :keyword:`assert` statement so the test
158runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Benjamin Peterson52baa292009-03-24 00:56:30 +0000160When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
161method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
162defined, the test runner will invoke that method after each test. In the
163example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
164test.
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000167provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000168line, the above script produces an output that looks like this::
169
170 ...
171 ----------------------------------------------------------------------
172 Ran 3 tests in 0.000s
173
174 OK
175
176Instead of :func:`unittest.main`, there are other ways to run the tests with a
177finer level of control, less terse output, and no requirement to be run from the
178command line. For example, the last two lines may be replaced with::
179
180 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
181 unittest.TextTestRunner(verbosity=2).run(suite)
182
183Running the revised script from the interpreter or another script produces the
184following output::
185
Ezio Melottid59e44a2010-02-28 03:46:13 +0000186 test_choice (__main__.TestSequenceFunctions) ... ok
187 test_sample (__main__.TestSequenceFunctions) ... ok
188 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190 ----------------------------------------------------------------------
191 Ran 3 tests in 0.110s
192
193 OK
194
195The above examples show the most commonly used :mod:`unittest` features which
196are sufficient to meet many everyday testing needs. The remainder of the
197documentation explores the full feature set from first principles.
198
Benjamin Petersonb48af542010-04-11 20:43:16 +0000199
200.. _unittest-command-line-interface:
201
Éric Araujo76338ec2010-11-26 23:46:18 +0000202Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000203----------------------
204
205The unittest module can be used from the command line to run tests from
206modules, classes or even individual test methods::
207
208 python -m unittest test_module1 test_module2
209 python -m unittest test_module.TestClass
210 python -m unittest test_module.TestClass.test_method
211
212You can pass in a list with any combination of module names, and fully
213qualified class or method names.
214
Michael Foord37d120a2010-12-04 01:11:21 +0000215Test modules can be specified by file path as well::
216
217 python -m unittest tests/test_something.py
218
219This allows you to use the shell filename completion to specify the test module.
220The file specified must still be importable as a module. The path is converted
221to a module name by removing the '.py' and converting path separators into '.'.
222If you want to execute a test file that isn't importable as a module you should
223execute the file directly instead.
224
Benjamin Petersonb48af542010-04-11 20:43:16 +0000225You can run tests with more detail (higher verbosity) by passing in the -v flag::
226
227 python -m unittest -v test_module
228
Michael Foord086f3082010-11-21 21:28:01 +0000229When executed without arguments :ref:`unittest-test-discovery` is started::
230
231 python -m unittest
232
Éric Araujo713d3032010-11-18 16:38:46 +0000233For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000234
235 python -m unittest -h
236
Georg Brandl67b21b72010-08-17 15:07:14 +0000237.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000238 In earlier versions it was only possible to run individual test methods and
239 not modules or classes.
240
241
Éric Araujo76338ec2010-11-26 23:46:18 +0000242Command-line options
243~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000244
Éric Araujod3309df2010-11-21 03:09:17 +0000245:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000246
Éric Araujo713d3032010-11-18 16:38:46 +0000247.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000248
Éric Araujo713d3032010-11-18 16:38:46 +0000249.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000250
Éric Araujo713d3032010-11-18 16:38:46 +0000251 The standard output and standard error streams are buffered during the test
252 run. Output during a passing test is discarded. Output is echoed normally
253 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000254
Éric Araujo713d3032010-11-18 16:38:46 +0000255.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000256
Éric Araujo713d3032010-11-18 16:38:46 +0000257 Control-C during the test run waits for the current test to end and then
258 reports all the results so far. A second control-C raises the normal
259 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000260
Éric Araujo713d3032010-11-18 16:38:46 +0000261 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000262
Éric Araujo713d3032010-11-18 16:38:46 +0000263.. cmdoption:: -f, --failfast
264
265 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000266
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000267.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000268 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000269
270The command line can also be used for test discovery, for running all of the
271tests in a project or just a subset.
272
273
274.. _unittest-test-discovery:
275
276Test Discovery
277--------------
278
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000279.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000280
Ezio Melotti3d995842011-03-08 16:17:35 +0200281Unittest supports simple test discovery. In order to be compatible with test
282discovery, all of the test files must be :ref:`modules <tut-modules>` or
283:ref:`packages <tut-packages>` importable from the top-level directory of
284the project (this means that their filenames must be valid
285:ref:`identifiers <identifiers>`).
Benjamin Petersonb48af542010-04-11 20:43:16 +0000286
287Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000288used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000289
290 cd project_directory
291 python -m unittest discover
292
Michael Foord086f3082010-11-21 21:28:01 +0000293.. note::
294
295 As a shortcut, ``python -m unittest`` is the equivalent of
296 ``python -m unittest discover``. If you want to pass arguments to test
Éric Araujo941afed2011-09-01 02:47:34 +0200297 discovery the ``discover`` sub-command must be used explicitly.
Michael Foord086f3082010-11-21 21:28:01 +0000298
Benjamin Petersonb48af542010-04-11 20:43:16 +0000299The ``discover`` sub-command has the following options:
300
Éric Araujo713d3032010-11-18 16:38:46 +0000301.. program:: unittest discover
302
303.. cmdoption:: -v, --verbose
304
305 Verbose output
306
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800307.. cmdoption:: -s, --start-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000308
Éric Araujo941afed2011-09-01 02:47:34 +0200309 Directory to start discovery (``.`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000310
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800311.. cmdoption:: -p, --pattern pattern
Éric Araujo713d3032010-11-18 16:38:46 +0000312
Éric Araujo941afed2011-09-01 02:47:34 +0200313 Pattern to match test files (``test*.py`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000314
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800315.. cmdoption:: -t, --top-level-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000316
317 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000318
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000319The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
320as positional arguments in that order. The following two command lines
321are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000322
323 python -m unittest discover -s project_directory -p '*_test.py'
324 python -m unittest discover project_directory '*_test.py'
325
Michael Foord16f3e902010-05-08 15:13:42 +0000326As well as being a path it is possible to pass a package name, for example
327``myproject.subpackage.test``, as the start directory. The package name you
328supply will then be imported and its location on the filesystem will be used
329as the start directory.
330
331.. caution::
332
Senthil Kumaran916bd382010-10-15 12:55:19 +0000333 Test discovery loads tests by importing them. Once test discovery has found
334 all the test files from the start directory you specify it turns the paths
335 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000336 imported as ``foo.bar.baz``.
337
338 If you have a package installed globally and attempt test discovery on
339 a different copy of the package then the import *could* happen from the
340 wrong place. If this happens test discovery will warn you and exit.
341
342 If you supply the start directory as a package name rather than a
343 path to a directory then discover assumes that whichever location it
344 imports from is the location you intended, so you will not get the
345 warning.
346
Benjamin Petersonb48af542010-04-11 20:43:16 +0000347Test modules and packages can customize test loading and discovery by through
348the `load_tests protocol`_.
349
350
Georg Brandl116aa622007-08-15 14:28:22 +0000351.. _organizing-tests:
352
353Organizing test code
354--------------------
355
356The basic building blocks of unit testing are :dfn:`test cases` --- single
357scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000358test cases are represented by :class:`unittest.TestCase` instances.
359To make your own test cases you must write subclasses of
360:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362An instance of a :class:`TestCase`\ -derived class is an object that can
363completely run a single test method, together with optional set-up and tidy-up
364code.
365
366The testing code of a :class:`TestCase` instance should be entirely self
367contained, such that it can be run either in isolation or in arbitrary
368combination with any number of other test cases.
369
Benjamin Peterson52baa292009-03-24 00:56:30 +0000370The simplest :class:`TestCase` subclass will simply override the
371:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373 import unittest
374
375 class DefaultWidgetSizeTestCase(unittest.TestCase):
376 def runTest(self):
377 widget = Widget('The widget')
378 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
379
Sandro Tosi41b24042012-01-21 10:59:37 +0100380Note that in order to test something, we use one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000381methods provided by the :class:`TestCase` base class. If the test fails, an
382exception will be raised, and :mod:`unittest` will identify the test case as a
383:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
384helps you identify where the problem is: :dfn:`failures` are caused by incorrect
385results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
386code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388The way to run a test case will be described later. For now, note that to
389construct an instance of such a test case, we call its constructor without
390arguments::
391
392 testCase = DefaultWidgetSizeTestCase()
393
394Now, such test cases can be numerous, and their set-up can be repetitive. In
395the above case, constructing a :class:`Widget` in each of 100 Widget test case
396subclasses would mean unsightly duplication.
397
398Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000399:meth:`~TestCase.setUp`, which the testing framework will automatically call for
400us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402 import unittest
403
404 class SimpleWidgetTestCase(unittest.TestCase):
405 def setUp(self):
406 self.widget = Widget('The widget')
407
408 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
409 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000410 self.assertEqual(self.widget.size(), (50,50),
411 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000412
413 class WidgetResizeTestCase(SimpleWidgetTestCase):
414 def runTest(self):
415 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000416 self.assertEqual(self.widget.size(), (100,150),
417 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000418
Benjamin Peterson52baa292009-03-24 00:56:30 +0000419If the :meth:`~TestCase.setUp` method raises an exception while the test is
420running, the framework will consider the test to have suffered an error, and the
421:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000422
Benjamin Peterson52baa292009-03-24 00:56:30 +0000423Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
424after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426 import unittest
427
428 class SimpleWidgetTestCase(unittest.TestCase):
429 def setUp(self):
430 self.widget = Widget('The widget')
431
432 def tearDown(self):
433 self.widget.dispose()
434 self.widget = None
435
Benjamin Peterson52baa292009-03-24 00:56:30 +0000436If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
437be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439Such a working environment for the testing code is called a :dfn:`fixture`.
440
441Often, many small test cases will use the same fixture. In this case, we would
442end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
443classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000444discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
445mechanism::
446
447 import unittest
448
449 class WidgetTestCase(unittest.TestCase):
450 def setUp(self):
451 self.widget = Widget('The widget')
452
453 def tearDown(self):
454 self.widget.dispose()
455 self.widget = None
456
Ezio Melottid59e44a2010-02-28 03:46:13 +0000457 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000458 self.assertEqual(self.widget.size(), (50,50),
459 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000460
Ezio Melottid59e44a2010-02-28 03:46:13 +0000461 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000462 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000463 self.assertEqual(self.widget.size(), (100,150),
464 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Benjamin Peterson52baa292009-03-24 00:56:30 +0000466Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
467provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000468the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000469separately for each instance. When creating an instance we must specify the
470test method it is to run. We do this by passing the method name in the
471constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000472
Ezio Melottid59e44a2010-02-28 03:46:13 +0000473 defaultSizeTestCase = WidgetTestCase('test_default_size')
474 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000475
476Test case instances are grouped together according to the features they test.
477:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
478represented by :mod:`unittest`'s :class:`TestSuite` class::
479
480 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000481 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
482 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484For the ease of running tests, as we will see later, it is a good idea to
485provide in each test module a callable object that returns a pre-built test
486suite::
487
488 def suite():
489 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000490 suite.addTest(WidgetTestCase('test_default_size'))
491 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000492 return suite
493
494or even::
495
496 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000497 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499 return unittest.TestSuite(map(WidgetTestCase, tests))
500
501Since it is a common pattern to create a :class:`TestCase` subclass with many
502similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
503class that can be used to automate the process of creating a test suite and
504populating it with individual tests. For example, ::
505
506 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
507
Ezio Melottid59e44a2010-02-28 03:46:13 +0000508will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
509``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000510name prefix to identify test methods automatically.
511
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000512Note that the order in which the various test cases will be run is
513determined by sorting the test function names with respect to the
514built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516Often it is desirable to group suites of test cases together, so as to run tests
517for the whole system at once. This is easy, since :class:`TestSuite` instances
518can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
519added to a :class:`TestSuite`::
520
521 suite1 = module1.TheTestSuite()
522 suite2 = module2.TheTestSuite()
523 alltests = unittest.TestSuite([suite1, suite2])
524
525You can place the definitions of test cases and test suites in the same modules
526as the code they are to test (such as :file:`widget.py`), but there are several
527advantages to placing the test code in a separate module, such as
528:file:`test_widget.py`:
529
530* The test module can be run standalone from the command line.
531
532* The test code can more easily be separated from shipped code.
533
534* There is less temptation to change test code to fit the code it tests without
535 a good reason.
536
537* Test code should be modified much less frequently than the code it tests.
538
539* Tested code can be refactored more easily.
540
541* Tests for modules written in C must be in separate modules anyway, so why not
542 be consistent?
543
544* If the testing strategy changes, there is no need to change the source code.
545
546
547.. _legacy-unit-tests:
548
549Re-using old test code
550----------------------
551
552Some users will find that they have existing test code that they would like to
553run from :mod:`unittest`, without converting every old test function to a
554:class:`TestCase` subclass.
555
556For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
557This subclass of :class:`TestCase` can be used to wrap an existing test
558function. Set-up and tear-down functions can also be provided.
559
560Given the following test function::
561
562 def testSomething():
563 something = makeSomething()
564 assert something.name is not None
565 # ...
566
567one can create an equivalent test case instance as follows::
568
569 testcase = unittest.FunctionTestCase(testSomething)
570
571If there are additional set-up and tear-down methods that should be called as
572part of the test case's operation, they can also be provided like so::
573
574 testcase = unittest.FunctionTestCase(testSomething,
575 setUp=makeSomethingDB,
576 tearDown=deleteSomethingDB)
577
578To make migrating existing test suites easier, :mod:`unittest` supports tests
579raising :exc:`AssertionError` to indicate test failure. However, it is
580recommended that you use the explicit :meth:`TestCase.fail\*` and
581:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
582may treat :exc:`AssertionError` differently.
583
584.. note::
585
Benjamin Petersond2397752009-06-27 23:45:02 +0000586 Even though :class:`FunctionTestCase` can be used to quickly convert an
587 existing test base over to a :mod:`unittest`\ -based system, this approach is
588 not recommended. Taking the time to set up proper :class:`TestCase`
589 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000590
Benjamin Peterson52baa292009-03-24 00:56:30 +0000591In some cases, the existing tests may have been written using the :mod:`doctest`
592module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
593automatically build :class:`unittest.TestSuite` instances from the existing
594:mod:`doctest`\ -based tests.
595
Georg Brandl116aa622007-08-15 14:28:22 +0000596
Benjamin Peterson5254c042009-03-23 22:25:03 +0000597.. _unittest-skipping:
598
599Skipping tests and expected failures
600------------------------------------
601
Michael Foordf5c851a2010-02-05 21:48:03 +0000602.. versionadded:: 3.1
603
Benjamin Peterson5254c042009-03-23 22:25:03 +0000604Unittest supports skipping individual test methods and even whole classes of
605tests. In addition, it supports marking a test as a "expected failure," a test
606that is broken and will fail, but shouldn't be counted as a failure on a
607:class:`TestResult`.
608
609Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
610or one of its conditional variants.
611
Ezio Melottifed69ba2013-03-01 21:26:04 +0200612Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000613
614 class MyTestCase(unittest.TestCase):
615
616 @unittest.skip("demonstrating skipping")
617 def test_nothing(self):
618 self.fail("shouldn't happen")
619
Benjamin Petersond2397752009-06-27 23:45:02 +0000620 @unittest.skipIf(mylib.__version__ < (1, 3),
621 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000622 def test_format(self):
623 # Tests that work for only a certain version of the library.
624 pass
625
626 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
627 def test_windows_support(self):
628 # windows specific testing code
629 pass
630
Ezio Melottifed69ba2013-03-01 21:26:04 +0200631This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000632
Benjamin Petersonded31c42009-03-30 15:04:16 +0000633 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000634 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000635 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000636
637 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000638 Ran 3 tests in 0.005s
639
640 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000641
Ezio Melottifed69ba2013-03-01 21:26:04 +0200642Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000643
Sandro Tosi317075d2012-03-31 18:34:59 +0200644 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000645 class MySkippedTestCase(unittest.TestCase):
646 def test_not_run(self):
647 pass
648
Benjamin Peterson52baa292009-03-24 00:56:30 +0000649:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
650that needs to be set up is not available.
651
Benjamin Peterson5254c042009-03-23 22:25:03 +0000652Expected failures use the :func:`expectedFailure` decorator. ::
653
654 class ExpectedFailureTestCase(unittest.TestCase):
655 @unittest.expectedFailure
656 def test_fail(self):
657 self.assertEqual(1, 0, "broken")
658
659It's easy to roll your own skipping decorators by making a decorator that calls
660:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottifed69ba2013-03-01 21:26:04 +0200661the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000662
663 def skipUnlessHasattr(obj, attr):
664 if hasattr(obj, attr):
665 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200666 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000667
668The following decorators implement test skipping and expected failures:
669
Georg Brandl8a1caa22010-07-29 16:01:11 +0000670.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000671
672 Unconditionally skip the decorated test. *reason* should describe why the
673 test is being skipped.
674
Georg Brandl8a1caa22010-07-29 16:01:11 +0000675.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000676
677 Skip the decorated test if *condition* is true.
678
Georg Brandl8a1caa22010-07-29 16:01:11 +0000679.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000680
Georg Brandl6faee4e2010-09-21 14:48:28 +0000681 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000682
Georg Brandl8a1caa22010-07-29 16:01:11 +0000683.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000684
685 Mark the test as an expected failure. If the test fails when run, the test
686 is not counted as a failure.
687
Ezio Melotti265281a2013-03-27 20:11:55 +0200688.. exception:: SkipTest(reason)
689
690 This exception is raised to skip a test.
691
692 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
693 decorators instead of raising this directly.
694
Benjamin Petersonb48af542010-04-11 20:43:16 +0000695Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
696Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
697
Benjamin Peterson5254c042009-03-23 22:25:03 +0000698
Georg Brandl116aa622007-08-15 14:28:22 +0000699.. _unittest-contents:
700
701Classes and functions
702---------------------
703
Benjamin Peterson52baa292009-03-24 00:56:30 +0000704This section describes in depth the API of :mod:`unittest`.
705
706
707.. _testcase-objects:
708
709Test cases
710~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Georg Brandl7f01a132009-09-16 15:58:14 +0000712.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000713
714 Instances of the :class:`TestCase` class represent the smallest testable units
715 in the :mod:`unittest` universe. This class is intended to be used as a base
716 class, with specific tests being implemented by concrete subclasses. This class
717 implements the interface needed by the test runner to allow it to drive the
718 test, and methods that the test code can use to check for and report various
719 kinds of failure.
720
721 Each instance of :class:`TestCase` will run a single test method: the method
722 named *methodName*. If you remember, we had an earlier example that went
723 something like this::
724
725 def suite():
726 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000727 suite.addTest(WidgetTestCase('test_default_size'))
728 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000729 return suite
730
731 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
732 single test.
733
Éric Araujoec9a5f62011-09-01 05:55:26 +0200734 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +0200735 :class:`TestCase` can be instantiated successfully without providing a method
736 name. This makes it easier to experiment with :class:`TestCase` from the
Michael Foord32e1d832011-01-03 17:00:11 +0000737 interactive interpreter.
738
Benjamin Peterson52baa292009-03-24 00:56:30 +0000739 *methodName* defaults to :meth:`runTest`.
740
741 :class:`TestCase` instances provide three groups of methods: one group used
742 to run the test, another used by the test implementation to check conditions
743 and report failures, and some inquiry methods allowing information about the
744 test itself to be gathered.
745
746 Methods in the first group (running the test) are:
747
748
749 .. method:: setUp()
750
751 Method called to prepare the test fixture. This is called immediately
752 before calling the test method; any exception raised by this method will
753 be considered an error rather than a test failure. The default
754 implementation does nothing.
755
756
757 .. method:: tearDown()
758
759 Method called immediately after the test method has been called and the
760 result recorded. This is called even if the test method raised an
761 exception, so the implementation in subclasses may need to be particularly
762 careful about checking internal state. Any exception raised by this
763 method will be considered an error rather than a test failure. This
764 method will only be called if the :meth:`setUp` succeeds, regardless of
765 the outcome of the test method. The default implementation does nothing.
766
767
Benjamin Petersonb48af542010-04-11 20:43:16 +0000768 .. method:: setUpClass()
769
770 A class method called before tests in an individual class run.
771 ``setUpClass`` is called with the class as the only argument
772 and must be decorated as a :func:`classmethod`::
773
774 @classmethod
775 def setUpClass(cls):
776 ...
777
778 See `Class and Module Fixtures`_ for more details.
779
780 .. versionadded:: 3.2
781
782
783 .. method:: tearDownClass()
784
785 A class method called after tests in an individual class have run.
786 ``tearDownClass`` is called with the class as the only argument
787 and must be decorated as a :meth:`classmethod`::
788
789 @classmethod
790 def tearDownClass(cls):
791 ...
792
793 See `Class and Module Fixtures`_ for more details.
794
795 .. versionadded:: 3.2
796
797
Georg Brandl7f01a132009-09-16 15:58:14 +0000798 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000799
800 Run the test, collecting the result into the test result object passed as
Ezio Melotti75b2a5e2010-11-20 10:13:45 +0000801 *result*. If *result* is omitted or ``None``, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000802 object is created (by calling the :meth:`defaultTestResult` method) and
803 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000804
805 The same effect may be had by simply calling the :class:`TestCase`
806 instance.
807
808
Benjamin Petersone549ead2009-03-28 21:42:05 +0000809 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000810
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000811 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000812 test. See :ref:`unittest-skipping` for more information.
813
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000814 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000815
Benjamin Peterson52baa292009-03-24 00:56:30 +0000816
817 .. method:: debug()
818
819 Run the test without collecting the result. This allows exceptions raised
820 by the test to be propagated to the caller, and can be used to support
821 running tests under a debugger.
822
Ezio Melotti22170ed2010-11-20 09:57:27 +0000823 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000824
Ezio Melotti4370b302010-11-03 20:39:14 +0000825 The :class:`TestCase` class provides a number of methods to check for and
826 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000827
Ezio Melotti4370b302010-11-03 20:39:14 +0000828 +-----------------------------------------+-----------------------------+---------------+
829 | Method | Checks that | New in |
830 +=========================================+=============================+===============+
831 | :meth:`assertEqual(a, b) | ``a == b`` | |
832 | <TestCase.assertEqual>` | | |
833 +-----------------------------------------+-----------------------------+---------------+
834 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
835 | <TestCase.assertNotEqual>` | | |
836 +-----------------------------------------+-----------------------------+---------------+
837 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
838 | <TestCase.assertTrue>` | | |
839 +-----------------------------------------+-----------------------------+---------------+
840 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
841 | <TestCase.assertFalse>` | | |
842 +-----------------------------------------+-----------------------------+---------------+
843 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
844 | <TestCase.assertIs>` | | |
845 +-----------------------------------------+-----------------------------+---------------+
846 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
847 | <TestCase.assertIsNot>` | | |
848 +-----------------------------------------+-----------------------------+---------------+
849 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
850 | <TestCase.assertIsNone>` | | |
851 +-----------------------------------------+-----------------------------+---------------+
852 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
853 | <TestCase.assertIsNotNone>` | | |
854 +-----------------------------------------+-----------------------------+---------------+
855 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
856 | <TestCase.assertIn>` | | |
857 +-----------------------------------------+-----------------------------+---------------+
858 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
859 | <TestCase.assertNotIn>` | | |
860 +-----------------------------------------+-----------------------------+---------------+
861 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
862 | <TestCase.assertIsInstance>` | | |
863 +-----------------------------------------+-----------------------------+---------------+
864 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
865 | <TestCase.assertNotIsInstance>` | | |
866 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000867
Ezio Melotti22170ed2010-11-20 09:57:27 +0000868 All the assert methods (except :meth:`assertRaises`,
Ezio Melottied3a7d22010-12-01 02:32:32 +0000869 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`)
Ezio Melotti22170ed2010-11-20 09:57:27 +0000870 accept a *msg* argument that, if specified, is used as the error message on
871 failure (see also :data:`longMessage`).
Benjamin Peterson52baa292009-03-24 00:56:30 +0000872
Michael Foorde180d392011-01-28 19:51:48 +0000873 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000874
Michael Foorde180d392011-01-28 19:51:48 +0000875 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000876 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000877
Michael Foorde180d392011-01-28 19:51:48 +0000878 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000879 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200880 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000881 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000882 error message (see also the :ref:`list of type-specific methods
883 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000884
Raymond Hettinger35a88362009-04-09 00:08:24 +0000885 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200886 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000887
Michael Foord28a817e2010-02-09 00:03:57 +0000888 .. versionchanged:: 3.2
889 :meth:`assertMultiLineEqual` added as the default type equality
890 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000891
Benjamin Peterson52baa292009-03-24 00:56:30 +0000892
Michael Foorde180d392011-01-28 19:51:48 +0000893 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000894
Michael Foorde180d392011-01-28 19:51:48 +0000895 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000896 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000897
Ezio Melotti4370b302010-11-03 20:39:14 +0000898 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000899 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000900
Ezio Melotti4841fd62010-11-05 15:43:40 +0000901 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000902
Ezio Melotti4841fd62010-11-05 15:43:40 +0000903 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
904 is True`` (use ``assertIs(expr, True)`` for the latter). This method
905 should also be avoided when more specific methods are available (e.g.
906 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
907 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000908
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000909
Michael Foorde180d392011-01-28 19:51:48 +0000910 .. method:: assertIs(first, second, msg=None)
911 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000912
Michael Foorde180d392011-01-28 19:51:48 +0000913 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000914 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000915
Raymond Hettinger35a88362009-04-09 00:08:24 +0000916 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000917
918
Ezio Melotti4370b302010-11-03 20:39:14 +0000919 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000920 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000921
Ezio Melotti9794a262010-11-04 14:52:13 +0000922 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000923
Ezio Melotti4370b302010-11-03 20:39:14 +0000924 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000925
926
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000927 .. method:: assertIn(first, second, msg=None)
928 assertNotIn(first, second, msg=None)
929
Ezio Melotti4841fd62010-11-05 15:43:40 +0000930 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000931
Raymond Hettinger35a88362009-04-09 00:08:24 +0000932 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000933
934
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000935 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000936 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000937
Ezio Melotti9794a262010-11-04 14:52:13 +0000938 Test that *obj* is (or is not) an instance of *cls* (which can be a
939 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200940 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000941
Ezio Melotti4370b302010-11-03 20:39:14 +0000942 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000943
944
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000945
Ezio Melotti4370b302010-11-03 20:39:14 +0000946 It is also possible to check that exceptions and warnings are raised using
947 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000948
Ezio Melotti4370b302010-11-03 20:39:14 +0000949 +---------------------------------------------------------+--------------------------------------+------------+
950 | Method | Checks that | New in |
951 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200952 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000953 | <TestCase.assertRaises>` | | |
954 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200955 | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
956 | <TestCase.assertRaisesRegex>` | and the message matches *re* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000957 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200958 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000959 | <TestCase.assertWarns>` | | |
960 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200961 | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
962 | <TestCase.assertWarnsRegex>` | and the message matches *re* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000963 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000964
Georg Brandl7f01a132009-09-16 15:58:14 +0000965 .. method:: assertRaises(exception, callable, *args, **kwds)
Georg Brandl7f01a132009-09-16 15:58:14 +0000966 assertRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000967
968 Test that an exception is raised when *callable* is called with any
969 positional or keyword arguments that are also passed to
970 :meth:`assertRaises`. The test passes if *exception* is raised, is an
971 error if another exception is raised, or fails if no exception is raised.
972 To catch any of a group of exceptions, a tuple containing the exception
973 classes may be passed as *exception*.
974
Georg Brandl7f01a132009-09-16 15:58:14 +0000975 If only the *exception* argument is given, returns a context manager so
976 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000977
Michael Foord41531f22010-02-05 21:13:40 +0000978 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000979 do_something()
980
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000981 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000982 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000983 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000984
Georg Brandl8a1caa22010-07-29 16:01:11 +0000985 with self.assertRaises(SomeException) as cm:
986 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000987
Georg Brandl8a1caa22010-07-29 16:01:11 +0000988 the_exception = cm.exception
989 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000990
Ezio Melotti49008232010-02-08 21:57:48 +0000991 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000992 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000993
Ezio Melotti49008232010-02-08 21:57:48 +0000994 .. versionchanged:: 3.2
995 Added the :attr:`exception` attribute.
996
Benjamin Peterson52baa292009-03-24 00:56:30 +0000997
Ezio Melottied3a7d22010-12-01 02:32:32 +0000998 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
999 assertRaisesRegex(exception, regex)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001000
Ezio Melottied3a7d22010-12-01 02:32:32 +00001001 Like :meth:`assertRaises` but also tests that *regex* matches
1002 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001003 a regular expression object or a string containing a regular expression
1004 suitable for use by :func:`re.search`. Examples::
1005
Ezio Melottied3a7d22010-12-01 02:32:32 +00001006 self.assertRaisesRegex(ValueError, 'invalid literal for.*XYZ$',
1007 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001008
1009 or::
1010
Ezio Melottied3a7d22010-12-01 02:32:32 +00001011 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001012 int('XYZ')
1013
Georg Brandl419e3de2010-12-01 15:44:25 +00001014 .. versionadded:: 3.1
1015 under the name ``assertRaisesRegexp``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001016 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001017 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001018
1019
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001020 .. method:: assertWarns(warning, callable, *args, **kwds)
1021 assertWarns(warning)
1022
1023 Test that a warning is triggered when *callable* is called with any
1024 positional or keyword arguments that are also passed to
1025 :meth:`assertWarns`. The test passes if *warning* is triggered and
1026 fails if it isn't. Also, any unexpected exception is an error.
1027 To catch any of a group of warnings, a tuple containing the warning
1028 classes may be passed as *warnings*.
1029
1030 If only the *warning* argument is given, returns a context manager so
1031 that the code under test can be written inline rather than as a function::
1032
1033 with self.assertWarns(SomeWarning):
1034 do_something()
1035
1036 The context manager will store the caught warning object in its
1037 :attr:`warning` attribute, and the source line which triggered the
1038 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1039 This can be useful if the intention is to perform additional checks
1040 on the exception raised::
1041
1042 with self.assertWarns(SomeWarning) as cm:
1043 do_something()
1044
1045 self.assertIn('myfile.py', cm.filename)
1046 self.assertEqual(320, cm.lineno)
1047
1048 This method works regardless of the warning filters in place when it
1049 is called.
1050
1051 .. versionadded:: 3.2
1052
1053
Ezio Melottied3a7d22010-12-01 02:32:32 +00001054 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
1055 assertWarnsRegex(warning, regex)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001056
Ezio Melottied3a7d22010-12-01 02:32:32 +00001057 Like :meth:`assertWarns` but also tests that *regex* matches on the
1058 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001059 object or a string containing a regular expression suitable for use
1060 by :func:`re.search`. Example::
1061
Ezio Melottied3a7d22010-12-01 02:32:32 +00001062 self.assertWarnsRegex(DeprecationWarning,
1063 r'legacy_function\(\) is deprecated',
1064 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001065
1066 or::
1067
Ezio Melottied3a7d22010-12-01 02:32:32 +00001068 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001069 frobnicate('/etc/passwd')
1070
1071 .. versionadded:: 3.2
1072
1073
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001074
Ezio Melotti4370b302010-11-03 20:39:14 +00001075 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001076
Ezio Melotti4370b302010-11-03 20:39:14 +00001077 +---------------------------------------+--------------------------------+--------------+
1078 | Method | Checks that | New in |
1079 +=======================================+================================+==============+
1080 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1081 | <TestCase.assertAlmostEqual>` | | |
1082 +---------------------------------------+--------------------------------+--------------+
1083 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1084 | <TestCase.assertNotAlmostEqual>` | | |
1085 +---------------------------------------+--------------------------------+--------------+
1086 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1087 | <TestCase.assertGreater>` | | |
1088 +---------------------------------------+--------------------------------+--------------+
1089 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1090 | <TestCase.assertGreaterEqual>` | | |
1091 +---------------------------------------+--------------------------------+--------------+
1092 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1093 | <TestCase.assertLess>` | | |
1094 +---------------------------------------+--------------------------------+--------------+
1095 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1096 | <TestCase.assertLessEqual>` | | |
1097 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001098 | :meth:`assertRegex(s, re) | ``regex.search(s)`` | 3.1 |
1099 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001100 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001101 | :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 |
1102 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001103 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001104 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001105 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001106 | | regardless of their order | |
1107 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001108
1109
Michael Foorde180d392011-01-28 19:51:48 +00001110 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1111 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001112
Michael Foorde180d392011-01-28 19:51:48 +00001113 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001114 equal by computing the difference, rounding to the given number of
1115 decimal *places* (default 7), and comparing to zero. Note that these
1116 methods round the values to the given number of *decimal places* (i.e.
1117 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001118
Ezio Melotti4370b302010-11-03 20:39:14 +00001119 If *delta* is supplied instead of *places* then the difference
Michael Foorde180d392011-01-28 19:51:48 +00001120 between *first* and *second* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001121
Ezio Melotti4370b302010-11-03 20:39:14 +00001122 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001123
Ezio Melotti4370b302010-11-03 20:39:14 +00001124 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001125 :meth:`assertAlmostEqual` automatically considers almost equal objects
1126 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1127 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001128
Ezio Melotti4370b302010-11-03 20:39:14 +00001129
Michael Foorde180d392011-01-28 19:51:48 +00001130 .. method:: assertGreater(first, second, msg=None)
1131 assertGreaterEqual(first, second, msg=None)
1132 assertLess(first, second, msg=None)
1133 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001134
Michael Foorde180d392011-01-28 19:51:48 +00001135 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001136 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001137
1138 >>> self.assertGreaterEqual(3, 4)
1139 AssertionError: "3" unexpectedly not greater than or equal to "4"
1140
1141 .. versionadded:: 3.1
1142
1143
Ezio Melottied3a7d22010-12-01 02:32:32 +00001144 .. method:: assertRegex(text, regex, msg=None)
1145 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001146
Ezio Melottied3a7d22010-12-01 02:32:32 +00001147 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001148 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001149 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001150 may be a regular expression object or a string containing a regular
1151 expression suitable for use by :func:`re.search`.
1152
Georg Brandl419e3de2010-12-01 15:44:25 +00001153 .. versionadded:: 3.1
1154 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001155 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001156 The method ``assertRegexpMatches()`` has been renamed to
1157 :meth:`.assertRegex`.
1158 .. versionadded:: 3.2
1159 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001160
1161
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001162 .. method:: assertDictContainsSubset(subset, dictionary, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001163
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001164 Tests whether the key/value pairs in *dictionary* are a superset of
1165 those in *subset*. If not, an error message listing the missing keys
1166 and mismatched values is generated.
Ezio Melotti4370b302010-11-03 20:39:14 +00001167
Raymond Hettinger8ebe27f2010-12-21 19:24:26 +00001168 Note, the arguments are in the opposite order of what the method name
1169 dictates. Instead, consider using the set-methods on :ref:`dictionary
1170 views <dict-views>`, for example: ``d.keys() <= e.keys()`` or
1171 ``d.items() <= d.items()``.
1172
Ezio Melotti4370b302010-11-03 20:39:14 +00001173 .. versionadded:: 3.1
Raymond Hettinger8ebe27f2010-12-21 19:24:26 +00001174 .. deprecated:: 3.2
Ezio Melotti4370b302010-11-03 20:39:14 +00001175
1176
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001177 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001178
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001179 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001180 regardless of their order. When they don't, an error message listing the
1181 differences between the sequences will be generated.
1182
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001183 Duplicate elements are *not* ignored when comparing *first* and
1184 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001185 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001186 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001187 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001188
Ezio Melotti4370b302010-11-03 20:39:14 +00001189 .. versionadded:: 3.2
1190
Michael Foorde180d392011-01-28 19:51:48 +00001191 .. method:: assertSameElements(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001192
Michael Foorde180d392011-01-28 19:51:48 +00001193 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001194 regardless of their order. When they don't, an error message listing
1195 the differences between the sequences will be generated.
1196
Michael Foorde180d392011-01-28 19:51:48 +00001197 Duplicate elements are ignored when comparing *first* and *second*.
1198 It is the equivalent of ``assertEqual(set(first), set(second))``
Ezio Melotti4370b302010-11-03 20:39:14 +00001199 but it works with sequences of unhashable objects as well. Because
1200 duplicates are ignored, this method has been deprecated in favour of
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001201 :meth:`assertCountEqual`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001202
Ezio Melotti4370b302010-11-03 20:39:14 +00001203 .. versionadded:: 3.1
1204 .. deprecated:: 3.2
1205
1206
Ezio Melotti22170ed2010-11-20 09:57:27 +00001207 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001208
Ezio Melotti22170ed2010-11-20 09:57:27 +00001209 The :meth:`assertEqual` method dispatches the equality check for objects of
1210 the same type to different type-specific methods. These methods are already
1211 implemented for most of the built-in types, but it's also possible to
1212 register new methods using :meth:`addTypeEqualityFunc`:
1213
1214 .. method:: addTypeEqualityFunc(typeobj, function)
1215
1216 Registers a type-specific method called by :meth:`assertEqual` to check
1217 if two objects of exactly the same *typeobj* (not subclasses) compare
1218 equal. *function* must take two positional arguments and a third msg=None
1219 keyword argument just as :meth:`assertEqual` does. It must raise
1220 :data:`self.failureException(msg) <failureException>` when inequality
1221 between the first two parameters is detected -- possibly providing useful
1222 information and explaining the inequalities in details in the error
1223 message.
1224
1225 .. versionadded:: 3.1
1226
1227 The list of type-specific methods automatically used by
1228 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1229 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001230
1231 +-----------------------------------------+-----------------------------+--------------+
1232 | Method | Used to compare | New in |
1233 +=========================================+=============================+==============+
1234 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1235 | <TestCase.assertMultiLineEqual>` | | |
1236 +-----------------------------------------+-----------------------------+--------------+
1237 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1238 | <TestCase.assertSequenceEqual>` | | |
1239 +-----------------------------------------+-----------------------------+--------------+
1240 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1241 | <TestCase.assertListEqual>` | | |
1242 +-----------------------------------------+-----------------------------+--------------+
1243 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1244 | <TestCase.assertTupleEqual>` | | |
1245 +-----------------------------------------+-----------------------------+--------------+
1246 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1247 | <TestCase.assertSetEqual>` | | |
1248 +-----------------------------------------+-----------------------------+--------------+
1249 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1250 | <TestCase.assertDictEqual>` | | |
1251 +-----------------------------------------+-----------------------------+--------------+
1252
1253
1254
Michael Foorde180d392011-01-28 19:51:48 +00001255 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001256
Michael Foorde180d392011-01-28 19:51:48 +00001257 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001258 When not equal a diff of the two strings highlighting the differences
1259 will be included in the error message. This method is used by default
1260 when comparing strings with :meth:`assertEqual`.
1261
Ezio Melotti4370b302010-11-03 20:39:14 +00001262 .. versionadded:: 3.1
1263
1264
Michael Foorde180d392011-01-28 19:51:48 +00001265 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001266
1267 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001268 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001269 be raised. If the sequences are different an error message is
1270 constructed that shows the difference between the two.
1271
Ezio Melotti22170ed2010-11-20 09:57:27 +00001272 This method is not called directly by :meth:`assertEqual`, but
1273 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001274 :meth:`assertTupleEqual`.
1275
1276 .. versionadded:: 3.1
1277
1278
Michael Foorde180d392011-01-28 19:51:48 +00001279 .. method:: assertListEqual(first, second, msg=None)
1280 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001281
Ezio Melotti49ccd512012-08-29 17:50:42 +03001282 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001283 constructed that shows only the differences between the two. An error
1284 is also raised if either of the parameters are of the wrong type.
1285 These methods are used by default when comparing lists or tuples with
1286 :meth:`assertEqual`.
1287
Ezio Melotti4370b302010-11-03 20:39:14 +00001288 .. versionadded:: 3.1
1289
1290
Michael Foorde180d392011-01-28 19:51:48 +00001291 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001292
1293 Tests that two sets are equal. If not, an error message is constructed
1294 that lists the differences between the sets. This method is used by
1295 default when comparing sets or frozensets with :meth:`assertEqual`.
1296
Michael Foorde180d392011-01-28 19:51:48 +00001297 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001298 method.
1299
Ezio Melotti4370b302010-11-03 20:39:14 +00001300 .. versionadded:: 3.1
1301
1302
Michael Foorde180d392011-01-28 19:51:48 +00001303 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001304
1305 Test that two dictionaries are equal. If not, an error message is
1306 constructed that shows the differences in the dictionaries. This
1307 method will be used by default to compare dictionaries in
1308 calls to :meth:`assertEqual`.
1309
Ezio Melotti4370b302010-11-03 20:39:14 +00001310 .. versionadded:: 3.1
1311
1312
1313
Ezio Melotti22170ed2010-11-20 09:57:27 +00001314 .. _other-methods-and-attrs:
1315
Ezio Melotti4370b302010-11-03 20:39:14 +00001316 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001317
Benjamin Peterson52baa292009-03-24 00:56:30 +00001318
Georg Brandl7f01a132009-09-16 15:58:14 +00001319 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001320
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001321 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001322 the error message.
1323
1324
1325 .. attribute:: failureException
1326
1327 This class attribute gives the exception raised by the test method. If a
1328 test framework needs to use a specialized exception, possibly to carry
1329 additional information, it must subclass this exception in order to "play
1330 fair" with the framework. The initial value of this attribute is
1331 :exc:`AssertionError`.
1332
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001333
1334 .. attribute:: longMessage
1335
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001336 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001337 :ref:`assert methods <assert-methods>` will be appended to the end of the
1338 normal failure message. The normal messages contain useful information
1339 about the objects involved, for example the message from assertEqual
1340 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001341 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001342 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001343
Michael Foord5074df62010-12-03 00:53:09 +00001344 This attribute defaults to ``True``. If set to False then a custom message
1345 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001346
1347 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001348 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001349
Raymond Hettinger35a88362009-04-09 00:08:24 +00001350 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001351
1352
Michael Foord98b3e762010-06-05 21:59:55 +00001353 .. attribute:: maxDiff
1354
1355 This attribute controls the maximum length of diffs output by assert
1356 methods that report diffs on failure. It defaults to 80*8 characters.
1357 Assert methods affected by this attribute are
1358 :meth:`assertSequenceEqual` (including all the sequence comparison
1359 methods that delegate to it), :meth:`assertDictEqual` and
1360 :meth:`assertMultiLineEqual`.
1361
1362 Setting ``maxDiff`` to None means that there is no maximum length of
1363 diffs.
1364
1365 .. versionadded:: 3.2
1366
1367
Benjamin Peterson52baa292009-03-24 00:56:30 +00001368 Testing frameworks can use the following methods to collect information on
1369 the test:
1370
1371
1372 .. method:: countTestCases()
1373
1374 Return the number of tests represented by this test object. For
1375 :class:`TestCase` instances, this will always be ``1``.
1376
1377
1378 .. method:: defaultTestResult()
1379
1380 Return an instance of the test result class that should be used for this
1381 test case class (if no other result instance is provided to the
1382 :meth:`run` method).
1383
1384 For :class:`TestCase` instances, this will always be an instance of
1385 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1386 as necessary.
1387
1388
1389 .. method:: id()
1390
1391 Return a string identifying the specific test case. This is usually the
1392 full name of the test method, including the module and class name.
1393
1394
1395 .. method:: shortDescription()
1396
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001397 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001398 has been provided. The default implementation of this method
1399 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001400 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001401
Georg Brandl419e3de2010-12-01 15:44:25 +00001402 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001403 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001404 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001405 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001406 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001407
Georg Brandl116aa622007-08-15 14:28:22 +00001408
Georg Brandl7f01a132009-09-16 15:58:14 +00001409 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001410
1411 Add a function to be called after :meth:`tearDown` to cleanup resources
1412 used during the test. Functions will be called in reverse order to the
1413 order they are added (LIFO). They are called with any arguments and
1414 keyword arguments passed into :meth:`addCleanup` when they are
1415 added.
1416
1417 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1418 then any cleanup functions added will still be called.
1419
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001420 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001421
1422
1423 .. method:: doCleanups()
1424
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001425 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001426 after :meth:`setUp` if :meth:`setUp` raises an exception.
1427
1428 It is responsible for calling all the cleanup functions added by
1429 :meth:`addCleanup`. If you need cleanup functions to be called
1430 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1431 yourself.
1432
1433 :meth:`doCleanups` pops methods off the stack of cleanup
1434 functions one at a time, so it can be called at any time.
1435
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001436 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001437
1438
Georg Brandl7f01a132009-09-16 15:58:14 +00001439.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001440
1441 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001442 allows the test runner to drive the test, but does not provide the methods
1443 which test code can use to check and report errors. This is used to create
1444 test cases using legacy test code, allowing it to be integrated into a
1445 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001446
1447
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001448.. _deprecated-aliases:
1449
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001450Deprecated aliases
1451##################
1452
1453For historical reasons, some of the :class:`TestCase` methods had one or more
1454aliases that are now deprecated. The following table lists the correct names
1455along with their deprecated aliases:
1456
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001457 ============================== ====================== ======================
1458 Method Name Deprecated alias Deprecated alias
1459 ============================== ====================== ======================
1460 :meth:`.assertEqual` failUnlessEqual assertEquals
1461 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1462 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001463 :meth:`.assertFalse` failIf
1464 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001465 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1466 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001467 :meth:`.assertRegex` assertRegexpMatches
1468 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001469 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001470
Ezio Melotti361467e2011-04-03 17:37:58 +03001471 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001472 the fail* aliases listed in the second column.
1473 .. deprecated:: 3.2
1474 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001475 .. deprecated:: 3.2
1476 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1477 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001478
1479
Benjamin Peterson52baa292009-03-24 00:56:30 +00001480.. _testsuite-objects:
1481
Benjamin Peterson52baa292009-03-24 00:56:30 +00001482Grouping tests
1483~~~~~~~~~~~~~~
1484
Georg Brandl7f01a132009-09-16 15:58:14 +00001485.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001486
1487 This class represents an aggregation of individual tests cases and test suites.
1488 The class presents the interface needed by the test runner to allow it to be run
1489 as any other test case. Running a :class:`TestSuite` instance is the same as
1490 iterating over the suite, running each test individually.
1491
1492 If *tests* is given, it must be an iterable of individual test cases or other
1493 test suites that will be used to build the suite initially. Additional methods
1494 are provided to add test cases and suites to the collection later on.
1495
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001496 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1497 they do not actually implement a test. Instead, they are used to aggregate
1498 tests into groups of tests that should be run together. Some additional
1499 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001500
1501
1502 .. method:: TestSuite.addTest(test)
1503
1504 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1505
1506
1507 .. method:: TestSuite.addTests(tests)
1508
1509 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1510 instances to this test suite.
1511
Benjamin Petersond2397752009-06-27 23:45:02 +00001512 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1513 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001514
1515 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1516
1517
1518 .. method:: run(result)
1519
1520 Run the tests associated with this suite, collecting the result into the
1521 test result object passed as *result*. Note that unlike
1522 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1523 be passed in.
1524
1525
1526 .. method:: debug()
1527
1528 Run the tests associated with this suite without collecting the
1529 result. This allows exceptions raised by the test to be propagated to the
1530 caller and can be used to support running tests under a debugger.
1531
1532
1533 .. method:: countTestCases()
1534
1535 Return the number of tests represented by this test object, including all
1536 individual tests and sub-suites.
1537
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001538
1539 .. method:: __iter__()
1540
1541 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1542 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1543 that this method maybe called several times on a single suite
1544 (for example when counting tests or comparing for equality)
1545 so the tests returned must be the same for repeated iterations.
1546
Georg Brandl853947a2010-01-31 18:53:23 +00001547 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001548 In earlier versions the :class:`TestSuite` accessed tests directly rather
1549 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1550 for providing tests.
1551
Benjamin Peterson52baa292009-03-24 00:56:30 +00001552 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1553 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1554
1555
Benjamin Peterson52baa292009-03-24 00:56:30 +00001556Loading and running tests
1557~~~~~~~~~~~~~~~~~~~~~~~~~
1558
Georg Brandl116aa622007-08-15 14:28:22 +00001559.. class:: TestLoader()
1560
Benjamin Peterson52baa292009-03-24 00:56:30 +00001561 The :class:`TestLoader` class is used to create test suites from classes and
1562 modules. Normally, there is no need to create an instance of this class; the
1563 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001564 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1565 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001566
1567 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001568
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001569
Benjamin Peterson52baa292009-03-24 00:56:30 +00001570 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001571
Benjamin Peterson52baa292009-03-24 00:56:30 +00001572 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1573 :class:`testCaseClass`.
1574
1575
1576 .. method:: loadTestsFromModule(module)
1577
1578 Return a suite of all tests cases contained in the given module. This
1579 method searches *module* for classes derived from :class:`TestCase` and
1580 creates an instance of the class for each test method defined for the
1581 class.
1582
Georg Brandle720c0a2009-04-27 16:20:50 +00001583 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001584
1585 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1586 convenient in sharing fixtures and helper functions, defining test
1587 methods on base classes that are not intended to be instantiated
1588 directly does not play well with this method. Doing so, however, can
1589 be useful when the fixtures are different and defined in subclasses.
1590
Benjamin Petersond2397752009-06-27 23:45:02 +00001591 If a module provides a ``load_tests`` function it will be called to
1592 load the tests. This allows modules to customize test loading.
1593 This is the `load_tests protocol`_.
1594
Georg Brandl853947a2010-01-31 18:53:23 +00001595 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001596 Support for ``load_tests`` added.
1597
Benjamin Peterson52baa292009-03-24 00:56:30 +00001598
Georg Brandl7f01a132009-09-16 15:58:14 +00001599 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001600
1601 Return a suite of all tests cases given a string specifier.
1602
1603 The specifier *name* is a "dotted name" that may resolve either to a
1604 module, a test case class, a test method within a test case class, a
1605 :class:`TestSuite` instance, or a callable object which returns a
1606 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1607 applied in the order listed here; that is, a method on a possible test
1608 case class will be picked up as "a test method within a test case class",
1609 rather than "a callable object".
1610
1611 For example, if you have a module :mod:`SampleTests` containing a
1612 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1613 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001614 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1615 return a suite which will run all three test methods. Using the specifier
1616 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1617 suite which will run only the :meth:`test_two` test method. The specifier
1618 can refer to modules and packages which have not been imported; they will
1619 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001620
1621 The method optionally resolves *name* relative to the given *module*.
1622
1623
Georg Brandl7f01a132009-09-16 15:58:14 +00001624 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001625
1626 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1627 than a single name. The return value is a test suite which supports all
1628 the tests defined for each name.
1629
1630
1631 .. method:: getTestCaseNames(testCaseClass)
1632
1633 Return a sorted sequence of method names found within *testCaseClass*;
1634 this should be a subclass of :class:`TestCase`.
1635
Benjamin Petersond2397752009-06-27 23:45:02 +00001636
1637 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1638
1639 Find and return all test modules from the specified start directory,
1640 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001641 *pattern* will be loaded. (Using shell style pattern matching.) Only
1642 module names that are importable (i.e. are valid Python identifiers) will
1643 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001644
1645 All test modules must be importable from the top level of the project. If
1646 the start directory is not the top level directory then the top level
1647 directory must be specified separately.
1648
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001649 If importing a module fails, for example due to a syntax error, then this
1650 will be recorded as a single error and discovery will continue.
1651
Benjamin Petersond2397752009-06-27 23:45:02 +00001652 If a test package name (directory with :file:`__init__.py`) matches the
1653 pattern then the package will be checked for a ``load_tests``
1654 function. If this exists then it will be called with *loader*, *tests*,
1655 *pattern*.
1656
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001657 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001658 ``load_tests`` is responsible for loading all tests in the package.
1659
1660 The pattern is deliberately not stored as a loader attribute so that
1661 packages can continue discovery themselves. *top_level_dir* is stored so
1662 ``load_tests`` does not need to pass this argument in to
1663 ``loader.discover()``.
1664
Benjamin Petersonb48af542010-04-11 20:43:16 +00001665 *start_dir* can be a dotted module name as well as a directory.
1666
Georg Brandl853947a2010-01-31 18:53:23 +00001667 .. versionadded:: 3.2
1668
Benjamin Petersond2397752009-06-27 23:45:02 +00001669
Benjamin Peterson52baa292009-03-24 00:56:30 +00001670 The following attributes of a :class:`TestLoader` can be configured either by
1671 subclassing or assignment on an instance:
1672
1673
1674 .. attribute:: testMethodPrefix
1675
1676 String giving the prefix of method names which will be interpreted as test
1677 methods. The default value is ``'test'``.
1678
1679 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1680 methods.
1681
1682
1683 .. attribute:: sortTestMethodsUsing
1684
1685 Function to be used to compare method names when sorting them in
1686 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1687
1688
1689 .. attribute:: suiteClass
1690
1691 Callable object that constructs a test suite from a list of tests. No
1692 methods on the resulting object are needed. The default value is the
1693 :class:`TestSuite` class.
1694
1695 This affects all the :meth:`loadTestsFrom\*` methods.
1696
1697
Benjamin Peterson52baa292009-03-24 00:56:30 +00001698.. class:: TestResult
1699
1700 This class is used to compile information about which tests have succeeded
1701 and which have failed.
1702
1703 A :class:`TestResult` object stores the results of a set of tests. The
1704 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1705 properly recorded; test authors do not need to worry about recording the
1706 outcome of tests.
1707
1708 Testing frameworks built on top of :mod:`unittest` may want access to the
1709 :class:`TestResult` object generated by running a set of tests for reporting
1710 purposes; a :class:`TestResult` instance is returned by the
1711 :meth:`TestRunner.run` method for this purpose.
1712
1713 :class:`TestResult` instances have the following attributes that will be of
1714 interest when inspecting the results of running a set of tests:
1715
1716
1717 .. attribute:: errors
1718
1719 A list containing 2-tuples of :class:`TestCase` instances and strings
1720 holding formatted tracebacks. Each tuple represents a test which raised an
1721 unexpected exception.
1722
Benjamin Peterson52baa292009-03-24 00:56:30 +00001723 .. attribute:: failures
1724
1725 A list containing 2-tuples of :class:`TestCase` instances and strings
1726 holding formatted tracebacks. Each tuple represents a test where a failure
1727 was explicitly signalled using the :meth:`TestCase.fail\*` or
1728 :meth:`TestCase.assert\*` methods.
1729
Benjamin Peterson52baa292009-03-24 00:56:30 +00001730 .. attribute:: skipped
1731
1732 A list containing 2-tuples of :class:`TestCase` instances and strings
1733 holding the reason for skipping the test.
1734
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001735 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001736
1737 .. attribute:: expectedFailures
1738
Georg Brandl6faee4e2010-09-21 14:48:28 +00001739 A list containing 2-tuples of :class:`TestCase` instances and strings
1740 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001741 of the test case.
1742
1743 .. attribute:: unexpectedSuccesses
1744
1745 A list containing :class:`TestCase` instances that were marked as expected
1746 failures, but succeeded.
1747
1748 .. attribute:: shouldStop
1749
1750 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1751
1752
1753 .. attribute:: testsRun
1754
1755 The total number of tests run so far.
1756
1757
Georg Brandl12037202010-12-02 22:35:25 +00001758 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001759
1760 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1761 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1762 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1763 fails or errors. Any output is also attached to the failure / error message.
1764
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001765 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001766
1767
1768 .. attribute:: failfast
1769
1770 If set to true :meth:`stop` will be called on the first failure or error,
1771 halting the test run.
1772
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001773 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001774
1775
Benjamin Peterson52baa292009-03-24 00:56:30 +00001776 .. method:: wasSuccessful()
1777
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001778 Return ``True`` if all tests run so far have passed, otherwise returns
1779 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001780
1781
1782 .. method:: stop()
1783
1784 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001785 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001786 :class:`TestRunner` objects should respect this flag and return without
1787 running any additional tests.
1788
1789 For example, this feature is used by the :class:`TextTestRunner` class to
1790 stop the test framework when the user signals an interrupt from the
1791 keyboard. Interactive tools which provide :class:`TestRunner`
1792 implementations can use this in a similar manner.
1793
1794 The following methods of the :class:`TestResult` class are used to maintain
1795 the internal data structures, and may be extended in subclasses to support
1796 additional reporting requirements. This is particularly useful in building
1797 tools which support interactive reporting while tests are being run.
1798
1799
1800 .. method:: startTest(test)
1801
1802 Called when the test case *test* is about to be run.
1803
Benjamin Peterson52baa292009-03-24 00:56:30 +00001804 .. method:: stopTest(test)
1805
1806 Called after the test case *test* has been executed, regardless of the
1807 outcome.
1808
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001809 .. method:: startTestRun(test)
1810
1811 Called once before any tests are executed.
1812
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001813 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001814
1815
1816 .. method:: stopTestRun(test)
1817
Ezio Melotti176d6c42010-01-27 20:58:07 +00001818 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001819
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001820 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001821
1822
Benjamin Peterson52baa292009-03-24 00:56:30 +00001823 .. method:: addError(test, err)
1824
1825 Called when the test case *test* raises an unexpected exception *err* is a
1826 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1827 traceback)``.
1828
1829 The default implementation appends a tuple ``(test, formatted_err)`` to
1830 the instance's :attr:`errors` attribute, where *formatted_err* is a
1831 formatted traceback derived from *err*.
1832
1833
1834 .. method:: addFailure(test, err)
1835
Benjamin Petersond2397752009-06-27 23:45:02 +00001836 Called when the test case *test* signals a failure. *err* is a tuple of
1837 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001838
1839 The default implementation appends a tuple ``(test, formatted_err)`` to
1840 the instance's :attr:`failures` attribute, where *formatted_err* is a
1841 formatted traceback derived from *err*.
1842
1843
1844 .. method:: addSuccess(test)
1845
1846 Called when the test case *test* succeeds.
1847
1848 The default implementation does nothing.
1849
1850
1851 .. method:: addSkip(test, reason)
1852
1853 Called when the test case *test* is skipped. *reason* is the reason the
1854 test gave for skipping.
1855
1856 The default implementation appends a tuple ``(test, reason)`` to the
1857 instance's :attr:`skipped` attribute.
1858
1859
1860 .. method:: addExpectedFailure(test, err)
1861
1862 Called when the test case *test* fails, but was marked with the
1863 :func:`expectedFailure` decorator.
1864
1865 The default implementation appends a tuple ``(test, formatted_err)`` to
1866 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1867 is a formatted traceback derived from *err*.
1868
1869
1870 .. method:: addUnexpectedSuccess(test)
1871
1872 Called when the test case *test* was marked with the
1873 :func:`expectedFailure` decorator, but succeeded.
1874
1875 The default implementation appends the test to the instance's
1876 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001877
Georg Brandl67b21b72010-08-17 15:07:14 +00001878
Michael Foord34c94622010-02-10 15:51:42 +00001879.. class:: TextTestResult(stream, descriptions, verbosity)
1880
Georg Brandl67b21b72010-08-17 15:07:14 +00001881 A concrete implementation of :class:`TestResult` used by the
1882 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001883
Georg Brandl67b21b72010-08-17 15:07:14 +00001884 .. versionadded:: 3.2
1885 This class was previously named ``_TextTestResult``. The old name still
1886 exists as an alias but is deprecated.
1887
Georg Brandl116aa622007-08-15 14:28:22 +00001888
1889.. data:: defaultTestLoader
1890
1891 Instance of the :class:`TestLoader` class intended to be shared. If no
1892 customization of the :class:`TestLoader` is needed, this instance can be used
1893 instead of repeatedly creating new instances.
1894
1895
Michael Foordd218e952011-01-03 12:55:11 +00001896.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, runnerclass=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001897
Michael Foordd218e952011-01-03 12:55:11 +00001898 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001899 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001900 has a few configurable parameters, but is essentially very simple. Graphical
1901 applications which run test suites should provide alternate implementations.
1902
Ezio Melotti60901872010-12-01 00:56:10 +00001903 By default this runner shows :exc:`DeprecationWarning`,
1904 :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` even if they are
1905 :ref:`ignored by default <warning-ignored>`. Deprecation warnings caused by
1906 :ref:`deprecated unittest methods <deprecated-aliases>` are also
1907 special-cased and, when the warning filters are ``'default'`` or ``'always'``,
1908 they will appear only once per-module, in order to avoid too many warning
Georg Brandl46402372010-12-04 19:06:18 +00001909 messages. This behavior can be overridden using the :option:`-Wd` or
Ezio Melotti60901872010-12-01 00:56:10 +00001910 :option:`-Wa` options and leaving *warnings* to ``None``.
1911
Michael Foordd218e952011-01-03 12:55:11 +00001912 .. versionchanged:: 3.2
1913 Added the ``warnings`` argument.
1914
1915 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001916 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001917 than import time.
1918
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001919 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001920
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001921 This method returns the instance of ``TestResult`` used by :meth:`run`.
1922 It is not intended to be called directly, but can be overridden in
1923 subclasses to provide a custom ``TestResult``.
1924
Michael Foord34c94622010-02-10 15:51:42 +00001925 ``_makeResult()`` instantiates the class or callable passed in the
1926 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001927 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001928 The result class is instantiated with the following arguments::
1929
1930 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001931
Ezio Melotti60901872010-12-01 00:56:10 +00001932
Georg Brandl419e3de2010-12-01 15:44:25 +00001933.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02001934 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00001935 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001936
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001937 A command-line program that loads a set of tests from *module* and runs them;
1938 this is primarily for making test modules conveniently executable.
1939 The simplest use for this function is to include the following line at the
1940 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00001941
1942 if __name__ == '__main__':
1943 unittest.main()
1944
Benjamin Petersond2397752009-06-27 23:45:02 +00001945 You can run tests with more detailed information by passing in the verbosity
1946 argument::
1947
1948 if __name__ == '__main__':
1949 unittest.main(verbosity=2)
1950
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001951 The *argv* argument can be a list of options passed to the program, with the
1952 first element being the program name. If not specified or ``None``,
1953 the values of :data:`sys.argv` are used.
1954
Georg Brandl116aa622007-08-15 14:28:22 +00001955 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001956 created instance of it. By default ``main`` calls :func:`sys.exit` with
1957 an exit code indicating success or failure of the tests run.
1958
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001959 The *testLoader* argument has to be a :class:`TestLoader` instance,
1960 and defaults to :data:`defaultTestLoader`.
1961
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001962 ``main`` supports being used from the interactive interpreter by passing in the
1963 argument ``exit=False``. This displays the result on standard output without
1964 calling :func:`sys.exit`::
1965
1966 >>> from unittest import main
1967 >>> main(module='test_module', exit=False)
1968
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001969 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00001970 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001971
Ezio Melotti60901872010-12-01 00:56:10 +00001972 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
1973 that should be used while running the tests. If it's not specified, it will
1974 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
1975 otherwise it will be set to ``'default'``.
1976
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001977 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1978 This stores the result of the tests run as the ``result`` attribute.
1979
Éric Araujo971dc012010-12-16 03:13:05 +00001980 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001981 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00001982
Georg Brandl853947a2010-01-31 18:53:23 +00001983 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001984 The *verbosity*, *failfast*, *catchbreak*, *buffer*
1985 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001986
1987
1988load_tests Protocol
1989###################
1990
Georg Brandl853947a2010-01-31 18:53:23 +00001991.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001992
Benjamin Petersond2397752009-06-27 23:45:02 +00001993Modules or packages can customize how tests are loaded from them during normal
1994test runs or test discovery by implementing a function called ``load_tests``.
1995
1996If a test module defines ``load_tests`` it will be called by
1997:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1998
1999 load_tests(loader, standard_tests, None)
2000
2001It should return a :class:`TestSuite`.
2002
2003*loader* is the instance of :class:`TestLoader` doing the loading.
2004*standard_tests* are the tests that would be loaded by default from the
2005module. It is common for test modules to only want to add or remove tests
2006from the standard set of tests.
2007The third argument is used when loading packages as part of test discovery.
2008
2009A typical ``load_tests`` function that loads tests from a specific set of
2010:class:`TestCase` classes may look like::
2011
2012 test_cases = (TestCase1, TestCase2, TestCase3)
2013
2014 def load_tests(loader, tests, pattern):
2015 suite = TestSuite()
2016 for test_class in test_cases:
2017 tests = loader.loadTestsFromTestCase(test_class)
2018 suite.addTests(tests)
2019 return suite
2020
2021If discovery is started, either from the command line or by calling
2022:meth:`TestLoader.discover`, with a pattern that matches a package
2023name then the package :file:`__init__.py` will be checked for ``load_tests``.
2024
2025.. note::
2026
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02002027 The default pattern is ``'test*.py'``. This matches all Python files
2028 that start with ``'test'`` but *won't* match any test directories.
Benjamin Petersond2397752009-06-27 23:45:02 +00002029
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02002030 A pattern like ``'test*'`` will match test packages as well as
Benjamin Petersond2397752009-06-27 23:45:02 +00002031 modules.
2032
2033If the package :file:`__init__.py` defines ``load_tests`` then it will be
2034called and discovery not continued into the package. ``load_tests``
2035is called with the following arguments::
2036
2037 load_tests(loader, standard_tests, pattern)
2038
2039This should return a :class:`TestSuite` representing all the tests
2040from the package. (``standard_tests`` will only contain tests
2041collected from :file:`__init__.py`.)
2042
2043Because the pattern is passed into ``load_tests`` the package is free to
2044continue (and potentially modify) test discovery. A 'do nothing'
2045``load_tests`` function for a test package would look like::
2046
2047 def load_tests(loader, standard_tests, pattern):
2048 # top level directory cached on loader instance
2049 this_dir = os.path.dirname(__file__)
2050 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2051 standard_tests.addTests(package_tests)
2052 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002053
2054
2055Class and Module Fixtures
2056-------------------------
2057
2058Class and module level fixtures are implemented in :class:`TestSuite`. When
2059the test suite encounters a test from a new class then :meth:`tearDownClass`
2060from the previous class (if there is one) is called, followed by
2061:meth:`setUpClass` from the new class.
2062
2063Similarly if a test is from a different module from the previous test then
2064``tearDownModule`` from the previous module is run, followed by
2065``setUpModule`` from the new module.
2066
2067After all the tests have run the final ``tearDownClass`` and
2068``tearDownModule`` are run.
2069
2070Note that shared fixtures do not play well with [potential] features like test
2071parallelization and they break test isolation. They should be used with care.
2072
2073The default ordering of tests created by the unittest test loaders is to group
2074all tests from the same modules and classes together. This will lead to
2075``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2076module. If you randomize the order, so that tests from different modules and
2077classes are adjacent to each other, then these shared fixture functions may be
2078called multiple times in a single test run.
2079
2080Shared fixtures are not intended to work with suites with non-standard
2081ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2082support shared fixtures.
2083
2084If there are any exceptions raised during one of the shared fixture functions
2085the test is reported as an error. Because there is no corresponding test
2086instance an ``_ErrorHolder`` object (that has the same interface as a
2087:class:`TestCase`) is created to represent the error. If you are just using
2088the standard unittest test runner then this detail doesn't matter, but if you
2089are a framework author it may be relevant.
2090
2091
2092setUpClass and tearDownClass
2093~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2094
2095These must be implemented as class methods::
2096
2097 import unittest
2098
2099 class Test(unittest.TestCase):
2100 @classmethod
2101 def setUpClass(cls):
2102 cls._connection = createExpensiveConnectionObject()
2103
2104 @classmethod
2105 def tearDownClass(cls):
2106 cls._connection.destroy()
2107
2108If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2109then you must call up to them yourself. The implementations in
2110:class:`TestCase` are empty.
2111
2112If an exception is raised during a ``setUpClass`` then the tests in the class
2113are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002114have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002115:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002116instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002117
2118
2119setUpModule and tearDownModule
2120~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2121
2122These should be implemented as functions::
2123
2124 def setUpModule():
2125 createConnection()
2126
2127 def tearDownModule():
2128 closeConnection()
2129
2130If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002131module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002132:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002133instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002134
2135
2136Signal Handling
2137---------------
2138
Georg Brandl419e3de2010-12-01 15:44:25 +00002139.. versionadded:: 3.2
2140
Éric Araujo8acb67c2010-11-26 23:31:07 +00002141The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002142along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2143more friendly handling of control-C during a test run. With catch break
2144behavior enabled control-C will allow the currently running test to complete,
2145and the test run will then end and report all the results so far. A second
2146control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002147
Michael Foordde4ceab2010-04-25 19:53:49 +00002148The control-c handling signal handler attempts to remain compatible with code or
2149tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2150handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2151i.e. it has been replaced by the system under test and delegated to, then it
2152calls the default handler. This will normally be the expected behavior by code
2153that replaces an installed handler and delegates to it. For individual tests
2154that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2155decorator can be used.
2156
2157There are a few utility functions for framework authors to enable control-c
2158handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002159
2160.. function:: installHandler()
2161
2162 Install the control-c handler. When a :const:`signal.SIGINT` is received
2163 (usually in response to the user pressing control-c) all registered results
2164 have :meth:`~TestResult.stop` called.
2165
Michael Foord469b1f02010-04-26 23:41:26 +00002166
Benjamin Petersonb48af542010-04-11 20:43:16 +00002167.. function:: registerResult(result)
2168
2169 Register a :class:`TestResult` object for control-c handling. Registering a
2170 result stores a weak reference to it, so it doesn't prevent the result from
2171 being garbage collected.
2172
Michael Foordde4ceab2010-04-25 19:53:49 +00002173 Registering a :class:`TestResult` object has no side-effects if control-c
2174 handling is not enabled, so test frameworks can unconditionally register
2175 all results they create independently of whether or not handling is enabled.
2176
Michael Foord469b1f02010-04-26 23:41:26 +00002177
Benjamin Petersonb48af542010-04-11 20:43:16 +00002178.. function:: removeResult(result)
2179
2180 Remove a registered result. Once a result has been removed then
2181 :meth:`~TestResult.stop` will no longer be called on that result object in
2182 response to a control-c.
2183
Michael Foord469b1f02010-04-26 23:41:26 +00002184
Michael Foordde4ceab2010-04-25 19:53:49 +00002185.. function:: removeHandler(function=None)
2186
2187 When called without arguments this function removes the control-c handler
2188 if it has been installed. This function can also be used as a test decorator
2189 to temporarily remove the handler whilst the test is being executed::
2190
2191 @unittest.removeHandler
2192 def test_signal_handling(self):
2193 ...