blob: 845bf0a2958cd5045f5ca186484e1b4bee04aa6b [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`unittest` --- Unit testing framework
2==========================================
3
4.. module:: unittest
5 :synopsis: Unit testing framework for Python.
6.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
7.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9.. sectionauthor:: Raymond Hettinger <python@rcn.com>
10
Ezio Melotti22170ed2010-11-20 09:57:27 +000011(If you are already familiar with the basic concepts of testing, you might want
12to skip to :ref:`the list of assert methods <assert-methods>`.)
Georg Brandl116aa622007-08-15 14:28:22 +000013
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010014The :mod:`unittest` unit testing framework was originally inspired by JUnit
15and has a similar flavor as major unit testing frameworks in other
16languages. It supports test automation, sharing of setup and shutdown code
17for tests, aggregation of tests into collections, and independence of the
18tests from the reporting framework.
Georg Brandl116aa622007-08-15 14:28:22 +000019
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010020To achieve this, :mod:`unittest` supports some important concepts in an
21object-oriented way:
Georg Brandl116aa622007-08-15 14:28:22 +000022
23test fixture
24 A :dfn:`test fixture` represents the preparation needed to perform one or more
25 tests, and any associate cleanup actions. This may involve, for example,
26 creating temporary or proxy databases, directories, or starting a server
27 process.
28
29test case
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010030 A :dfn:`test case` is the individual unit of testing. It checks for a specific
Georg Brandl116aa622007-08-15 14:28:22 +000031 response to a particular set of inputs. :mod:`unittest` provides a base class,
32 :class:`TestCase`, which may be used to create new test cases.
33
34test suite
35 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
36 used to aggregate tests that should be executed together.
37
38test runner
39 A :dfn:`test runner` is a component which orchestrates the execution of tests
40 and provides the outcome to the user. The runner may use a graphical interface,
41 a textual interface, or return a special value to indicate the results of
42 executing the tests.
43
Georg Brandl116aa622007-08-15 14:28:22 +000044
45.. seealso::
46
47 Module :mod:`doctest`
48 Another test-support module with a very different flavor.
49
50 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000051 Kent Beck's original paper on testing frameworks using the pattern shared
52 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000053
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000054 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000055 Third-party unittest frameworks with a lighter-weight syntax for writing
56 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000057
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010058 `The Python Testing Tools Taxonomy <http://wiki.python.org/moin/PythonTestingToolsTaxonomy>`_
Benjamin Petersonb48af542010-04-11 20:43:16 +000059 An extensive list of Python testing tools including functional testing
60 frameworks and mock object libraries.
Benjamin Petersond2397752009-06-27 23:45:02 +000061
Benjamin Petersonb48af542010-04-11 20:43:16 +000062 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
63 A special-interest-group for discussion of testing, and testing tools,
64 in Python.
Benjamin Petersond2397752009-06-27 23:45:02 +000065
Michael Foord90efac72011-01-03 15:39:49 +000066 The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is
67 a GUI tool for test discovery and execution. This is intended largely for ease of use
Senthil Kumaran847c33c2012-10-27 11:04:55 -070068 for those new to unit testing. For production environments it is
69 recommended that tests be driven by a continuous integration system such as
70 `Buildbot <http://buildbot.net/trac>`_, `Jenkins <http://jenkins-ci.org>`_
71 or `Hudson <http://hudson-ci.org/>`_.
Michael Foord90efac72011-01-03 15:39:49 +000072
73
Georg Brandl116aa622007-08-15 14:28:22 +000074.. _unittest-minimal-example:
75
76Basic example
77-------------
78
79The :mod:`unittest` module provides a rich set of tools for constructing and
80running tests. This section demonstrates that a small subset of the tools
81suffice to meet the needs of most users.
82
83Here is a short script to test three functions from the :mod:`random` module::
84
85 import random
86 import unittest
87
88 class TestSequenceFunctions(unittest.TestCase):
89
90 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +000091 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +000092
Benjamin Peterson52baa292009-03-24 00:56:30 +000093 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +000094 # make sure the shuffled sequence does not lose any elements
95 random.shuffle(self.seq)
96 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +000097 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +000098
Benjamin Peterson847a4112010-03-14 15:04:17 +000099 # should raise an exception for an immutable sequence
100 self.assertRaises(TypeError, random.shuffle, (1,2,3))
101
Benjamin Peterson52baa292009-03-24 00:56:30 +0000102 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000103 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000104 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Benjamin Peterson52baa292009-03-24 00:56:30 +0000106 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000107 with self.assertRaises(ValueError):
108 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000109 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000110 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112 if __name__ == '__main__':
113 unittest.main()
114
Benjamin Peterson52baa292009-03-24 00:56:30 +0000115A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000116individual tests are defined with methods whose names start with the letters
117``test``. This naming convention informs the test runner about which methods
118represent tests.
119
Benjamin Peterson52baa292009-03-24 00:56:30 +0000120The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000121expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000122:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
123These methods are used instead of the :keyword:`assert` statement so the test
124runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000125
Benjamin Peterson52baa292009-03-24 00:56:30 +0000126When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
127method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
128defined, the test runner will invoke that method after each test. In the
129example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
130test.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000133provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000134line, the above script produces an output that looks like this::
135
136 ...
137 ----------------------------------------------------------------------
138 Ran 3 tests in 0.000s
139
140 OK
141
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100142Passing the ``-v`` option to your test script will instruct :func:`unittest.main`
143to enable a higher level of verbosity, and produce the following output::
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Ezio Melottid59e44a2010-02-28 03:46:13 +0000145 test_choice (__main__.TestSequenceFunctions) ... ok
146 test_sample (__main__.TestSequenceFunctions) ... ok
147 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149 ----------------------------------------------------------------------
150 Ran 3 tests in 0.110s
151
152 OK
153
154The above examples show the most commonly used :mod:`unittest` features which
155are sufficient to meet many everyday testing needs. The remainder of the
156documentation explores the full feature set from first principles.
157
Benjamin Petersonb48af542010-04-11 20:43:16 +0000158
159.. _unittest-command-line-interface:
160
Éric Araujo76338ec2010-11-26 23:46:18 +0000161Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000162----------------------
163
164The unittest module can be used from the command line to run tests from
165modules, classes or even individual test methods::
166
167 python -m unittest test_module1 test_module2
168 python -m unittest test_module.TestClass
169 python -m unittest test_module.TestClass.test_method
170
171You can pass in a list with any combination of module names, and fully
172qualified class or method names.
173
Michael Foord37d120a2010-12-04 01:11:21 +0000174Test modules can be specified by file path as well::
175
176 python -m unittest tests/test_something.py
177
178This allows you to use the shell filename completion to specify the test module.
179The file specified must still be importable as a module. The path is converted
180to a module name by removing the '.py' and converting path separators into '.'.
181If you want to execute a test file that isn't importable as a module you should
182execute the file directly instead.
183
Benjamin Petersonb48af542010-04-11 20:43:16 +0000184You can run tests with more detail (higher verbosity) by passing in the -v flag::
185
186 python -m unittest -v test_module
187
Michael Foord086f3082010-11-21 21:28:01 +0000188When executed without arguments :ref:`unittest-test-discovery` is started::
189
190 python -m unittest
191
Éric Araujo713d3032010-11-18 16:38:46 +0000192For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000193
194 python -m unittest -h
195
Georg Brandl67b21b72010-08-17 15:07:14 +0000196.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000197 In earlier versions it was only possible to run individual test methods and
198 not modules or classes.
199
200
Éric Araujo76338ec2010-11-26 23:46:18 +0000201Command-line options
202~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000203
Éric Araujod3309df2010-11-21 03:09:17 +0000204:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000205
Éric Araujo713d3032010-11-18 16:38:46 +0000206.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000207
Éric Araujo713d3032010-11-18 16:38:46 +0000208.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000209
Éric Araujo713d3032010-11-18 16:38:46 +0000210 The standard output and standard error streams are buffered during the test
211 run. Output during a passing test is discarded. Output is echoed normally
212 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000213
Éric Araujo713d3032010-11-18 16:38:46 +0000214.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000215
Éric Araujo713d3032010-11-18 16:38:46 +0000216 Control-C during the test run waits for the current test to end and then
217 reports all the results so far. A second control-C raises the normal
218 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000219
Éric Araujo713d3032010-11-18 16:38:46 +0000220 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000221
Éric Araujo713d3032010-11-18 16:38:46 +0000222.. cmdoption:: -f, --failfast
223
224 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000225
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000226.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000227 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000228
229The command line can also be used for test discovery, for running all of the
230tests in a project or just a subset.
231
232
233.. _unittest-test-discovery:
234
235Test Discovery
236--------------
237
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000238.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000239
Ezio Melotti3d995842011-03-08 16:17:35 +0200240Unittest supports simple test discovery. In order to be compatible with test
241discovery, all of the test files must be :ref:`modules <tut-modules>` or
242:ref:`packages <tut-packages>` importable from the top-level directory of
243the project (this means that their filenames must be valid
244:ref:`identifiers <identifiers>`).
Benjamin Petersonb48af542010-04-11 20:43:16 +0000245
246Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000247used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000248
249 cd project_directory
250 python -m unittest discover
251
Michael Foord086f3082010-11-21 21:28:01 +0000252.. note::
253
254 As a shortcut, ``python -m unittest`` is the equivalent of
255 ``python -m unittest discover``. If you want to pass arguments to test
Éric Araujo941afed2011-09-01 02:47:34 +0200256 discovery the ``discover`` sub-command must be used explicitly.
Michael Foord086f3082010-11-21 21:28:01 +0000257
Benjamin Petersonb48af542010-04-11 20:43:16 +0000258The ``discover`` sub-command has the following options:
259
Éric Araujo713d3032010-11-18 16:38:46 +0000260.. program:: unittest discover
261
262.. cmdoption:: -v, --verbose
263
264 Verbose output
265
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800266.. cmdoption:: -s, --start-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000267
Éric Araujo941afed2011-09-01 02:47:34 +0200268 Directory to start discovery (``.`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000269
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800270.. cmdoption:: -p, --pattern pattern
Éric Araujo713d3032010-11-18 16:38:46 +0000271
Éric Araujo941afed2011-09-01 02:47:34 +0200272 Pattern to match test files (``test*.py`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000273
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800274.. cmdoption:: -t, --top-level-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000275
276 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000277
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000278The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
279as positional arguments in that order. The following two command lines
280are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000281
282 python -m unittest discover -s project_directory -p '*_test.py'
283 python -m unittest discover project_directory '*_test.py'
284
Michael Foord16f3e902010-05-08 15:13:42 +0000285As well as being a path it is possible to pass a package name, for example
286``myproject.subpackage.test``, as the start directory. The package name you
287supply will then be imported and its location on the filesystem will be used
288as the start directory.
289
290.. caution::
291
Senthil Kumaran916bd382010-10-15 12:55:19 +0000292 Test discovery loads tests by importing them. Once test discovery has found
293 all the test files from the start directory you specify it turns the paths
294 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000295 imported as ``foo.bar.baz``.
296
297 If you have a package installed globally and attempt test discovery on
298 a different copy of the package then the import *could* happen from the
299 wrong place. If this happens test discovery will warn you and exit.
300
301 If you supply the start directory as a package name rather than a
302 path to a directory then discover assumes that whichever location it
303 imports from is the location you intended, so you will not get the
304 warning.
305
Benjamin Petersonb48af542010-04-11 20:43:16 +0000306Test modules and packages can customize test loading and discovery by through
307the `load_tests protocol`_.
308
309
Georg Brandl116aa622007-08-15 14:28:22 +0000310.. _organizing-tests:
311
312Organizing test code
313--------------------
314
315The basic building blocks of unit testing are :dfn:`test cases` --- single
316scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000317test cases are represented by :class:`unittest.TestCase` instances.
318To make your own test cases you must write subclasses of
319:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000320
Georg Brandl116aa622007-08-15 14:28:22 +0000321The testing code of a :class:`TestCase` instance should be entirely self
322contained, such that it can be run either in isolation or in arbitrary
323combination with any number of other test cases.
324
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100325The simplest :class:`TestCase` subclass will simply implement a test method
326(i.e. a method whose name starts with ``test``) in order to perform specific
327testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000328
329 import unittest
330
331 class DefaultWidgetSizeTestCase(unittest.TestCase):
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100332 def test_default_widget_size(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000333 widget = Widget('The widget')
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100334 self.assertEqual(widget.size(), (50, 50))
Georg Brandl116aa622007-08-15 14:28:22 +0000335
Sandro Tosi41b24042012-01-21 10:59:37 +0100336Note that in order to test something, we use one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000337methods provided by the :class:`TestCase` base class. If the test fails, an
338exception will be raised, and :mod:`unittest` will identify the test case as a
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100339:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`.
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100341Tests can be numerous, and their set-up can be repetitive. Luckily, we
342can factor out set-up code by implementing a method called
343:meth:`~TestCase.setUp`, which the testing framework will automatically
344call for every single test we run::
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346 import unittest
347
348 class SimpleWidgetTestCase(unittest.TestCase):
349 def setUp(self):
350 self.widget = Widget('The widget')
351
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100352 def test_default_widget_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000353 self.assertEqual(self.widget.size(), (50,50),
354 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100356 def test_widget_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000357 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000358 self.assertEqual(self.widget.size(), (100,150),
359 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100361.. note::
362 The order in which the various tests will be run is determined
363 by sorting the test method names with respect to the built-in
364 ordering for strings.
365
Benjamin Peterson52baa292009-03-24 00:56:30 +0000366If the :meth:`~TestCase.setUp` method raises an exception while the test is
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100367running, the framework will consider the test to have suffered an error, and
368the test method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Benjamin Peterson52baa292009-03-24 00:56:30 +0000370Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100371after the test method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373 import unittest
374
375 class SimpleWidgetTestCase(unittest.TestCase):
376 def setUp(self):
377 self.widget = Widget('The widget')
378
379 def tearDown(self):
380 self.widget.dispose()
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100382If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be
383run whether the test method succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385Such a working environment for the testing code is called a :dfn:`fixture`.
386
Georg Brandl116aa622007-08-15 14:28:22 +0000387Test case instances are grouped together according to the features they test.
388:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100389represented by :mod:`unittest`'s :class:`TestSuite` class. In most cases,
390calling :func:`unittest.main` will do the right thing and collect all the
391module's test cases for you, and then execute them.
Georg Brandl116aa622007-08-15 14:28:22 +0000392
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100393However, should you want to customize the building of your test suite,
394you can do it yourself::
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396 def suite():
397 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000398 suite.addTest(WidgetTestCase('test_default_size'))
399 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000400 return suite
401
Georg Brandl116aa622007-08-15 14:28:22 +0000402You can place the definitions of test cases and test suites in the same modules
403as the code they are to test (such as :file:`widget.py`), but there are several
404advantages to placing the test code in a separate module, such as
405:file:`test_widget.py`:
406
407* The test module can be run standalone from the command line.
408
409* The test code can more easily be separated from shipped code.
410
411* There is less temptation to change test code to fit the code it tests without
412 a good reason.
413
414* Test code should be modified much less frequently than the code it tests.
415
416* Tested code can be refactored more easily.
417
418* Tests for modules written in C must be in separate modules anyway, so why not
419 be consistent?
420
421* If the testing strategy changes, there is no need to change the source code.
422
423
424.. _legacy-unit-tests:
425
426Re-using old test code
427----------------------
428
429Some users will find that they have existing test code that they would like to
430run from :mod:`unittest`, without converting every old test function to a
431:class:`TestCase` subclass.
432
433For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
434This subclass of :class:`TestCase` can be used to wrap an existing test
435function. Set-up and tear-down functions can also be provided.
436
437Given the following test function::
438
439 def testSomething():
440 something = makeSomething()
441 assert something.name is not None
442 # ...
443
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100444one can create an equivalent test case instance as follows, with optional
445set-up and tear-down methods::
Georg Brandl116aa622007-08-15 14:28:22 +0000446
447 testcase = unittest.FunctionTestCase(testSomething,
448 setUp=makeSomethingDB,
449 tearDown=deleteSomethingDB)
450
Georg Brandl116aa622007-08-15 14:28:22 +0000451.. note::
452
Benjamin Petersond2397752009-06-27 23:45:02 +0000453 Even though :class:`FunctionTestCase` can be used to quickly convert an
454 existing test base over to a :mod:`unittest`\ -based system, this approach is
455 not recommended. Taking the time to set up proper :class:`TestCase`
456 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000457
Benjamin Peterson52baa292009-03-24 00:56:30 +0000458In some cases, the existing tests may have been written using the :mod:`doctest`
459module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
460automatically build :class:`unittest.TestSuite` instances from the existing
461:mod:`doctest`\ -based tests.
462
Georg Brandl116aa622007-08-15 14:28:22 +0000463
Benjamin Peterson5254c042009-03-23 22:25:03 +0000464.. _unittest-skipping:
465
466Skipping tests and expected failures
467------------------------------------
468
Michael Foordf5c851a2010-02-05 21:48:03 +0000469.. versionadded:: 3.1
470
Benjamin Peterson5254c042009-03-23 22:25:03 +0000471Unittest supports skipping individual test methods and even whole classes of
472tests. In addition, it supports marking a test as a "expected failure," a test
473that is broken and will fail, but shouldn't be counted as a failure on a
474:class:`TestResult`.
475
476Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
477or one of its conditional variants.
478
Ezio Melottifed69ba2013-03-01 21:26:04 +0200479Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000480
481 class MyTestCase(unittest.TestCase):
482
483 @unittest.skip("demonstrating skipping")
484 def test_nothing(self):
485 self.fail("shouldn't happen")
486
Benjamin Petersond2397752009-06-27 23:45:02 +0000487 @unittest.skipIf(mylib.__version__ < (1, 3),
488 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000489 def test_format(self):
490 # Tests that work for only a certain version of the library.
491 pass
492
493 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
494 def test_windows_support(self):
495 # windows specific testing code
496 pass
497
Ezio Melottifed69ba2013-03-01 21:26:04 +0200498This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000499
Benjamin Petersonded31c42009-03-30 15:04:16 +0000500 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000501 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000502 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000503
504 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000505 Ran 3 tests in 0.005s
506
507 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000508
Ezio Melottifed69ba2013-03-01 21:26:04 +0200509Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000510
Sandro Tosi317075d2012-03-31 18:34:59 +0200511 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000512 class MySkippedTestCase(unittest.TestCase):
513 def test_not_run(self):
514 pass
515
Benjamin Peterson52baa292009-03-24 00:56:30 +0000516:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
517that needs to be set up is not available.
518
Benjamin Peterson5254c042009-03-23 22:25:03 +0000519Expected failures use the :func:`expectedFailure` decorator. ::
520
521 class ExpectedFailureTestCase(unittest.TestCase):
522 @unittest.expectedFailure
523 def test_fail(self):
524 self.assertEqual(1, 0, "broken")
525
526It's easy to roll your own skipping decorators by making a decorator that calls
527:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottifed69ba2013-03-01 21:26:04 +0200528the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000529
530 def skipUnlessHasattr(obj, attr):
531 if hasattr(obj, attr):
532 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200533 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000534
535The following decorators implement test skipping and expected failures:
536
Georg Brandl8a1caa22010-07-29 16:01:11 +0000537.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000538
539 Unconditionally skip the decorated test. *reason* should describe why the
540 test is being skipped.
541
Georg Brandl8a1caa22010-07-29 16:01:11 +0000542.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000543
544 Skip the decorated test if *condition* is true.
545
Georg Brandl8a1caa22010-07-29 16:01:11 +0000546.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000547
Georg Brandl6faee4e2010-09-21 14:48:28 +0000548 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000549
Georg Brandl8a1caa22010-07-29 16:01:11 +0000550.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000551
552 Mark the test as an expected failure. If the test fails when run, the test
553 is not counted as a failure.
554
Ezio Melotti265281a2013-03-27 20:11:55 +0200555.. exception:: SkipTest(reason)
556
557 This exception is raised to skip a test.
558
559 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
560 decorators instead of raising this directly.
561
Benjamin Petersonb48af542010-04-11 20:43:16 +0000562Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
563Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
564
Benjamin Peterson5254c042009-03-23 22:25:03 +0000565
Georg Brandl116aa622007-08-15 14:28:22 +0000566.. _unittest-contents:
567
568Classes and functions
569---------------------
570
Benjamin Peterson52baa292009-03-24 00:56:30 +0000571This section describes in depth the API of :mod:`unittest`.
572
573
574.. _testcase-objects:
575
576Test cases
577~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000578
Georg Brandl7f01a132009-09-16 15:58:14 +0000579.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000580
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100581 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000582 in the :mod:`unittest` universe. This class is intended to be used as a base
583 class, with specific tests being implemented by concrete subclasses. This class
584 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100585 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000586 kinds of failure.
587
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100588 Each instance of :class:`TestCase` will run a single base method: the method
589 named *methodName*. However, the standard implementation of the default
590 *methodName*, ``runTest()``, will run every method starting with ``test``
591 as an individual test, and count successes and failures accordingly.
592 Therefore, in most uses of :class:`TestCase`, you will neither change
593 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000594
Michael Foord1341bb02011-03-14 19:01:46 -0400595 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100596 :class:`TestCase` can be instantiated successfully without providing a
597 *methodName*. This makes it easier to experiment with :class:`TestCase`
598 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000599
600 :class:`TestCase` instances provide three groups of methods: one group used
601 to run the test, another used by the test implementation to check conditions
602 and report failures, and some inquiry methods allowing information about the
603 test itself to be gathered.
604
605 Methods in the first group (running the test) are:
606
Benjamin Peterson52baa292009-03-24 00:56:30 +0000607 .. method:: setUp()
608
609 Method called to prepare the test fixture. This is called immediately
610 before calling the test method; any exception raised by this method will
611 be considered an error rather than a test failure. The default
612 implementation does nothing.
613
614
615 .. method:: tearDown()
616
617 Method called immediately after the test method has been called and the
618 result recorded. This is called even if the test method raised an
619 exception, so the implementation in subclasses may need to be particularly
620 careful about checking internal state. Any exception raised by this
621 method will be considered an error rather than a test failure. This
622 method will only be called if the :meth:`setUp` succeeds, regardless of
623 the outcome of the test method. The default implementation does nothing.
624
625
Benjamin Petersonb48af542010-04-11 20:43:16 +0000626 .. method:: setUpClass()
627
628 A class method called before tests in an individual class run.
629 ``setUpClass`` is called with the class as the only argument
630 and must be decorated as a :func:`classmethod`::
631
632 @classmethod
633 def setUpClass(cls):
634 ...
635
636 See `Class and Module Fixtures`_ for more details.
637
638 .. versionadded:: 3.2
639
640
641 .. method:: tearDownClass()
642
643 A class method called after tests in an individual class have run.
644 ``tearDownClass`` is called with the class as the only argument
645 and must be decorated as a :meth:`classmethod`::
646
647 @classmethod
648 def tearDownClass(cls):
649 ...
650
651 See `Class and Module Fixtures`_ for more details.
652
653 .. versionadded:: 3.2
654
655
Georg Brandl7f01a132009-09-16 15:58:14 +0000656 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000657
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100658 Run the test, collecting the result into the :class:`TestResult` object
659 passed as *result*. If *result* is omitted or ``None``, a temporary
660 result object is created (by calling the :meth:`defaultTestResult`
661 method) and used. The result object is returned to :meth:`run`'s
662 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000663
664 The same effect may be had by simply calling the :class:`TestCase`
665 instance.
666
Michael Foord1341bb02011-03-14 19:01:46 -0400667 .. versionchanged:: 3.3
668 Previous versions of ``run`` did not return the result. Neither did
669 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000670
Benjamin Petersone549ead2009-03-28 21:42:05 +0000671 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000672
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000673 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000674 test. See :ref:`unittest-skipping` for more information.
675
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000676 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000677
Benjamin Peterson52baa292009-03-24 00:56:30 +0000678
679 .. method:: debug()
680
681 Run the test without collecting the result. This allows exceptions raised
682 by the test to be propagated to the caller, and can be used to support
683 running tests under a debugger.
684
Ezio Melotti22170ed2010-11-20 09:57:27 +0000685 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000686
Ezio Melotti4370b302010-11-03 20:39:14 +0000687 The :class:`TestCase` class provides a number of methods to check for and
688 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000689
Ezio Melotti4370b302010-11-03 20:39:14 +0000690 +-----------------------------------------+-----------------------------+---------------+
691 | Method | Checks that | New in |
692 +=========================================+=============================+===============+
693 | :meth:`assertEqual(a, b) | ``a == b`` | |
694 | <TestCase.assertEqual>` | | |
695 +-----------------------------------------+-----------------------------+---------------+
696 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
697 | <TestCase.assertNotEqual>` | | |
698 +-----------------------------------------+-----------------------------+---------------+
699 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
700 | <TestCase.assertTrue>` | | |
701 +-----------------------------------------+-----------------------------+---------------+
702 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
703 | <TestCase.assertFalse>` | | |
704 +-----------------------------------------+-----------------------------+---------------+
705 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
706 | <TestCase.assertIs>` | | |
707 +-----------------------------------------+-----------------------------+---------------+
708 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
709 | <TestCase.assertIsNot>` | | |
710 +-----------------------------------------+-----------------------------+---------------+
711 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
712 | <TestCase.assertIsNone>` | | |
713 +-----------------------------------------+-----------------------------+---------------+
714 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
715 | <TestCase.assertIsNotNone>` | | |
716 +-----------------------------------------+-----------------------------+---------------+
717 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
718 | <TestCase.assertIn>` | | |
719 +-----------------------------------------+-----------------------------+---------------+
720 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
721 | <TestCase.assertNotIn>` | | |
722 +-----------------------------------------+-----------------------------+---------------+
723 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
724 | <TestCase.assertIsInstance>` | | |
725 +-----------------------------------------+-----------------------------+---------------+
726 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
727 | <TestCase.assertNotIsInstance>` | | |
728 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000729
Ezio Melottib4dc2502011-05-06 15:01:41 +0300730 All the assert methods accept a *msg* argument that, if specified, is used
731 as the error message on failure (see also :data:`longMessage`).
732 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
733 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
734 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000735
Michael Foorde180d392011-01-28 19:51:48 +0000736 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000737
Michael Foorde180d392011-01-28 19:51:48 +0000738 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000739 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000740
Michael Foorde180d392011-01-28 19:51:48 +0000741 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000742 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200743 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000744 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000745 error message (see also the :ref:`list of type-specific methods
746 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000747
Raymond Hettinger35a88362009-04-09 00:08:24 +0000748 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200749 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000750
Michael Foord28a817e2010-02-09 00:03:57 +0000751 .. versionchanged:: 3.2
752 :meth:`assertMultiLineEqual` added as the default type equality
753 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000754
Benjamin Peterson52baa292009-03-24 00:56:30 +0000755
Michael Foorde180d392011-01-28 19:51:48 +0000756 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000757
Michael Foorde180d392011-01-28 19:51:48 +0000758 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000759 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000760
Ezio Melotti4370b302010-11-03 20:39:14 +0000761 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000762 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000763
Ezio Melotti4841fd62010-11-05 15:43:40 +0000764 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000765
Ezio Melotti4841fd62010-11-05 15:43:40 +0000766 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
767 is True`` (use ``assertIs(expr, True)`` for the latter). This method
768 should also be avoided when more specific methods are available (e.g.
769 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
770 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000771
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000772
Michael Foorde180d392011-01-28 19:51:48 +0000773 .. method:: assertIs(first, second, msg=None)
774 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000775
Michael Foorde180d392011-01-28 19:51:48 +0000776 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000777 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000778
Raymond Hettinger35a88362009-04-09 00:08:24 +0000779 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000780
781
Ezio Melotti4370b302010-11-03 20:39:14 +0000782 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000783 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000784
Ezio Melotti9794a262010-11-04 14:52:13 +0000785 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000786
Ezio Melotti4370b302010-11-03 20:39:14 +0000787 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000788
789
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000790 .. method:: assertIn(first, second, msg=None)
791 assertNotIn(first, second, msg=None)
792
Ezio Melotti4841fd62010-11-05 15:43:40 +0000793 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000794
Raymond Hettinger35a88362009-04-09 00:08:24 +0000795 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000796
797
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000798 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000799 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000800
Ezio Melotti9794a262010-11-04 14:52:13 +0000801 Test that *obj* is (or is not) an instance of *cls* (which can be a
802 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200803 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000804
Ezio Melotti4370b302010-11-03 20:39:14 +0000805 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000806
807
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000808
Ezio Melotti4370b302010-11-03 20:39:14 +0000809 It is also possible to check that exceptions and warnings are raised using
810 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000811
Ezio Melotti4370b302010-11-03 20:39:14 +0000812 +---------------------------------------------------------+--------------------------------------+------------+
813 | Method | Checks that | New in |
814 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200815 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000816 | <TestCase.assertRaises>` | | |
817 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200818 | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
819 | <TestCase.assertRaisesRegex>` | and the message matches *re* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000820 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200821 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000822 | <TestCase.assertWarns>` | | |
823 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200824 | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
825 | <TestCase.assertWarnsRegex>` | and the message matches *re* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000826 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000827
Georg Brandl7f01a132009-09-16 15:58:14 +0000828 .. method:: assertRaises(exception, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300829 assertRaises(exception, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000830
831 Test that an exception is raised when *callable* is called with any
832 positional or keyword arguments that are also passed to
833 :meth:`assertRaises`. The test passes if *exception* is raised, is an
834 error if another exception is raised, or fails if no exception is raised.
835 To catch any of a group of exceptions, a tuple containing the exception
836 classes may be passed as *exception*.
837
Ezio Melottib4dc2502011-05-06 15:01:41 +0300838 If only the *exception* and possibly the *msg* arguments are given,
839 return a context manager so that the code under test can be written
840 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000841
Michael Foord41531f22010-02-05 21:13:40 +0000842 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000843 do_something()
844
Ezio Melottib4dc2502011-05-06 15:01:41 +0300845 When used as a context manager, :meth:`assertRaises` accepts the
846 additional keyword argument *msg*.
847
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000848 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000849 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000850 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000851
Georg Brandl8a1caa22010-07-29 16:01:11 +0000852 with self.assertRaises(SomeException) as cm:
853 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000854
Georg Brandl8a1caa22010-07-29 16:01:11 +0000855 the_exception = cm.exception
856 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000857
Ezio Melotti49008232010-02-08 21:57:48 +0000858 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000859 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000860
Ezio Melotti49008232010-02-08 21:57:48 +0000861 .. versionchanged:: 3.2
862 Added the :attr:`exception` attribute.
863
Ezio Melottib4dc2502011-05-06 15:01:41 +0300864 .. versionchanged:: 3.3
865 Added the *msg* keyword argument when used as a context manager.
866
Benjamin Peterson52baa292009-03-24 00:56:30 +0000867
Ezio Melottied3a7d22010-12-01 02:32:32 +0000868 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300869 assertRaisesRegex(exception, regex, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000870
Ezio Melottied3a7d22010-12-01 02:32:32 +0000871 Like :meth:`assertRaises` but also tests that *regex* matches
872 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000873 a regular expression object or a string containing a regular expression
874 suitable for use by :func:`re.search`. Examples::
875
Terry Jan Reedyc4565a92013-06-29 13:15:43 -0400876 self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
Ezio Melottied3a7d22010-12-01 02:32:32 +0000877 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000878
879 or::
880
Ezio Melottied3a7d22010-12-01 02:32:32 +0000881 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000882 int('XYZ')
883
Georg Brandl419e3de2010-12-01 15:44:25 +0000884 .. versionadded:: 3.1
885 under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +0300886
Ezio Melottied3a7d22010-12-01 02:32:32 +0000887 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +0000888 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000889
Ezio Melottib4dc2502011-05-06 15:01:41 +0300890 .. versionchanged:: 3.3
891 Added the *msg* keyword argument when used as a context manager.
892
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000893
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000894 .. method:: assertWarns(warning, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300895 assertWarns(warning, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000896
897 Test that a warning is triggered when *callable* is called with any
898 positional or keyword arguments that are also passed to
899 :meth:`assertWarns`. The test passes if *warning* is triggered and
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400900 fails if it isn't. Any exception is an error.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000901 To catch any of a group of warnings, a tuple containing the warning
902 classes may be passed as *warnings*.
903
Ezio Melottib4dc2502011-05-06 15:01:41 +0300904 If only the *warning* and possibly the *msg* arguments are given,
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400905 return a context manager so that the code under test can be written
Ezio Melottib4dc2502011-05-06 15:01:41 +0300906 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000907
908 with self.assertWarns(SomeWarning):
909 do_something()
910
Terry Jan Reedy9eda66d2013-07-27 16:15:29 -0400911 When used as a context manager, :meth:`assertWarns` accepts the
Ezio Melottib4dc2502011-05-06 15:01:41 +0300912 additional keyword argument *msg*.
913
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000914 The context manager will store the caught warning object in its
915 :attr:`warning` attribute, and the source line which triggered the
916 warnings in the :attr:`filename` and :attr:`lineno` attributes.
917 This can be useful if the intention is to perform additional checks
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400918 on the warning caught::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000919
920 with self.assertWarns(SomeWarning) as cm:
921 do_something()
922
923 self.assertIn('myfile.py', cm.filename)
924 self.assertEqual(320, cm.lineno)
925
926 This method works regardless of the warning filters in place when it
927 is called.
928
929 .. versionadded:: 3.2
930
Ezio Melottib4dc2502011-05-06 15:01:41 +0300931 .. versionchanged:: 3.3
932 Added the *msg* keyword argument when used as a context manager.
933
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000934
Ezio Melottied3a7d22010-12-01 02:32:32 +0000935 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300936 assertWarnsRegex(warning, regex, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000937
Ezio Melottied3a7d22010-12-01 02:32:32 +0000938 Like :meth:`assertWarns` but also tests that *regex* matches on the
939 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000940 object or a string containing a regular expression suitable for use
941 by :func:`re.search`. Example::
942
Ezio Melottied3a7d22010-12-01 02:32:32 +0000943 self.assertWarnsRegex(DeprecationWarning,
944 r'legacy_function\(\) is deprecated',
945 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000946
947 or::
948
Ezio Melottied3a7d22010-12-01 02:32:32 +0000949 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000950 frobnicate('/etc/passwd')
951
952 .. versionadded:: 3.2
953
Ezio Melottib4dc2502011-05-06 15:01:41 +0300954 .. versionchanged:: 3.3
955 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000956
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000957
Ezio Melotti4370b302010-11-03 20:39:14 +0000958 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000959
Ezio Melotti4370b302010-11-03 20:39:14 +0000960 +---------------------------------------+--------------------------------+--------------+
961 | Method | Checks that | New in |
962 +=======================================+================================+==============+
963 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
964 | <TestCase.assertAlmostEqual>` | | |
965 +---------------------------------------+--------------------------------+--------------+
966 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
967 | <TestCase.assertNotAlmostEqual>` | | |
968 +---------------------------------------+--------------------------------+--------------+
969 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
970 | <TestCase.assertGreater>` | | |
971 +---------------------------------------+--------------------------------+--------------+
972 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
973 | <TestCase.assertGreaterEqual>` | | |
974 +---------------------------------------+--------------------------------+--------------+
975 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
976 | <TestCase.assertLess>` | | |
977 +---------------------------------------+--------------------------------+--------------+
978 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
979 | <TestCase.assertLessEqual>` | | |
980 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +0000981 | :meth:`assertRegex(s, re) | ``regex.search(s)`` | 3.1 |
982 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000983 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +0000984 | :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 |
985 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000986 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200987 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +0000988 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000989 | | regardless of their order | |
990 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000991
992
Michael Foorde180d392011-01-28 19:51:48 +0000993 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
994 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000995
Michael Foorde180d392011-01-28 19:51:48 +0000996 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000997 equal by computing the difference, rounding to the given number of
998 decimal *places* (default 7), and comparing to zero. Note that these
999 methods round the values to the given number of *decimal places* (i.e.
1000 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001001
Ezio Melotti4370b302010-11-03 20:39:14 +00001002 If *delta* is supplied instead of *places* then the difference
Michael Foorde180d392011-01-28 19:51:48 +00001003 between *first* and *second* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001004
Ezio Melotti4370b302010-11-03 20:39:14 +00001005 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001006
Ezio Melotti4370b302010-11-03 20:39:14 +00001007 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001008 :meth:`assertAlmostEqual` automatically considers almost equal objects
1009 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1010 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001011
Ezio Melotti4370b302010-11-03 20:39:14 +00001012
Michael Foorde180d392011-01-28 19:51:48 +00001013 .. method:: assertGreater(first, second, msg=None)
1014 assertGreaterEqual(first, second, msg=None)
1015 assertLess(first, second, msg=None)
1016 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001017
Michael Foorde180d392011-01-28 19:51:48 +00001018 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001019 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001020
1021 >>> self.assertGreaterEqual(3, 4)
1022 AssertionError: "3" unexpectedly not greater than or equal to "4"
1023
1024 .. versionadded:: 3.1
1025
1026
Ezio Melottied3a7d22010-12-01 02:32:32 +00001027 .. method:: assertRegex(text, regex, msg=None)
1028 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001029
Ezio Melottied3a7d22010-12-01 02:32:32 +00001030 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001031 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001032 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001033 may be a regular expression object or a string containing a regular
1034 expression suitable for use by :func:`re.search`.
1035
Georg Brandl419e3de2010-12-01 15:44:25 +00001036 .. versionadded:: 3.1
1037 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001038 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001039 The method ``assertRegexpMatches()`` has been renamed to
1040 :meth:`.assertRegex`.
1041 .. versionadded:: 3.2
1042 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001043
1044
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001045 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001046
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001047 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001048 regardless of their order. When they don't, an error message listing the
1049 differences between the sequences will be generated.
1050
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001051 Duplicate elements are *not* ignored when comparing *first* and
1052 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001053 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001054 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001055 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001056
Ezio Melotti4370b302010-11-03 20:39:14 +00001057 .. versionadded:: 3.2
1058
Ezio Melotti4370b302010-11-03 20:39:14 +00001059
Ezio Melotti22170ed2010-11-20 09:57:27 +00001060 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001061
Ezio Melotti22170ed2010-11-20 09:57:27 +00001062 The :meth:`assertEqual` method dispatches the equality check for objects of
1063 the same type to different type-specific methods. These methods are already
1064 implemented for most of the built-in types, but it's also possible to
1065 register new methods using :meth:`addTypeEqualityFunc`:
1066
1067 .. method:: addTypeEqualityFunc(typeobj, function)
1068
1069 Registers a type-specific method called by :meth:`assertEqual` to check
1070 if two objects of exactly the same *typeobj* (not subclasses) compare
1071 equal. *function* must take two positional arguments and a third msg=None
1072 keyword argument just as :meth:`assertEqual` does. It must raise
1073 :data:`self.failureException(msg) <failureException>` when inequality
1074 between the first two parameters is detected -- possibly providing useful
1075 information and explaining the inequalities in details in the error
1076 message.
1077
1078 .. versionadded:: 3.1
1079
1080 The list of type-specific methods automatically used by
1081 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1082 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001083
1084 +-----------------------------------------+-----------------------------+--------------+
1085 | Method | Used to compare | New in |
1086 +=========================================+=============================+==============+
1087 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1088 | <TestCase.assertMultiLineEqual>` | | |
1089 +-----------------------------------------+-----------------------------+--------------+
1090 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1091 | <TestCase.assertSequenceEqual>` | | |
1092 +-----------------------------------------+-----------------------------+--------------+
1093 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1094 | <TestCase.assertListEqual>` | | |
1095 +-----------------------------------------+-----------------------------+--------------+
1096 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1097 | <TestCase.assertTupleEqual>` | | |
1098 +-----------------------------------------+-----------------------------+--------------+
1099 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1100 | <TestCase.assertSetEqual>` | | |
1101 +-----------------------------------------+-----------------------------+--------------+
1102 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1103 | <TestCase.assertDictEqual>` | | |
1104 +-----------------------------------------+-----------------------------+--------------+
1105
1106
1107
Michael Foorde180d392011-01-28 19:51:48 +00001108 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001109
Michael Foorde180d392011-01-28 19:51:48 +00001110 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001111 When not equal a diff of the two strings highlighting the differences
1112 will be included in the error message. This method is used by default
1113 when comparing strings with :meth:`assertEqual`.
1114
Ezio Melotti4370b302010-11-03 20:39:14 +00001115 .. versionadded:: 3.1
1116
1117
Michael Foorde180d392011-01-28 19:51:48 +00001118 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001119
1120 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001121 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001122 be raised. If the sequences are different an error message is
1123 constructed that shows the difference between the two.
1124
Ezio Melotti22170ed2010-11-20 09:57:27 +00001125 This method is not called directly by :meth:`assertEqual`, but
1126 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001127 :meth:`assertTupleEqual`.
1128
1129 .. versionadded:: 3.1
1130
1131
Michael Foorde180d392011-01-28 19:51:48 +00001132 .. method:: assertListEqual(first, second, msg=None)
1133 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001134
Ezio Melotti49ccd512012-08-29 17:50:42 +03001135 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001136 constructed that shows only the differences between the two. An error
1137 is also raised if either of the parameters are of the wrong type.
1138 These methods are used by default when comparing lists or tuples with
1139 :meth:`assertEqual`.
1140
Ezio Melotti4370b302010-11-03 20:39:14 +00001141 .. versionadded:: 3.1
1142
1143
Michael Foorde180d392011-01-28 19:51:48 +00001144 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001145
1146 Tests that two sets are equal. If not, an error message is constructed
1147 that lists the differences between the sets. This method is used by
1148 default when comparing sets or frozensets with :meth:`assertEqual`.
1149
Michael Foorde180d392011-01-28 19:51:48 +00001150 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001151 method.
1152
Ezio Melotti4370b302010-11-03 20:39:14 +00001153 .. versionadded:: 3.1
1154
1155
Michael Foorde180d392011-01-28 19:51:48 +00001156 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001157
1158 Test that two dictionaries are equal. If not, an error message is
1159 constructed that shows the differences in the dictionaries. This
1160 method will be used by default to compare dictionaries in
1161 calls to :meth:`assertEqual`.
1162
Ezio Melotti4370b302010-11-03 20:39:14 +00001163 .. versionadded:: 3.1
1164
1165
1166
Ezio Melotti22170ed2010-11-20 09:57:27 +00001167 .. _other-methods-and-attrs:
1168
Ezio Melotti4370b302010-11-03 20:39:14 +00001169 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001170
Benjamin Peterson52baa292009-03-24 00:56:30 +00001171
Georg Brandl7f01a132009-09-16 15:58:14 +00001172 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001173
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001174 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001175 the error message.
1176
1177
1178 .. attribute:: failureException
1179
1180 This class attribute gives the exception raised by the test method. If a
1181 test framework needs to use a specialized exception, possibly to carry
1182 additional information, it must subclass this exception in order to "play
1183 fair" with the framework. The initial value of this attribute is
1184 :exc:`AssertionError`.
1185
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001186
1187 .. attribute:: longMessage
1188
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001189 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001190 :ref:`assert methods <assert-methods>` will be appended to the end of the
1191 normal failure message. The normal messages contain useful information
1192 about the objects involved, for example the message from assertEqual
1193 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001194 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001195 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001196
Michael Foord5074df62010-12-03 00:53:09 +00001197 This attribute defaults to ``True``. If set to False then a custom message
1198 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001199
1200 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001201 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001202
Raymond Hettinger35a88362009-04-09 00:08:24 +00001203 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001204
1205
Michael Foord98b3e762010-06-05 21:59:55 +00001206 .. attribute:: maxDiff
1207
1208 This attribute controls the maximum length of diffs output by assert
1209 methods that report diffs on failure. It defaults to 80*8 characters.
1210 Assert methods affected by this attribute are
1211 :meth:`assertSequenceEqual` (including all the sequence comparison
1212 methods that delegate to it), :meth:`assertDictEqual` and
1213 :meth:`assertMultiLineEqual`.
1214
1215 Setting ``maxDiff`` to None means that there is no maximum length of
1216 diffs.
1217
1218 .. versionadded:: 3.2
1219
1220
Benjamin Peterson52baa292009-03-24 00:56:30 +00001221 Testing frameworks can use the following methods to collect information on
1222 the test:
1223
1224
1225 .. method:: countTestCases()
1226
1227 Return the number of tests represented by this test object. For
1228 :class:`TestCase` instances, this will always be ``1``.
1229
1230
1231 .. method:: defaultTestResult()
1232
1233 Return an instance of the test result class that should be used for this
1234 test case class (if no other result instance is provided to the
1235 :meth:`run` method).
1236
1237 For :class:`TestCase` instances, this will always be an instance of
1238 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1239 as necessary.
1240
1241
1242 .. method:: id()
1243
1244 Return a string identifying the specific test case. This is usually the
1245 full name of the test method, including the module and class name.
1246
1247
1248 .. method:: shortDescription()
1249
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001250 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001251 has been provided. The default implementation of this method
1252 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001253 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001254
Georg Brandl419e3de2010-12-01 15:44:25 +00001255 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001256 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001257 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001258 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001259 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001260
Georg Brandl116aa622007-08-15 14:28:22 +00001261
Georg Brandl7f01a132009-09-16 15:58:14 +00001262 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001263
1264 Add a function to be called after :meth:`tearDown` to cleanup resources
1265 used during the test. Functions will be called in reverse order to the
1266 order they are added (LIFO). They are called with any arguments and
1267 keyword arguments passed into :meth:`addCleanup` when they are
1268 added.
1269
1270 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1271 then any cleanup functions added will still be called.
1272
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001273 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001274
1275
1276 .. method:: doCleanups()
1277
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001278 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001279 after :meth:`setUp` if :meth:`setUp` raises an exception.
1280
1281 It is responsible for calling all the cleanup functions added by
1282 :meth:`addCleanup`. If you need cleanup functions to be called
1283 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1284 yourself.
1285
1286 :meth:`doCleanups` pops methods off the stack of cleanup
1287 functions one at a time, so it can be called at any time.
1288
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001289 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001290
1291
Georg Brandl7f01a132009-09-16 15:58:14 +00001292.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001293
1294 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001295 allows the test runner to drive the test, but does not provide the methods
1296 which test code can use to check and report errors. This is used to create
1297 test cases using legacy test code, allowing it to be integrated into a
1298 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001299
1300
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001301.. _deprecated-aliases:
1302
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001303Deprecated aliases
1304##################
1305
1306For historical reasons, some of the :class:`TestCase` methods had one or more
1307aliases that are now deprecated. The following table lists the correct names
1308along with their deprecated aliases:
1309
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001310 ============================== ====================== ======================
1311 Method Name Deprecated alias Deprecated alias
1312 ============================== ====================== ======================
1313 :meth:`.assertEqual` failUnlessEqual assertEquals
1314 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1315 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001316 :meth:`.assertFalse` failIf
1317 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001318 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1319 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001320 :meth:`.assertRegex` assertRegexpMatches
1321 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001322 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001323
Ezio Melotti361467e2011-04-03 17:37:58 +03001324 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001325 the fail* aliases listed in the second column.
1326 .. deprecated:: 3.2
1327 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001328 .. deprecated:: 3.2
1329 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1330 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001331
1332
Benjamin Peterson52baa292009-03-24 00:56:30 +00001333.. _testsuite-objects:
1334
Benjamin Peterson52baa292009-03-24 00:56:30 +00001335Grouping tests
1336~~~~~~~~~~~~~~
1337
Georg Brandl7f01a132009-09-16 15:58:14 +00001338.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001339
1340 This class represents an aggregation of individual tests cases and test suites.
1341 The class presents the interface needed by the test runner to allow it to be run
1342 as any other test case. Running a :class:`TestSuite` instance is the same as
1343 iterating over the suite, running each test individually.
1344
1345 If *tests* is given, it must be an iterable of individual test cases or other
1346 test suites that will be used to build the suite initially. Additional methods
1347 are provided to add test cases and suites to the collection later on.
1348
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001349 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1350 they do not actually implement a test. Instead, they are used to aggregate
1351 tests into groups of tests that should be run together. Some additional
1352 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001353
1354
1355 .. method:: TestSuite.addTest(test)
1356
1357 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1358
1359
1360 .. method:: TestSuite.addTests(tests)
1361
1362 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1363 instances to this test suite.
1364
Benjamin Petersond2397752009-06-27 23:45:02 +00001365 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1366 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001367
1368 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1369
1370
1371 .. method:: run(result)
1372
1373 Run the tests associated with this suite, collecting the result into the
1374 test result object passed as *result*. Note that unlike
1375 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1376 be passed in.
1377
1378
1379 .. method:: debug()
1380
1381 Run the tests associated with this suite without collecting the
1382 result. This allows exceptions raised by the test to be propagated to the
1383 caller and can be used to support running tests under a debugger.
1384
1385
1386 .. method:: countTestCases()
1387
1388 Return the number of tests represented by this test object, including all
1389 individual tests and sub-suites.
1390
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001391
1392 .. method:: __iter__()
1393
1394 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1395 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1396 that this method maybe called several times on a single suite
1397 (for example when counting tests or comparing for equality)
1398 so the tests returned must be the same for repeated iterations.
1399
Georg Brandl853947a2010-01-31 18:53:23 +00001400 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001401 In earlier versions the :class:`TestSuite` accessed tests directly rather
1402 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1403 for providing tests.
1404
Benjamin Peterson52baa292009-03-24 00:56:30 +00001405 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1406 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1407
1408
Benjamin Peterson52baa292009-03-24 00:56:30 +00001409Loading and running tests
1410~~~~~~~~~~~~~~~~~~~~~~~~~
1411
Georg Brandl116aa622007-08-15 14:28:22 +00001412.. class:: TestLoader()
1413
Benjamin Peterson52baa292009-03-24 00:56:30 +00001414 The :class:`TestLoader` class is used to create test suites from classes and
1415 modules. Normally, there is no need to create an instance of this class; the
1416 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001417 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1418 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001419
1420 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001421
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001422
Benjamin Peterson52baa292009-03-24 00:56:30 +00001423 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001424
Benjamin Peterson52baa292009-03-24 00:56:30 +00001425 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1426 :class:`testCaseClass`.
1427
1428
1429 .. method:: loadTestsFromModule(module)
1430
1431 Return a suite of all tests cases contained in the given module. This
1432 method searches *module* for classes derived from :class:`TestCase` and
1433 creates an instance of the class for each test method defined for the
1434 class.
1435
Georg Brandle720c0a2009-04-27 16:20:50 +00001436 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001437
1438 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1439 convenient in sharing fixtures and helper functions, defining test
1440 methods on base classes that are not intended to be instantiated
1441 directly does not play well with this method. Doing so, however, can
1442 be useful when the fixtures are different and defined in subclasses.
1443
Benjamin Petersond2397752009-06-27 23:45:02 +00001444 If a module provides a ``load_tests`` function it will be called to
1445 load the tests. This allows modules to customize test loading.
1446 This is the `load_tests protocol`_.
1447
Georg Brandl853947a2010-01-31 18:53:23 +00001448 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001449 Support for ``load_tests`` added.
1450
Benjamin Peterson52baa292009-03-24 00:56:30 +00001451
Georg Brandl7f01a132009-09-16 15:58:14 +00001452 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001453
1454 Return a suite of all tests cases given a string specifier.
1455
1456 The specifier *name* is a "dotted name" that may resolve either to a
1457 module, a test case class, a test method within a test case class, a
1458 :class:`TestSuite` instance, or a callable object which returns a
1459 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1460 applied in the order listed here; that is, a method on a possible test
1461 case class will be picked up as "a test method within a test case class",
1462 rather than "a callable object".
1463
1464 For example, if you have a module :mod:`SampleTests` containing a
1465 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1466 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001467 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1468 return a suite which will run all three test methods. Using the specifier
1469 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1470 suite which will run only the :meth:`test_two` test method. The specifier
1471 can refer to modules and packages which have not been imported; they will
1472 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001473
1474 The method optionally resolves *name* relative to the given *module*.
1475
1476
Georg Brandl7f01a132009-09-16 15:58:14 +00001477 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001478
1479 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1480 than a single name. The return value is a test suite which supports all
1481 the tests defined for each name.
1482
1483
1484 .. method:: getTestCaseNames(testCaseClass)
1485
1486 Return a sorted sequence of method names found within *testCaseClass*;
1487 this should be a subclass of :class:`TestCase`.
1488
Benjamin Petersond2397752009-06-27 23:45:02 +00001489
1490 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1491
1492 Find and return all test modules from the specified start directory,
1493 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001494 *pattern* will be loaded. (Using shell style pattern matching.) Only
1495 module names that are importable (i.e. are valid Python identifiers) will
1496 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001497
1498 All test modules must be importable from the top level of the project. If
1499 the start directory is not the top level directory then the top level
1500 directory must be specified separately.
1501
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001502 If importing a module fails, for example due to a syntax error, then this
1503 will be recorded as a single error and discovery will continue.
1504
Benjamin Petersond2397752009-06-27 23:45:02 +00001505 If a test package name (directory with :file:`__init__.py`) matches the
1506 pattern then the package will be checked for a ``load_tests``
1507 function. If this exists then it will be called with *loader*, *tests*,
1508 *pattern*.
1509
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001510 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001511 ``load_tests`` is responsible for loading all tests in the package.
1512
1513 The pattern is deliberately not stored as a loader attribute so that
1514 packages can continue discovery themselves. *top_level_dir* is stored so
1515 ``load_tests`` does not need to pass this argument in to
1516 ``loader.discover()``.
1517
Benjamin Petersonb48af542010-04-11 20:43:16 +00001518 *start_dir* can be a dotted module name as well as a directory.
1519
Georg Brandl853947a2010-01-31 18:53:23 +00001520 .. versionadded:: 3.2
1521
Benjamin Petersond2397752009-06-27 23:45:02 +00001522
Benjamin Peterson52baa292009-03-24 00:56:30 +00001523 The following attributes of a :class:`TestLoader` can be configured either by
1524 subclassing or assignment on an instance:
1525
1526
1527 .. attribute:: testMethodPrefix
1528
1529 String giving the prefix of method names which will be interpreted as test
1530 methods. The default value is ``'test'``.
1531
1532 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1533 methods.
1534
1535
1536 .. attribute:: sortTestMethodsUsing
1537
1538 Function to be used to compare method names when sorting them in
1539 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1540
1541
1542 .. attribute:: suiteClass
1543
1544 Callable object that constructs a test suite from a list of tests. No
1545 methods on the resulting object are needed. The default value is the
1546 :class:`TestSuite` class.
1547
1548 This affects all the :meth:`loadTestsFrom\*` methods.
1549
1550
Benjamin Peterson52baa292009-03-24 00:56:30 +00001551.. class:: TestResult
1552
1553 This class is used to compile information about which tests have succeeded
1554 and which have failed.
1555
1556 A :class:`TestResult` object stores the results of a set of tests. The
1557 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1558 properly recorded; test authors do not need to worry about recording the
1559 outcome of tests.
1560
1561 Testing frameworks built on top of :mod:`unittest` may want access to the
1562 :class:`TestResult` object generated by running a set of tests for reporting
1563 purposes; a :class:`TestResult` instance is returned by the
1564 :meth:`TestRunner.run` method for this purpose.
1565
1566 :class:`TestResult` instances have the following attributes that will be of
1567 interest when inspecting the results of running a set of tests:
1568
1569
1570 .. attribute:: errors
1571
1572 A list containing 2-tuples of :class:`TestCase` instances and strings
1573 holding formatted tracebacks. Each tuple represents a test which raised an
1574 unexpected exception.
1575
Benjamin Peterson52baa292009-03-24 00:56:30 +00001576 .. attribute:: failures
1577
1578 A list containing 2-tuples of :class:`TestCase` instances and strings
1579 holding formatted tracebacks. Each tuple represents a test where a failure
1580 was explicitly signalled using the :meth:`TestCase.fail\*` or
1581 :meth:`TestCase.assert\*` methods.
1582
Benjamin Peterson52baa292009-03-24 00:56:30 +00001583 .. attribute:: skipped
1584
1585 A list containing 2-tuples of :class:`TestCase` instances and strings
1586 holding the reason for skipping the test.
1587
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001588 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001589
1590 .. attribute:: expectedFailures
1591
Georg Brandl6faee4e2010-09-21 14:48:28 +00001592 A list containing 2-tuples of :class:`TestCase` instances and strings
1593 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001594 of the test case.
1595
1596 .. attribute:: unexpectedSuccesses
1597
1598 A list containing :class:`TestCase` instances that were marked as expected
1599 failures, but succeeded.
1600
1601 .. attribute:: shouldStop
1602
1603 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1604
1605
1606 .. attribute:: testsRun
1607
1608 The total number of tests run so far.
1609
1610
Georg Brandl12037202010-12-02 22:35:25 +00001611 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001612
1613 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1614 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1615 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1616 fails or errors. Any output is also attached to the failure / error message.
1617
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001618 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001619
1620
1621 .. attribute:: failfast
1622
1623 If set to true :meth:`stop` will be called on the first failure or error,
1624 halting the test run.
1625
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001626 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001627
1628
Benjamin Peterson52baa292009-03-24 00:56:30 +00001629 .. method:: wasSuccessful()
1630
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001631 Return ``True`` if all tests run so far have passed, otherwise returns
1632 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001633
1634
1635 .. method:: stop()
1636
1637 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001638 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001639 :class:`TestRunner` objects should respect this flag and return without
1640 running any additional tests.
1641
1642 For example, this feature is used by the :class:`TextTestRunner` class to
1643 stop the test framework when the user signals an interrupt from the
1644 keyboard. Interactive tools which provide :class:`TestRunner`
1645 implementations can use this in a similar manner.
1646
1647 The following methods of the :class:`TestResult` class are used to maintain
1648 the internal data structures, and may be extended in subclasses to support
1649 additional reporting requirements. This is particularly useful in building
1650 tools which support interactive reporting while tests are being run.
1651
1652
1653 .. method:: startTest(test)
1654
1655 Called when the test case *test* is about to be run.
1656
Benjamin Peterson52baa292009-03-24 00:56:30 +00001657 .. method:: stopTest(test)
1658
1659 Called after the test case *test* has been executed, regardless of the
1660 outcome.
1661
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001662 .. method:: startTestRun(test)
1663
1664 Called once before any tests are executed.
1665
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001666 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001667
1668
1669 .. method:: stopTestRun(test)
1670
Ezio Melotti176d6c42010-01-27 20:58:07 +00001671 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001672
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001673 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001674
1675
Benjamin Peterson52baa292009-03-24 00:56:30 +00001676 .. method:: addError(test, err)
1677
1678 Called when the test case *test* raises an unexpected exception *err* is a
1679 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1680 traceback)``.
1681
1682 The default implementation appends a tuple ``(test, formatted_err)`` to
1683 the instance's :attr:`errors` attribute, where *formatted_err* is a
1684 formatted traceback derived from *err*.
1685
1686
1687 .. method:: addFailure(test, err)
1688
Benjamin Petersond2397752009-06-27 23:45:02 +00001689 Called when the test case *test* signals a failure. *err* is a tuple of
1690 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001691
1692 The default implementation appends a tuple ``(test, formatted_err)`` to
1693 the instance's :attr:`failures` attribute, where *formatted_err* is a
1694 formatted traceback derived from *err*.
1695
1696
1697 .. method:: addSuccess(test)
1698
1699 Called when the test case *test* succeeds.
1700
1701 The default implementation does nothing.
1702
1703
1704 .. method:: addSkip(test, reason)
1705
1706 Called when the test case *test* is skipped. *reason* is the reason the
1707 test gave for skipping.
1708
1709 The default implementation appends a tuple ``(test, reason)`` to the
1710 instance's :attr:`skipped` attribute.
1711
1712
1713 .. method:: addExpectedFailure(test, err)
1714
1715 Called when the test case *test* fails, but was marked with the
1716 :func:`expectedFailure` decorator.
1717
1718 The default implementation appends a tuple ``(test, formatted_err)`` to
1719 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1720 is a formatted traceback derived from *err*.
1721
1722
1723 .. method:: addUnexpectedSuccess(test)
1724
1725 Called when the test case *test* was marked with the
1726 :func:`expectedFailure` decorator, but succeeded.
1727
1728 The default implementation appends the test to the instance's
1729 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001730
Georg Brandl67b21b72010-08-17 15:07:14 +00001731
Michael Foord34c94622010-02-10 15:51:42 +00001732.. class:: TextTestResult(stream, descriptions, verbosity)
1733
Georg Brandl67b21b72010-08-17 15:07:14 +00001734 A concrete implementation of :class:`TestResult` used by the
1735 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001736
Georg Brandl67b21b72010-08-17 15:07:14 +00001737 .. versionadded:: 3.2
1738 This class was previously named ``_TextTestResult``. The old name still
1739 exists as an alias but is deprecated.
1740
Georg Brandl116aa622007-08-15 14:28:22 +00001741
1742.. data:: defaultTestLoader
1743
1744 Instance of the :class:`TestLoader` class intended to be shared. If no
1745 customization of the :class:`TestLoader` is needed, this instance can be used
1746 instead of repeatedly creating new instances.
1747
1748
Ezio Melotti9c939bc2013-05-07 09:46:30 +03001749.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \
1750 buffer=False, resultclass=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001751
Michael Foordd218e952011-01-03 12:55:11 +00001752 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001753 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001754 has a few configurable parameters, but is essentially very simple. Graphical
1755 applications which run test suites should provide alternate implementations.
1756
Ezio Melotti60901872010-12-01 00:56:10 +00001757 By default this runner shows :exc:`DeprecationWarning`,
1758 :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` even if they are
1759 :ref:`ignored by default <warning-ignored>`. Deprecation warnings caused by
1760 :ref:`deprecated unittest methods <deprecated-aliases>` are also
1761 special-cased and, when the warning filters are ``'default'`` or ``'always'``,
1762 they will appear only once per-module, in order to avoid too many warning
Georg Brandl46402372010-12-04 19:06:18 +00001763 messages. This behavior can be overridden using the :option:`-Wd` or
Ezio Melotti60901872010-12-01 00:56:10 +00001764 :option:`-Wa` options and leaving *warnings* to ``None``.
1765
Michael Foordd218e952011-01-03 12:55:11 +00001766 .. versionchanged:: 3.2
1767 Added the ``warnings`` argument.
1768
1769 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001770 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001771 than import time.
1772
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001773 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001774
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001775 This method returns the instance of ``TestResult`` used by :meth:`run`.
1776 It is not intended to be called directly, but can be overridden in
1777 subclasses to provide a custom ``TestResult``.
1778
Michael Foord34c94622010-02-10 15:51:42 +00001779 ``_makeResult()`` instantiates the class or callable passed in the
1780 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001781 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001782 The result class is instantiated with the following arguments::
1783
1784 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001785
Ezio Melotti60901872010-12-01 00:56:10 +00001786
Georg Brandl419e3de2010-12-01 15:44:25 +00001787.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02001788 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00001789 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001790
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001791 A command-line program that loads a set of tests from *module* and runs them;
1792 this is primarily for making test modules conveniently executable.
1793 The simplest use for this function is to include the following line at the
1794 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00001795
1796 if __name__ == '__main__':
1797 unittest.main()
1798
Benjamin Petersond2397752009-06-27 23:45:02 +00001799 You can run tests with more detailed information by passing in the verbosity
1800 argument::
1801
1802 if __name__ == '__main__':
1803 unittest.main(verbosity=2)
1804
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001805 The *argv* argument can be a list of options passed to the program, with the
1806 first element being the program name. If not specified or ``None``,
1807 the values of :data:`sys.argv` are used.
1808
Georg Brandl116aa622007-08-15 14:28:22 +00001809 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001810 created instance of it. By default ``main`` calls :func:`sys.exit` with
1811 an exit code indicating success or failure of the tests run.
1812
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001813 The *testLoader* argument has to be a :class:`TestLoader` instance,
1814 and defaults to :data:`defaultTestLoader`.
1815
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001816 ``main`` supports being used from the interactive interpreter by passing in the
1817 argument ``exit=False``. This displays the result on standard output without
1818 calling :func:`sys.exit`::
1819
1820 >>> from unittest import main
1821 >>> main(module='test_module', exit=False)
1822
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001823 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00001824 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001825
Ezio Melotti60901872010-12-01 00:56:10 +00001826 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
1827 that should be used while running the tests. If it's not specified, it will
1828 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
1829 otherwise it will be set to ``'default'``.
1830
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001831 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1832 This stores the result of the tests run as the ``result`` attribute.
1833
Éric Araujo971dc012010-12-16 03:13:05 +00001834 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001835 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00001836
Georg Brandl853947a2010-01-31 18:53:23 +00001837 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001838 The *verbosity*, *failfast*, *catchbreak*, *buffer*
1839 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001840
1841
1842load_tests Protocol
1843###################
1844
Georg Brandl853947a2010-01-31 18:53:23 +00001845.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001846
Benjamin Petersond2397752009-06-27 23:45:02 +00001847Modules or packages can customize how tests are loaded from them during normal
1848test runs or test discovery by implementing a function called ``load_tests``.
1849
1850If a test module defines ``load_tests`` it will be called by
1851:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1852
1853 load_tests(loader, standard_tests, None)
1854
1855It should return a :class:`TestSuite`.
1856
1857*loader* is the instance of :class:`TestLoader` doing the loading.
1858*standard_tests* are the tests that would be loaded by default from the
1859module. It is common for test modules to only want to add or remove tests
1860from the standard set of tests.
1861The third argument is used when loading packages as part of test discovery.
1862
1863A typical ``load_tests`` function that loads tests from a specific set of
1864:class:`TestCase` classes may look like::
1865
1866 test_cases = (TestCase1, TestCase2, TestCase3)
1867
1868 def load_tests(loader, tests, pattern):
1869 suite = TestSuite()
1870 for test_class in test_cases:
1871 tests = loader.loadTestsFromTestCase(test_class)
1872 suite.addTests(tests)
1873 return suite
1874
1875If discovery is started, either from the command line or by calling
1876:meth:`TestLoader.discover`, with a pattern that matches a package
1877name then the package :file:`__init__.py` will be checked for ``load_tests``.
1878
1879.. note::
1880
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02001881 The default pattern is ``'test*.py'``. This matches all Python files
1882 that start with ``'test'`` but *won't* match any test directories.
Benjamin Petersond2397752009-06-27 23:45:02 +00001883
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02001884 A pattern like ``'test*'`` will match test packages as well as
Benjamin Petersond2397752009-06-27 23:45:02 +00001885 modules.
1886
1887If the package :file:`__init__.py` defines ``load_tests`` then it will be
1888called and discovery not continued into the package. ``load_tests``
1889is called with the following arguments::
1890
1891 load_tests(loader, standard_tests, pattern)
1892
1893This should return a :class:`TestSuite` representing all the tests
1894from the package. (``standard_tests`` will only contain tests
1895collected from :file:`__init__.py`.)
1896
1897Because the pattern is passed into ``load_tests`` the package is free to
1898continue (and potentially modify) test discovery. A 'do nothing'
1899``load_tests`` function for a test package would look like::
1900
1901 def load_tests(loader, standard_tests, pattern):
1902 # top level directory cached on loader instance
1903 this_dir = os.path.dirname(__file__)
1904 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1905 standard_tests.addTests(package_tests)
1906 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00001907
1908
1909Class and Module Fixtures
1910-------------------------
1911
1912Class and module level fixtures are implemented in :class:`TestSuite`. When
1913the test suite encounters a test from a new class then :meth:`tearDownClass`
1914from the previous class (if there is one) is called, followed by
1915:meth:`setUpClass` from the new class.
1916
1917Similarly if a test is from a different module from the previous test then
1918``tearDownModule`` from the previous module is run, followed by
1919``setUpModule`` from the new module.
1920
1921After all the tests have run the final ``tearDownClass`` and
1922``tearDownModule`` are run.
1923
1924Note that shared fixtures do not play well with [potential] features like test
1925parallelization and they break test isolation. They should be used with care.
1926
1927The default ordering of tests created by the unittest test loaders is to group
1928all tests from the same modules and classes together. This will lead to
1929``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
1930module. If you randomize the order, so that tests from different modules and
1931classes are adjacent to each other, then these shared fixture functions may be
1932called multiple times in a single test run.
1933
1934Shared fixtures are not intended to work with suites with non-standard
1935ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
1936support shared fixtures.
1937
1938If there are any exceptions raised during one of the shared fixture functions
1939the test is reported as an error. Because there is no corresponding test
1940instance an ``_ErrorHolder`` object (that has the same interface as a
1941:class:`TestCase`) is created to represent the error. If you are just using
1942the standard unittest test runner then this detail doesn't matter, but if you
1943are a framework author it may be relevant.
1944
1945
1946setUpClass and tearDownClass
1947~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1948
1949These must be implemented as class methods::
1950
1951 import unittest
1952
1953 class Test(unittest.TestCase):
1954 @classmethod
1955 def setUpClass(cls):
1956 cls._connection = createExpensiveConnectionObject()
1957
1958 @classmethod
1959 def tearDownClass(cls):
1960 cls._connection.destroy()
1961
1962If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
1963then you must call up to them yourself. The implementations in
1964:class:`TestCase` are empty.
1965
1966If an exception is raised during a ``setUpClass`` then the tests in the class
1967are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00001968have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02001969:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00001970instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001971
1972
1973setUpModule and tearDownModule
1974~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1975
1976These should be implemented as functions::
1977
1978 def setUpModule():
1979 createConnection()
1980
1981 def tearDownModule():
1982 closeConnection()
1983
1984If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00001985module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02001986:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00001987instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001988
1989
1990Signal Handling
1991---------------
1992
Georg Brandl419e3de2010-12-01 15:44:25 +00001993.. versionadded:: 3.2
1994
Éric Araujo8acb67c2010-11-26 23:31:07 +00001995The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00001996along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
1997more friendly handling of control-C during a test run. With catch break
1998behavior enabled control-C will allow the currently running test to complete,
1999and the test run will then end and report all the results so far. A second
2000control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002001
Michael Foordde4ceab2010-04-25 19:53:49 +00002002The control-c handling signal handler attempts to remain compatible with code or
2003tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2004handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2005i.e. it has been replaced by the system under test and delegated to, then it
2006calls the default handler. This will normally be the expected behavior by code
2007that replaces an installed handler and delegates to it. For individual tests
2008that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2009decorator can be used.
2010
2011There are a few utility functions for framework authors to enable control-c
2012handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002013
2014.. function:: installHandler()
2015
2016 Install the control-c handler. When a :const:`signal.SIGINT` is received
2017 (usually in response to the user pressing control-c) all registered results
2018 have :meth:`~TestResult.stop` called.
2019
Michael Foord469b1f02010-04-26 23:41:26 +00002020
Benjamin Petersonb48af542010-04-11 20:43:16 +00002021.. function:: registerResult(result)
2022
2023 Register a :class:`TestResult` object for control-c handling. Registering a
2024 result stores a weak reference to it, so it doesn't prevent the result from
2025 being garbage collected.
2026
Michael Foordde4ceab2010-04-25 19:53:49 +00002027 Registering a :class:`TestResult` object has no side-effects if control-c
2028 handling is not enabled, so test frameworks can unconditionally register
2029 all results they create independently of whether or not handling is enabled.
2030
Michael Foord469b1f02010-04-26 23:41:26 +00002031
Benjamin Petersonb48af542010-04-11 20:43:16 +00002032.. function:: removeResult(result)
2033
2034 Remove a registered result. Once a result has been removed then
2035 :meth:`~TestResult.stop` will no longer be called on that result object in
2036 response to a control-c.
2037
Michael Foord469b1f02010-04-26 23:41:26 +00002038
Michael Foordde4ceab2010-04-25 19:53:49 +00002039.. function:: removeHandler(function=None)
2040
2041 When called without arguments this function removes the control-c handler
2042 if it has been installed. This function can also be used as a test decorator
2043 to temporarily remove the handler whilst the test is being executed::
2044
2045 @unittest.removeHandler
2046 def test_signal_handling(self):
2047 ...