blob: 92dd8dc3b77f24935a8e6de66a8cba565fe2cdb2 [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
533 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
534
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
Benjamin Petersonb48af542010-04-11 20:43:16 +0000555Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
556Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
557
Benjamin Peterson5254c042009-03-23 22:25:03 +0000558
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100559.. _subtests:
560
561Distinguishing test iterations using subtests
562---------------------------------------------
563
564.. versionadded:: 3.4
565
566When some of your tests differ only by a some very small differences, for
567instance some parameters, unittest allows you to distinguish them inside
568the body of a test method using the :meth:`~TestCase.subTest` context manager.
569
570For example, the following test::
571
572 class NumbersTest(unittest.TestCase):
573
574 def test_even(self):
575 """
576 Test that numbers between 0 and 5 are all even.
577 """
578 for i in range(0, 6):
579 with self.subTest(i=i):
580 self.assertEqual(i % 2, 0)
581
582will produce the following output::
583
584 ======================================================================
585 FAIL: test_even (__main__.NumbersTest) (i=1)
586 ----------------------------------------------------------------------
587 Traceback (most recent call last):
588 File "subtests.py", line 32, in test_even
589 self.assertEqual(i % 2, 0)
590 AssertionError: 1 != 0
591
592 ======================================================================
593 FAIL: test_even (__main__.NumbersTest) (i=3)
594 ----------------------------------------------------------------------
595 Traceback (most recent call last):
596 File "subtests.py", line 32, in test_even
597 self.assertEqual(i % 2, 0)
598 AssertionError: 1 != 0
599
600 ======================================================================
601 FAIL: test_even (__main__.NumbersTest) (i=5)
602 ----------------------------------------------------------------------
603 Traceback (most recent call last):
604 File "subtests.py", line 32, in test_even
605 self.assertEqual(i % 2, 0)
606 AssertionError: 1 != 0
607
608Without using a subtest, execution would stop after the first failure,
609and the error would be less easy to diagnose because the value of ``i``
610wouldn't be displayed::
611
612 ======================================================================
613 FAIL: test_even (__main__.NumbersTest)
614 ----------------------------------------------------------------------
615 Traceback (most recent call last):
616 File "subtests.py", line 32, in test_even
617 self.assertEqual(i % 2, 0)
618 AssertionError: 1 != 0
619
620
Georg Brandl116aa622007-08-15 14:28:22 +0000621.. _unittest-contents:
622
623Classes and functions
624---------------------
625
Benjamin Peterson52baa292009-03-24 00:56:30 +0000626This section describes in depth the API of :mod:`unittest`.
627
628
629.. _testcase-objects:
630
631Test cases
632~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000633
Georg Brandl7f01a132009-09-16 15:58:14 +0000634.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000635
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100636 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000637 in the :mod:`unittest` universe. This class is intended to be used as a base
638 class, with specific tests being implemented by concrete subclasses. This class
639 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100640 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000641 kinds of failure.
642
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100643 Each instance of :class:`TestCase` will run a single base method: the method
644 named *methodName*. However, the standard implementation of the default
645 *methodName*, ``runTest()``, will run every method starting with ``test``
646 as an individual test, and count successes and failures accordingly.
647 Therefore, in most uses of :class:`TestCase`, you will neither change
648 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Michael Foord1341bb02011-03-14 19:01:46 -0400650 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100651 :class:`TestCase` can be instantiated successfully without providing a
652 *methodName*. This makes it easier to experiment with :class:`TestCase`
653 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000654
655 :class:`TestCase` instances provide three groups of methods: one group used
656 to run the test, another used by the test implementation to check conditions
657 and report failures, and some inquiry methods allowing information about the
658 test itself to be gathered.
659
660 Methods in the first group (running the test) are:
661
Benjamin Peterson52baa292009-03-24 00:56:30 +0000662 .. method:: setUp()
663
664 Method called to prepare the test fixture. This is called immediately
665 before calling the test method; any exception raised by this method will
666 be considered an error rather than a test failure. The default
667 implementation does nothing.
668
669
670 .. method:: tearDown()
671
672 Method called immediately after the test method has been called and the
673 result recorded. This is called even if the test method raised an
674 exception, so the implementation in subclasses may need to be particularly
675 careful about checking internal state. Any exception raised by this
676 method will be considered an error rather than a test failure. This
677 method will only be called if the :meth:`setUp` succeeds, regardless of
678 the outcome of the test method. The default implementation does nothing.
679
680
Benjamin Petersonb48af542010-04-11 20:43:16 +0000681 .. method:: setUpClass()
682
683 A class method called before tests in an individual class run.
684 ``setUpClass`` is called with the class as the only argument
685 and must be decorated as a :func:`classmethod`::
686
687 @classmethod
688 def setUpClass(cls):
689 ...
690
691 See `Class and Module Fixtures`_ for more details.
692
693 .. versionadded:: 3.2
694
695
696 .. method:: tearDownClass()
697
698 A class method called after tests in an individual class have run.
699 ``tearDownClass`` is called with the class as the only argument
700 and must be decorated as a :meth:`classmethod`::
701
702 @classmethod
703 def tearDownClass(cls):
704 ...
705
706 See `Class and Module Fixtures`_ for more details.
707
708 .. versionadded:: 3.2
709
710
Georg Brandl7f01a132009-09-16 15:58:14 +0000711 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000712
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100713 Run the test, collecting the result into the :class:`TestResult` object
714 passed as *result*. If *result* is omitted or ``None``, a temporary
715 result object is created (by calling the :meth:`defaultTestResult`
716 method) and used. The result object is returned to :meth:`run`'s
717 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000718
719 The same effect may be had by simply calling the :class:`TestCase`
720 instance.
721
Michael Foord1341bb02011-03-14 19:01:46 -0400722 .. versionchanged:: 3.3
723 Previous versions of ``run`` did not return the result. Neither did
724 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000725
Benjamin Petersone549ead2009-03-28 21:42:05 +0000726 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000727
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000728 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000729 test. See :ref:`unittest-skipping` for more information.
730
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000731 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000732
Benjamin Peterson52baa292009-03-24 00:56:30 +0000733
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100734 .. method:: subTest(msg=None, **params)
735
736 Return a context manager which executes the enclosed code block as a
737 subtest. *msg* and *params* are optional, arbitrary values which are
738 displayed whenever a subtest fails, allowing you to identify them
739 clearly.
740
741 A test case can contain any number of subtest declarations, and
742 they can be arbitrarily nested.
743
744 See :ref:`subtests` for more information.
745
746 .. versionadded:: 3.4
747
748
Benjamin Peterson52baa292009-03-24 00:56:30 +0000749 .. method:: debug()
750
751 Run the test without collecting the result. This allows exceptions raised
752 by the test to be propagated to the caller, and can be used to support
753 running tests under a debugger.
754
Ezio Melotti22170ed2010-11-20 09:57:27 +0000755 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000756
Ezio Melotti4370b302010-11-03 20:39:14 +0000757 The :class:`TestCase` class provides a number of methods to check for and
758 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000759
Ezio Melotti4370b302010-11-03 20:39:14 +0000760 +-----------------------------------------+-----------------------------+---------------+
761 | Method | Checks that | New in |
762 +=========================================+=============================+===============+
763 | :meth:`assertEqual(a, b) | ``a == b`` | |
764 | <TestCase.assertEqual>` | | |
765 +-----------------------------------------+-----------------------------+---------------+
766 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
767 | <TestCase.assertNotEqual>` | | |
768 +-----------------------------------------+-----------------------------+---------------+
769 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
770 | <TestCase.assertTrue>` | | |
771 +-----------------------------------------+-----------------------------+---------------+
772 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
773 | <TestCase.assertFalse>` | | |
774 +-----------------------------------------+-----------------------------+---------------+
775 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
776 | <TestCase.assertIs>` | | |
777 +-----------------------------------------+-----------------------------+---------------+
778 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
779 | <TestCase.assertIsNot>` | | |
780 +-----------------------------------------+-----------------------------+---------------+
781 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
782 | <TestCase.assertIsNone>` | | |
783 +-----------------------------------------+-----------------------------+---------------+
784 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
785 | <TestCase.assertIsNotNone>` | | |
786 +-----------------------------------------+-----------------------------+---------------+
787 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
788 | <TestCase.assertIn>` | | |
789 +-----------------------------------------+-----------------------------+---------------+
790 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
791 | <TestCase.assertNotIn>` | | |
792 +-----------------------------------------+-----------------------------+---------------+
793 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
794 | <TestCase.assertIsInstance>` | | |
795 +-----------------------------------------+-----------------------------+---------------+
796 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
797 | <TestCase.assertNotIsInstance>` | | |
798 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000799
Ezio Melottib4dc2502011-05-06 15:01:41 +0300800 All the assert methods accept a *msg* argument that, if specified, is used
801 as the error message on failure (see also :data:`longMessage`).
802 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
803 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
804 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000805
Michael Foorde180d392011-01-28 19:51:48 +0000806 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000807
Michael Foorde180d392011-01-28 19:51:48 +0000808 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000809 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000810
Michael Foorde180d392011-01-28 19:51:48 +0000811 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000812 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200813 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000814 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000815 error message (see also the :ref:`list of type-specific methods
816 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000817
Raymond Hettinger35a88362009-04-09 00:08:24 +0000818 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200819 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000820
Michael Foord28a817e2010-02-09 00:03:57 +0000821 .. versionchanged:: 3.2
822 :meth:`assertMultiLineEqual` added as the default type equality
823 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000824
Benjamin Peterson52baa292009-03-24 00:56:30 +0000825
Michael Foorde180d392011-01-28 19:51:48 +0000826 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000827
Michael Foorde180d392011-01-28 19:51:48 +0000828 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000829 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000830
Ezio Melotti4370b302010-11-03 20:39:14 +0000831 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000832 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000833
Ezio Melotti4841fd62010-11-05 15:43:40 +0000834 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000835
Ezio Melotti4841fd62010-11-05 15:43:40 +0000836 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
837 is True`` (use ``assertIs(expr, True)`` for the latter). This method
838 should also be avoided when more specific methods are available (e.g.
839 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
840 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000841
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000842
Michael Foorde180d392011-01-28 19:51:48 +0000843 .. method:: assertIs(first, second, msg=None)
844 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000845
Michael Foorde180d392011-01-28 19:51:48 +0000846 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000847 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000848
Raymond Hettinger35a88362009-04-09 00:08:24 +0000849 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000850
851
Ezio Melotti4370b302010-11-03 20:39:14 +0000852 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000853 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000854
Ezio Melotti9794a262010-11-04 14:52:13 +0000855 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000856
Ezio Melotti4370b302010-11-03 20:39:14 +0000857 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000858
859
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000860 .. method:: assertIn(first, second, msg=None)
861 assertNotIn(first, second, msg=None)
862
Ezio Melotti4841fd62010-11-05 15:43:40 +0000863 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000864
Raymond Hettinger35a88362009-04-09 00:08:24 +0000865 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000866
867
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000868 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000869 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000870
Ezio Melotti9794a262010-11-04 14:52:13 +0000871 Test that *obj* is (or is not) an instance of *cls* (which can be a
872 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200873 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000874
Ezio Melotti4370b302010-11-03 20:39:14 +0000875 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000876
877
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000878
Ezio Melotti4370b302010-11-03 20:39:14 +0000879 It is also possible to check that exceptions and warnings are raised using
880 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000881
Ezio Melotti4370b302010-11-03 20:39:14 +0000882 +---------------------------------------------------------+--------------------------------------+------------+
883 | Method | Checks that | New in |
884 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200885 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000886 | <TestCase.assertRaises>` | | |
887 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200888 | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
889 | <TestCase.assertRaisesRegex>` | and the message matches *re* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000890 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200891 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000892 | <TestCase.assertWarns>` | | |
893 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200894 | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
895 | <TestCase.assertWarnsRegex>` | and the message matches *re* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000896 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000897
Georg Brandl7f01a132009-09-16 15:58:14 +0000898 .. method:: assertRaises(exception, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300899 assertRaises(exception, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000900
901 Test that an exception is raised when *callable* is called with any
902 positional or keyword arguments that are also passed to
903 :meth:`assertRaises`. The test passes if *exception* is raised, is an
904 error if another exception is raised, or fails if no exception is raised.
905 To catch any of a group of exceptions, a tuple containing the exception
906 classes may be passed as *exception*.
907
Ezio Melottib4dc2502011-05-06 15:01:41 +0300908 If only the *exception* and possibly the *msg* arguments are given,
909 return a context manager so that the code under test can be written
910 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000911
Michael Foord41531f22010-02-05 21:13:40 +0000912 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000913 do_something()
914
Ezio Melottib4dc2502011-05-06 15:01:41 +0300915 When used as a context manager, :meth:`assertRaises` accepts the
916 additional keyword argument *msg*.
917
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000918 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000919 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000920 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000921
Georg Brandl8a1caa22010-07-29 16:01:11 +0000922 with self.assertRaises(SomeException) as cm:
923 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000924
Georg Brandl8a1caa22010-07-29 16:01:11 +0000925 the_exception = cm.exception
926 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000927
Ezio Melotti49008232010-02-08 21:57:48 +0000928 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000929 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000930
Ezio Melotti49008232010-02-08 21:57:48 +0000931 .. versionchanged:: 3.2
932 Added the :attr:`exception` attribute.
933
Ezio Melottib4dc2502011-05-06 15:01:41 +0300934 .. versionchanged:: 3.3
935 Added the *msg* keyword argument when used as a context manager.
936
Benjamin Peterson52baa292009-03-24 00:56:30 +0000937
Ezio Melottied3a7d22010-12-01 02:32:32 +0000938 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300939 assertRaisesRegex(exception, regex, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000940
Ezio Melottied3a7d22010-12-01 02:32:32 +0000941 Like :meth:`assertRaises` but also tests that *regex* matches
942 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000943 a regular expression object or a string containing a regular expression
944 suitable for use by :func:`re.search`. Examples::
945
Ezio Melottied3a7d22010-12-01 02:32:32 +0000946 self.assertRaisesRegex(ValueError, 'invalid literal for.*XYZ$',
947 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000948
949 or::
950
Ezio Melottied3a7d22010-12-01 02:32:32 +0000951 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000952 int('XYZ')
953
Georg Brandl419e3de2010-12-01 15:44:25 +0000954 .. versionadded:: 3.1
955 under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +0300956
Ezio Melottied3a7d22010-12-01 02:32:32 +0000957 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +0000958 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000959
Ezio Melottib4dc2502011-05-06 15:01:41 +0300960 .. versionchanged:: 3.3
961 Added the *msg* keyword argument when used as a context manager.
962
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000963
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000964 .. method:: assertWarns(warning, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300965 assertWarns(warning, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000966
967 Test that a warning is triggered when *callable* is called with any
968 positional or keyword arguments that are also passed to
969 :meth:`assertWarns`. The test passes if *warning* is triggered and
970 fails if it isn't. Also, any unexpected exception is an error.
971 To catch any of a group of warnings, a tuple containing the warning
972 classes may be passed as *warnings*.
973
Ezio Melottib4dc2502011-05-06 15:01:41 +0300974 If only the *warning* and possibly the *msg* arguments are given,
975 returns a context manager so that the code under test can be written
976 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000977
978 with self.assertWarns(SomeWarning):
979 do_something()
980
Ezio Melottib4dc2502011-05-06 15:01:41 +0300981 When used as a context manager, :meth:`assertRaises` accepts the
982 additional keyword argument *msg*.
983
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000984 The context manager will store the caught warning object in its
985 :attr:`warning` attribute, and the source line which triggered the
986 warnings in the :attr:`filename` and :attr:`lineno` attributes.
987 This can be useful if the intention is to perform additional checks
988 on the exception raised::
989
990 with self.assertWarns(SomeWarning) as cm:
991 do_something()
992
993 self.assertIn('myfile.py', cm.filename)
994 self.assertEqual(320, cm.lineno)
995
996 This method works regardless of the warning filters in place when it
997 is called.
998
999 .. versionadded:: 3.2
1000
Ezio Melottib4dc2502011-05-06 15:01:41 +03001001 .. versionchanged:: 3.3
1002 Added the *msg* keyword argument when used as a context manager.
1003
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001004
Ezio Melottied3a7d22010-12-01 02:32:32 +00001005 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001006 assertWarnsRegex(warning, regex, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001007
Ezio Melottied3a7d22010-12-01 02:32:32 +00001008 Like :meth:`assertWarns` but also tests that *regex* matches on the
1009 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001010 object or a string containing a regular expression suitable for use
1011 by :func:`re.search`. Example::
1012
Ezio Melottied3a7d22010-12-01 02:32:32 +00001013 self.assertWarnsRegex(DeprecationWarning,
1014 r'legacy_function\(\) is deprecated',
1015 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001016
1017 or::
1018
Ezio Melottied3a7d22010-12-01 02:32:32 +00001019 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001020 frobnicate('/etc/passwd')
1021
1022 .. versionadded:: 3.2
1023
Ezio Melottib4dc2502011-05-06 15:01:41 +03001024 .. versionchanged:: 3.3
1025 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001026
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001027
Ezio Melotti4370b302010-11-03 20:39:14 +00001028 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001029
Ezio Melotti4370b302010-11-03 20:39:14 +00001030 +---------------------------------------+--------------------------------+--------------+
1031 | Method | Checks that | New in |
1032 +=======================================+================================+==============+
1033 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1034 | <TestCase.assertAlmostEqual>` | | |
1035 +---------------------------------------+--------------------------------+--------------+
1036 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1037 | <TestCase.assertNotAlmostEqual>` | | |
1038 +---------------------------------------+--------------------------------+--------------+
1039 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1040 | <TestCase.assertGreater>` | | |
1041 +---------------------------------------+--------------------------------+--------------+
1042 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1043 | <TestCase.assertGreaterEqual>` | | |
1044 +---------------------------------------+--------------------------------+--------------+
1045 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1046 | <TestCase.assertLess>` | | |
1047 +---------------------------------------+--------------------------------+--------------+
1048 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1049 | <TestCase.assertLessEqual>` | | |
1050 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001051 | :meth:`assertRegex(s, re) | ``regex.search(s)`` | 3.1 |
1052 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001053 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001054 | :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 |
1055 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001056 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001057 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001058 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001059 | | regardless of their order | |
1060 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001061
1062
Michael Foorde180d392011-01-28 19:51:48 +00001063 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1064 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001065
Michael Foorde180d392011-01-28 19:51:48 +00001066 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001067 equal by computing the difference, rounding to the given number of
1068 decimal *places* (default 7), and comparing to zero. Note that these
1069 methods round the values to the given number of *decimal places* (i.e.
1070 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001071
Ezio Melotti4370b302010-11-03 20:39:14 +00001072 If *delta* is supplied instead of *places* then the difference
Michael Foorde180d392011-01-28 19:51:48 +00001073 between *first* and *second* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001074
Ezio Melotti4370b302010-11-03 20:39:14 +00001075 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001076
Ezio Melotti4370b302010-11-03 20:39:14 +00001077 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001078 :meth:`assertAlmostEqual` automatically considers almost equal objects
1079 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1080 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001081
Ezio Melotti4370b302010-11-03 20:39:14 +00001082
Michael Foorde180d392011-01-28 19:51:48 +00001083 .. method:: assertGreater(first, second, msg=None)
1084 assertGreaterEqual(first, second, msg=None)
1085 assertLess(first, second, msg=None)
1086 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001087
Michael Foorde180d392011-01-28 19:51:48 +00001088 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001089 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001090
1091 >>> self.assertGreaterEqual(3, 4)
1092 AssertionError: "3" unexpectedly not greater than or equal to "4"
1093
1094 .. versionadded:: 3.1
1095
1096
Ezio Melottied3a7d22010-12-01 02:32:32 +00001097 .. method:: assertRegex(text, regex, msg=None)
1098 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001099
Ezio Melottied3a7d22010-12-01 02:32:32 +00001100 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001101 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001102 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001103 may be a regular expression object or a string containing a regular
1104 expression suitable for use by :func:`re.search`.
1105
Georg Brandl419e3de2010-12-01 15:44:25 +00001106 .. versionadded:: 3.1
1107 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001108 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001109 The method ``assertRegexpMatches()`` has been renamed to
1110 :meth:`.assertRegex`.
1111 .. versionadded:: 3.2
1112 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001113
1114
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001115 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001116
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001117 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001118 regardless of their order. When they don't, an error message listing the
1119 differences between the sequences will be generated.
1120
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001121 Duplicate elements are *not* ignored when comparing *first* and
1122 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001123 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001124 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001125 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001126
Ezio Melotti4370b302010-11-03 20:39:14 +00001127 .. versionadded:: 3.2
1128
Ezio Melotti4370b302010-11-03 20:39:14 +00001129
Ezio Melotti22170ed2010-11-20 09:57:27 +00001130 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001131
Ezio Melotti22170ed2010-11-20 09:57:27 +00001132 The :meth:`assertEqual` method dispatches the equality check for objects of
1133 the same type to different type-specific methods. These methods are already
1134 implemented for most of the built-in types, but it's also possible to
1135 register new methods using :meth:`addTypeEqualityFunc`:
1136
1137 .. method:: addTypeEqualityFunc(typeobj, function)
1138
1139 Registers a type-specific method called by :meth:`assertEqual` to check
1140 if two objects of exactly the same *typeobj* (not subclasses) compare
1141 equal. *function* must take two positional arguments and a third msg=None
1142 keyword argument just as :meth:`assertEqual` does. It must raise
1143 :data:`self.failureException(msg) <failureException>` when inequality
1144 between the first two parameters is detected -- possibly providing useful
1145 information and explaining the inequalities in details in the error
1146 message.
1147
1148 .. versionadded:: 3.1
1149
1150 The list of type-specific methods automatically used by
1151 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1152 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001153
1154 +-----------------------------------------+-----------------------------+--------------+
1155 | Method | Used to compare | New in |
1156 +=========================================+=============================+==============+
1157 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1158 | <TestCase.assertMultiLineEqual>` | | |
1159 +-----------------------------------------+-----------------------------+--------------+
1160 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1161 | <TestCase.assertSequenceEqual>` | | |
1162 +-----------------------------------------+-----------------------------+--------------+
1163 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1164 | <TestCase.assertListEqual>` | | |
1165 +-----------------------------------------+-----------------------------+--------------+
1166 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1167 | <TestCase.assertTupleEqual>` | | |
1168 +-----------------------------------------+-----------------------------+--------------+
1169 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1170 | <TestCase.assertSetEqual>` | | |
1171 +-----------------------------------------+-----------------------------+--------------+
1172 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1173 | <TestCase.assertDictEqual>` | | |
1174 +-----------------------------------------+-----------------------------+--------------+
1175
1176
1177
Michael Foorde180d392011-01-28 19:51:48 +00001178 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001179
Michael Foorde180d392011-01-28 19:51:48 +00001180 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001181 When not equal a diff of the two strings highlighting the differences
1182 will be included in the error message. This method is used by default
1183 when comparing strings with :meth:`assertEqual`.
1184
Ezio Melotti4370b302010-11-03 20:39:14 +00001185 .. versionadded:: 3.1
1186
1187
Michael Foorde180d392011-01-28 19:51:48 +00001188 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001189
1190 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001191 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001192 be raised. If the sequences are different an error message is
1193 constructed that shows the difference between the two.
1194
Ezio Melotti22170ed2010-11-20 09:57:27 +00001195 This method is not called directly by :meth:`assertEqual`, but
1196 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001197 :meth:`assertTupleEqual`.
1198
1199 .. versionadded:: 3.1
1200
1201
Michael Foorde180d392011-01-28 19:51:48 +00001202 .. method:: assertListEqual(first, second, msg=None)
1203 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001204
Ezio Melotti49ccd512012-08-29 17:50:42 +03001205 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001206 constructed that shows only the differences between the two. An error
1207 is also raised if either of the parameters are of the wrong type.
1208 These methods are used by default when comparing lists or tuples with
1209 :meth:`assertEqual`.
1210
Ezio Melotti4370b302010-11-03 20:39:14 +00001211 .. versionadded:: 3.1
1212
1213
Michael Foorde180d392011-01-28 19:51:48 +00001214 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001215
1216 Tests that two sets are equal. If not, an error message is constructed
1217 that lists the differences between the sets. This method is used by
1218 default when comparing sets or frozensets with :meth:`assertEqual`.
1219
Michael Foorde180d392011-01-28 19:51:48 +00001220 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001221 method.
1222
Ezio Melotti4370b302010-11-03 20:39:14 +00001223 .. versionadded:: 3.1
1224
1225
Michael Foorde180d392011-01-28 19:51:48 +00001226 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001227
1228 Test that two dictionaries are equal. If not, an error message is
1229 constructed that shows the differences in the dictionaries. This
1230 method will be used by default to compare dictionaries in
1231 calls to :meth:`assertEqual`.
1232
Ezio Melotti4370b302010-11-03 20:39:14 +00001233 .. versionadded:: 3.1
1234
1235
1236
Ezio Melotti22170ed2010-11-20 09:57:27 +00001237 .. _other-methods-and-attrs:
1238
Ezio Melotti4370b302010-11-03 20:39:14 +00001239 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001240
Benjamin Peterson52baa292009-03-24 00:56:30 +00001241
Georg Brandl7f01a132009-09-16 15:58:14 +00001242 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001243
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001244 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001245 the error message.
1246
1247
1248 .. attribute:: failureException
1249
1250 This class attribute gives the exception raised by the test method. If a
1251 test framework needs to use a specialized exception, possibly to carry
1252 additional information, it must subclass this exception in order to "play
1253 fair" with the framework. The initial value of this attribute is
1254 :exc:`AssertionError`.
1255
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001256
1257 .. attribute:: longMessage
1258
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001259 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001260 :ref:`assert methods <assert-methods>` will be appended to the end of the
1261 normal failure message. The normal messages contain useful information
1262 about the objects involved, for example the message from assertEqual
1263 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001264 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001265 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001266
Michael Foord5074df62010-12-03 00:53:09 +00001267 This attribute defaults to ``True``. If set to False then a custom message
1268 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001269
1270 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001271 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001272
Raymond Hettinger35a88362009-04-09 00:08:24 +00001273 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001274
1275
Michael Foord98b3e762010-06-05 21:59:55 +00001276 .. attribute:: maxDiff
1277
1278 This attribute controls the maximum length of diffs output by assert
1279 methods that report diffs on failure. It defaults to 80*8 characters.
1280 Assert methods affected by this attribute are
1281 :meth:`assertSequenceEqual` (including all the sequence comparison
1282 methods that delegate to it), :meth:`assertDictEqual` and
1283 :meth:`assertMultiLineEqual`.
1284
1285 Setting ``maxDiff`` to None means that there is no maximum length of
1286 diffs.
1287
1288 .. versionadded:: 3.2
1289
1290
Benjamin Peterson52baa292009-03-24 00:56:30 +00001291 Testing frameworks can use the following methods to collect information on
1292 the test:
1293
1294
1295 .. method:: countTestCases()
1296
1297 Return the number of tests represented by this test object. For
1298 :class:`TestCase` instances, this will always be ``1``.
1299
1300
1301 .. method:: defaultTestResult()
1302
1303 Return an instance of the test result class that should be used for this
1304 test case class (if no other result instance is provided to the
1305 :meth:`run` method).
1306
1307 For :class:`TestCase` instances, this will always be an instance of
1308 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1309 as necessary.
1310
1311
1312 .. method:: id()
1313
1314 Return a string identifying the specific test case. This is usually the
1315 full name of the test method, including the module and class name.
1316
1317
1318 .. method:: shortDescription()
1319
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001320 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001321 has been provided. The default implementation of this method
1322 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001323 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001324
Georg Brandl419e3de2010-12-01 15:44:25 +00001325 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001326 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001327 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001328 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001329 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001330
Georg Brandl116aa622007-08-15 14:28:22 +00001331
Georg Brandl7f01a132009-09-16 15:58:14 +00001332 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001333
1334 Add a function to be called after :meth:`tearDown` to cleanup resources
1335 used during the test. Functions will be called in reverse order to the
1336 order they are added (LIFO). They are called with any arguments and
1337 keyword arguments passed into :meth:`addCleanup` when they are
1338 added.
1339
1340 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1341 then any cleanup functions added will still be called.
1342
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001343 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001344
1345
1346 .. method:: doCleanups()
1347
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001348 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001349 after :meth:`setUp` if :meth:`setUp` raises an exception.
1350
1351 It is responsible for calling all the cleanup functions added by
1352 :meth:`addCleanup`. If you need cleanup functions to be called
1353 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1354 yourself.
1355
1356 :meth:`doCleanups` pops methods off the stack of cleanup
1357 functions one at a time, so it can be called at any time.
1358
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001359 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001360
1361
Georg Brandl7f01a132009-09-16 15:58:14 +00001362.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001363
1364 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001365 allows the test runner to drive the test, but does not provide the methods
1366 which test code can use to check and report errors. This is used to create
1367 test cases using legacy test code, allowing it to be integrated into a
1368 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001369
1370
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001371.. _deprecated-aliases:
1372
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001373Deprecated aliases
1374##################
1375
1376For historical reasons, some of the :class:`TestCase` methods had one or more
1377aliases that are now deprecated. The following table lists the correct names
1378along with their deprecated aliases:
1379
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001380 ============================== ====================== ======================
1381 Method Name Deprecated alias Deprecated alias
1382 ============================== ====================== ======================
1383 :meth:`.assertEqual` failUnlessEqual assertEquals
1384 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1385 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001386 :meth:`.assertFalse` failIf
1387 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001388 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1389 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001390 :meth:`.assertRegex` assertRegexpMatches
1391 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001392 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001393
Ezio Melotti361467e2011-04-03 17:37:58 +03001394 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001395 the fail* aliases listed in the second column.
1396 .. deprecated:: 3.2
1397 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001398 .. deprecated:: 3.2
1399 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1400 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001401
1402
Benjamin Peterson52baa292009-03-24 00:56:30 +00001403.. _testsuite-objects:
1404
Benjamin Peterson52baa292009-03-24 00:56:30 +00001405Grouping tests
1406~~~~~~~~~~~~~~
1407
Georg Brandl7f01a132009-09-16 15:58:14 +00001408.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001409
1410 This class represents an aggregation of individual tests cases and test suites.
1411 The class presents the interface needed by the test runner to allow it to be run
1412 as any other test case. Running a :class:`TestSuite` instance is the same as
1413 iterating over the suite, running each test individually.
1414
1415 If *tests* is given, it must be an iterable of individual test cases or other
1416 test suites that will be used to build the suite initially. Additional methods
1417 are provided to add test cases and suites to the collection later on.
1418
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001419 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1420 they do not actually implement a test. Instead, they are used to aggregate
1421 tests into groups of tests that should be run together. Some additional
1422 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001423
1424
1425 .. method:: TestSuite.addTest(test)
1426
1427 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1428
1429
1430 .. method:: TestSuite.addTests(tests)
1431
1432 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1433 instances to this test suite.
1434
Benjamin Petersond2397752009-06-27 23:45:02 +00001435 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1436 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001437
1438 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1439
1440
1441 .. method:: run(result)
1442
1443 Run the tests associated with this suite, collecting the result into the
1444 test result object passed as *result*. Note that unlike
1445 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1446 be passed in.
1447
1448
1449 .. method:: debug()
1450
1451 Run the tests associated with this suite without collecting the
1452 result. This allows exceptions raised by the test to be propagated to the
1453 caller and can be used to support running tests under a debugger.
1454
1455
1456 .. method:: countTestCases()
1457
1458 Return the number of tests represented by this test object, including all
1459 individual tests and sub-suites.
1460
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001461
1462 .. method:: __iter__()
1463
1464 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1465 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1466 that this method maybe called several times on a single suite
1467 (for example when counting tests or comparing for equality)
1468 so the tests returned must be the same for repeated iterations.
1469
Georg Brandl853947a2010-01-31 18:53:23 +00001470 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001471 In earlier versions the :class:`TestSuite` accessed tests directly rather
1472 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1473 for providing tests.
1474
Benjamin Peterson52baa292009-03-24 00:56:30 +00001475 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1476 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1477
1478
Benjamin Peterson52baa292009-03-24 00:56:30 +00001479Loading and running tests
1480~~~~~~~~~~~~~~~~~~~~~~~~~
1481
Georg Brandl116aa622007-08-15 14:28:22 +00001482.. class:: TestLoader()
1483
Benjamin Peterson52baa292009-03-24 00:56:30 +00001484 The :class:`TestLoader` class is used to create test suites from classes and
1485 modules. Normally, there is no need to create an instance of this class; the
1486 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001487 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1488 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001489
1490 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001491
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001492
Benjamin Peterson52baa292009-03-24 00:56:30 +00001493 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001494
Benjamin Peterson52baa292009-03-24 00:56:30 +00001495 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1496 :class:`testCaseClass`.
1497
1498
1499 .. method:: loadTestsFromModule(module)
1500
1501 Return a suite of all tests cases contained in the given module. This
1502 method searches *module* for classes derived from :class:`TestCase` and
1503 creates an instance of the class for each test method defined for the
1504 class.
1505
Georg Brandle720c0a2009-04-27 16:20:50 +00001506 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001507
1508 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1509 convenient in sharing fixtures and helper functions, defining test
1510 methods on base classes that are not intended to be instantiated
1511 directly does not play well with this method. Doing so, however, can
1512 be useful when the fixtures are different and defined in subclasses.
1513
Benjamin Petersond2397752009-06-27 23:45:02 +00001514 If a module provides a ``load_tests`` function it will be called to
1515 load the tests. This allows modules to customize test loading.
1516 This is the `load_tests protocol`_.
1517
Georg Brandl853947a2010-01-31 18:53:23 +00001518 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001519 Support for ``load_tests`` added.
1520
Benjamin Peterson52baa292009-03-24 00:56:30 +00001521
Georg Brandl7f01a132009-09-16 15:58:14 +00001522 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001523
1524 Return a suite of all tests cases given a string specifier.
1525
1526 The specifier *name* is a "dotted name" that may resolve either to a
1527 module, a test case class, a test method within a test case class, a
1528 :class:`TestSuite` instance, or a callable object which returns a
1529 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1530 applied in the order listed here; that is, a method on a possible test
1531 case class will be picked up as "a test method within a test case class",
1532 rather than "a callable object".
1533
1534 For example, if you have a module :mod:`SampleTests` containing a
1535 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1536 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001537 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1538 return a suite which will run all three test methods. Using the specifier
1539 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1540 suite which will run only the :meth:`test_two` test method. The specifier
1541 can refer to modules and packages which have not been imported; they will
1542 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001543
1544 The method optionally resolves *name* relative to the given *module*.
1545
1546
Georg Brandl7f01a132009-09-16 15:58:14 +00001547 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001548
1549 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1550 than a single name. The return value is a test suite which supports all
1551 the tests defined for each name.
1552
1553
1554 .. method:: getTestCaseNames(testCaseClass)
1555
1556 Return a sorted sequence of method names found within *testCaseClass*;
1557 this should be a subclass of :class:`TestCase`.
1558
Benjamin Petersond2397752009-06-27 23:45:02 +00001559
1560 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1561
1562 Find and return all test modules from the specified start directory,
1563 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001564 *pattern* will be loaded. (Using shell style pattern matching.) Only
1565 module names that are importable (i.e. are valid Python identifiers) will
1566 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001567
1568 All test modules must be importable from the top level of the project. If
1569 the start directory is not the top level directory then the top level
1570 directory must be specified separately.
1571
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001572 If importing a module fails, for example due to a syntax error, then this
Ezio Melottieae2b382013-03-01 14:47:50 +02001573 will be recorded as a single error and discovery will continue. If the
1574 import failure is due to ``SkipTest`` being raised, it will be recorded
1575 as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001576
Benjamin Petersond2397752009-06-27 23:45:02 +00001577 If a test package name (directory with :file:`__init__.py`) matches the
1578 pattern then the package will be checked for a ``load_tests``
1579 function. If this exists then it will be called with *loader*, *tests*,
1580 *pattern*.
1581
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001582 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001583 ``load_tests`` is responsible for loading all tests in the package.
1584
1585 The pattern is deliberately not stored as a loader attribute so that
1586 packages can continue discovery themselves. *top_level_dir* is stored so
1587 ``load_tests`` does not need to pass this argument in to
1588 ``loader.discover()``.
1589
Benjamin Petersonb48af542010-04-11 20:43:16 +00001590 *start_dir* can be a dotted module name as well as a directory.
1591
Georg Brandl853947a2010-01-31 18:53:23 +00001592 .. versionadded:: 3.2
1593
Ezio Melottieae2b382013-03-01 14:47:50 +02001594 .. versionchanged:: 3.4
1595 Modules that raise ``SkipTest`` on import are recorded as skips, not
1596 errors.
1597
Michael Foord80cbc9e2013-03-18 17:50:12 -07001598 .. versionchanged:: 3.4
1599 Paths are sorted before being imported to ensure execution order for a
1600 given test suite is the same even if the underlying file system's ordering
1601 is not dependent on file name like in ext3/4.
1602
Benjamin Petersond2397752009-06-27 23:45:02 +00001603
Benjamin Peterson52baa292009-03-24 00:56:30 +00001604 The following attributes of a :class:`TestLoader` can be configured either by
1605 subclassing or assignment on an instance:
1606
1607
1608 .. attribute:: testMethodPrefix
1609
1610 String giving the prefix of method names which will be interpreted as test
1611 methods. The default value is ``'test'``.
1612
1613 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1614 methods.
1615
1616
1617 .. attribute:: sortTestMethodsUsing
1618
1619 Function to be used to compare method names when sorting them in
1620 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1621
1622
1623 .. attribute:: suiteClass
1624
1625 Callable object that constructs a test suite from a list of tests. No
1626 methods on the resulting object are needed. The default value is the
1627 :class:`TestSuite` class.
1628
1629 This affects all the :meth:`loadTestsFrom\*` methods.
1630
1631
Benjamin Peterson52baa292009-03-24 00:56:30 +00001632.. class:: TestResult
1633
1634 This class is used to compile information about which tests have succeeded
1635 and which have failed.
1636
1637 A :class:`TestResult` object stores the results of a set of tests. The
1638 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1639 properly recorded; test authors do not need to worry about recording the
1640 outcome of tests.
1641
1642 Testing frameworks built on top of :mod:`unittest` may want access to the
1643 :class:`TestResult` object generated by running a set of tests for reporting
1644 purposes; a :class:`TestResult` instance is returned by the
1645 :meth:`TestRunner.run` method for this purpose.
1646
1647 :class:`TestResult` instances have the following attributes that will be of
1648 interest when inspecting the results of running a set of tests:
1649
1650
1651 .. attribute:: errors
1652
1653 A list containing 2-tuples of :class:`TestCase` instances and strings
1654 holding formatted tracebacks. Each tuple represents a test which raised an
1655 unexpected exception.
1656
Benjamin Peterson52baa292009-03-24 00:56:30 +00001657 .. attribute:: failures
1658
1659 A list containing 2-tuples of :class:`TestCase` instances and strings
1660 holding formatted tracebacks. Each tuple represents a test where a failure
1661 was explicitly signalled using the :meth:`TestCase.fail\*` or
1662 :meth:`TestCase.assert\*` methods.
1663
Benjamin Peterson52baa292009-03-24 00:56:30 +00001664 .. attribute:: skipped
1665
1666 A list containing 2-tuples of :class:`TestCase` instances and strings
1667 holding the reason for skipping the test.
1668
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001669 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001670
1671 .. attribute:: expectedFailures
1672
Georg Brandl6faee4e2010-09-21 14:48:28 +00001673 A list containing 2-tuples of :class:`TestCase` instances and strings
1674 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001675 of the test case.
1676
1677 .. attribute:: unexpectedSuccesses
1678
1679 A list containing :class:`TestCase` instances that were marked as expected
1680 failures, but succeeded.
1681
1682 .. attribute:: shouldStop
1683
1684 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1685
1686
1687 .. attribute:: testsRun
1688
1689 The total number of tests run so far.
1690
1691
Georg Brandl12037202010-12-02 22:35:25 +00001692 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001693
1694 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1695 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1696 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1697 fails or errors. Any output is also attached to the failure / error message.
1698
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001699 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001700
1701
1702 .. attribute:: failfast
1703
1704 If set to true :meth:`stop` will be called on the first failure or error,
1705 halting the test run.
1706
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001707 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001708
1709
Benjamin Peterson52baa292009-03-24 00:56:30 +00001710 .. method:: wasSuccessful()
1711
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001712 Return ``True`` if all tests run so far have passed, otherwise returns
1713 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001714
1715
1716 .. method:: stop()
1717
1718 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001719 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001720 :class:`TestRunner` objects should respect this flag and return without
1721 running any additional tests.
1722
1723 For example, this feature is used by the :class:`TextTestRunner` class to
1724 stop the test framework when the user signals an interrupt from the
1725 keyboard. Interactive tools which provide :class:`TestRunner`
1726 implementations can use this in a similar manner.
1727
1728 The following methods of the :class:`TestResult` class are used to maintain
1729 the internal data structures, and may be extended in subclasses to support
1730 additional reporting requirements. This is particularly useful in building
1731 tools which support interactive reporting while tests are being run.
1732
1733
1734 .. method:: startTest(test)
1735
1736 Called when the test case *test* is about to be run.
1737
Benjamin Peterson52baa292009-03-24 00:56:30 +00001738 .. method:: stopTest(test)
1739
1740 Called after the test case *test* has been executed, regardless of the
1741 outcome.
1742
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001743 .. method:: startTestRun(test)
1744
1745 Called once before any tests are executed.
1746
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001747 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001748
1749
1750 .. method:: stopTestRun(test)
1751
Ezio Melotti176d6c42010-01-27 20:58:07 +00001752 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001753
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001754 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001755
1756
Benjamin Peterson52baa292009-03-24 00:56:30 +00001757 .. method:: addError(test, err)
1758
1759 Called when the test case *test* raises an unexpected exception *err* is a
1760 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1761 traceback)``.
1762
1763 The default implementation appends a tuple ``(test, formatted_err)`` to
1764 the instance's :attr:`errors` attribute, where *formatted_err* is a
1765 formatted traceback derived from *err*.
1766
1767
1768 .. method:: addFailure(test, err)
1769
Benjamin Petersond2397752009-06-27 23:45:02 +00001770 Called when the test case *test* signals a failure. *err* is a tuple of
1771 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001772
1773 The default implementation appends a tuple ``(test, formatted_err)`` to
1774 the instance's :attr:`failures` attribute, where *formatted_err* is a
1775 formatted traceback derived from *err*.
1776
1777
1778 .. method:: addSuccess(test)
1779
1780 Called when the test case *test* succeeds.
1781
1782 The default implementation does nothing.
1783
1784
1785 .. method:: addSkip(test, reason)
1786
1787 Called when the test case *test* is skipped. *reason* is the reason the
1788 test gave for skipping.
1789
1790 The default implementation appends a tuple ``(test, reason)`` to the
1791 instance's :attr:`skipped` attribute.
1792
1793
1794 .. method:: addExpectedFailure(test, err)
1795
1796 Called when the test case *test* fails, but was marked with the
1797 :func:`expectedFailure` decorator.
1798
1799 The default implementation appends a tuple ``(test, formatted_err)`` to
1800 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1801 is a formatted traceback derived from *err*.
1802
1803
1804 .. method:: addUnexpectedSuccess(test)
1805
1806 Called when the test case *test* was marked with the
1807 :func:`expectedFailure` decorator, but succeeded.
1808
1809 The default implementation appends the test to the instance's
1810 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001811
Georg Brandl67b21b72010-08-17 15:07:14 +00001812
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001813 .. method:: addSubTest(test, subtest, outcome)
1814
1815 Called when a subtest finishes. *test* is the test case
1816 corresponding to the test method. *subtest* is a custom
1817 :class:`TestCase` instance describing the subtest.
1818
1819 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
1820 it failed with an exception where *outcome* is a tuple of the form
1821 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1822
1823 The default implementation does nothing when the outcome is a
1824 success, and records subtest failures as normal failures.
1825
1826 .. versionadded:: 3.4
1827
1828
Michael Foord34c94622010-02-10 15:51:42 +00001829.. class:: TextTestResult(stream, descriptions, verbosity)
1830
Georg Brandl67b21b72010-08-17 15:07:14 +00001831 A concrete implementation of :class:`TestResult` used by the
1832 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001833
Georg Brandl67b21b72010-08-17 15:07:14 +00001834 .. versionadded:: 3.2
1835 This class was previously named ``_TextTestResult``. The old name still
1836 exists as an alias but is deprecated.
1837
Georg Brandl116aa622007-08-15 14:28:22 +00001838
1839.. data:: defaultTestLoader
1840
1841 Instance of the :class:`TestLoader` class intended to be shared. If no
1842 customization of the :class:`TestLoader` is needed, this instance can be used
1843 instead of repeatedly creating new instances.
1844
1845
Michael Foordd218e952011-01-03 12:55:11 +00001846.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, runnerclass=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001847
Michael Foordd218e952011-01-03 12:55:11 +00001848 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001849 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001850 has a few configurable parameters, but is essentially very simple. Graphical
1851 applications which run test suites should provide alternate implementations.
1852
Ezio Melotti60901872010-12-01 00:56:10 +00001853 By default this runner shows :exc:`DeprecationWarning`,
1854 :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` even if they are
1855 :ref:`ignored by default <warning-ignored>`. Deprecation warnings caused by
1856 :ref:`deprecated unittest methods <deprecated-aliases>` are also
1857 special-cased and, when the warning filters are ``'default'`` or ``'always'``,
1858 they will appear only once per-module, in order to avoid too many warning
Georg Brandl46402372010-12-04 19:06:18 +00001859 messages. This behavior can be overridden using the :option:`-Wd` or
Ezio Melotti60901872010-12-01 00:56:10 +00001860 :option:`-Wa` options and leaving *warnings* to ``None``.
1861
Michael Foordd218e952011-01-03 12:55:11 +00001862 .. versionchanged:: 3.2
1863 Added the ``warnings`` argument.
1864
1865 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001866 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001867 than import time.
1868
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001869 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001870
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001871 This method returns the instance of ``TestResult`` used by :meth:`run`.
1872 It is not intended to be called directly, but can be overridden in
1873 subclasses to provide a custom ``TestResult``.
1874
Michael Foord34c94622010-02-10 15:51:42 +00001875 ``_makeResult()`` instantiates the class or callable passed in the
1876 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001877 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001878 The result class is instantiated with the following arguments::
1879
1880 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001881
Ezio Melotti60901872010-12-01 00:56:10 +00001882
Georg Brandl419e3de2010-12-01 15:44:25 +00001883.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02001884 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00001885 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001886
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001887 A command-line program that loads a set of tests from *module* and runs them;
1888 this is primarily for making test modules conveniently executable.
1889 The simplest use for this function is to include the following line at the
1890 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00001891
1892 if __name__ == '__main__':
1893 unittest.main()
1894
Benjamin Petersond2397752009-06-27 23:45:02 +00001895 You can run tests with more detailed information by passing in the verbosity
1896 argument::
1897
1898 if __name__ == '__main__':
1899 unittest.main(verbosity=2)
1900
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001901 The *argv* argument can be a list of options passed to the program, with the
1902 first element being the program name. If not specified or ``None``,
1903 the values of :data:`sys.argv` are used.
1904
Georg Brandl116aa622007-08-15 14:28:22 +00001905 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001906 created instance of it. By default ``main`` calls :func:`sys.exit` with
1907 an exit code indicating success or failure of the tests run.
1908
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001909 The *testLoader* argument has to be a :class:`TestLoader` instance,
1910 and defaults to :data:`defaultTestLoader`.
1911
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001912 ``main`` supports being used from the interactive interpreter by passing in the
1913 argument ``exit=False``. This displays the result on standard output without
1914 calling :func:`sys.exit`::
1915
1916 >>> from unittest import main
1917 >>> main(module='test_module', exit=False)
1918
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001919 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00001920 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001921
Ezio Melotti60901872010-12-01 00:56:10 +00001922 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
1923 that should be used while running the tests. If it's not specified, it will
1924 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
1925 otherwise it will be set to ``'default'``.
1926
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001927 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1928 This stores the result of the tests run as the ``result`` attribute.
1929
Éric Araujo971dc012010-12-16 03:13:05 +00001930 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001931 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00001932
Georg Brandl853947a2010-01-31 18:53:23 +00001933 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001934 The *verbosity*, *failfast*, *catchbreak*, *buffer*
1935 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001936
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08001937 .. versionchanged:: 3.4
1938 The *defaultTest* parameter was changed to also accept an iterable of
1939 test names.
1940
Benjamin Petersond2397752009-06-27 23:45:02 +00001941
1942load_tests Protocol
1943###################
1944
Georg Brandl853947a2010-01-31 18:53:23 +00001945.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001946
Benjamin Petersond2397752009-06-27 23:45:02 +00001947Modules or packages can customize how tests are loaded from them during normal
1948test runs or test discovery by implementing a function called ``load_tests``.
1949
1950If a test module defines ``load_tests`` it will be called by
1951:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1952
1953 load_tests(loader, standard_tests, None)
1954
1955It should return a :class:`TestSuite`.
1956
1957*loader* is the instance of :class:`TestLoader` doing the loading.
1958*standard_tests* are the tests that would be loaded by default from the
1959module. It is common for test modules to only want to add or remove tests
1960from the standard set of tests.
1961The third argument is used when loading packages as part of test discovery.
1962
1963A typical ``load_tests`` function that loads tests from a specific set of
1964:class:`TestCase` classes may look like::
1965
1966 test_cases = (TestCase1, TestCase2, TestCase3)
1967
1968 def load_tests(loader, tests, pattern):
1969 suite = TestSuite()
1970 for test_class in test_cases:
1971 tests = loader.loadTestsFromTestCase(test_class)
1972 suite.addTests(tests)
1973 return suite
1974
1975If discovery is started, either from the command line or by calling
1976:meth:`TestLoader.discover`, with a pattern that matches a package
1977name then the package :file:`__init__.py` will be checked for ``load_tests``.
1978
1979.. note::
1980
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02001981 The default pattern is ``'test*.py'``. This matches all Python files
1982 that start with ``'test'`` but *won't* match any test directories.
Benjamin Petersond2397752009-06-27 23:45:02 +00001983
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02001984 A pattern like ``'test*'`` will match test packages as well as
Benjamin Petersond2397752009-06-27 23:45:02 +00001985 modules.
1986
1987If the package :file:`__init__.py` defines ``load_tests`` then it will be
1988called and discovery not continued into the package. ``load_tests``
1989is called with the following arguments::
1990
1991 load_tests(loader, standard_tests, pattern)
1992
1993This should return a :class:`TestSuite` representing all the tests
1994from the package. (``standard_tests`` will only contain tests
1995collected from :file:`__init__.py`.)
1996
1997Because the pattern is passed into ``load_tests`` the package is free to
1998continue (and potentially modify) test discovery. A 'do nothing'
1999``load_tests`` function for a test package would look like::
2000
2001 def load_tests(loader, standard_tests, pattern):
2002 # top level directory cached on loader instance
2003 this_dir = os.path.dirname(__file__)
2004 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2005 standard_tests.addTests(package_tests)
2006 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002007
2008
2009Class and Module Fixtures
2010-------------------------
2011
2012Class and module level fixtures are implemented in :class:`TestSuite`. When
2013the test suite encounters a test from a new class then :meth:`tearDownClass`
2014from the previous class (if there is one) is called, followed by
2015:meth:`setUpClass` from the new class.
2016
2017Similarly if a test is from a different module from the previous test then
2018``tearDownModule`` from the previous module is run, followed by
2019``setUpModule`` from the new module.
2020
2021After all the tests have run the final ``tearDownClass`` and
2022``tearDownModule`` are run.
2023
2024Note that shared fixtures do not play well with [potential] features like test
2025parallelization and they break test isolation. They should be used with care.
2026
2027The default ordering of tests created by the unittest test loaders is to group
2028all tests from the same modules and classes together. This will lead to
2029``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2030module. If you randomize the order, so that tests from different modules and
2031classes are adjacent to each other, then these shared fixture functions may be
2032called multiple times in a single test run.
2033
2034Shared fixtures are not intended to work with suites with non-standard
2035ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2036support shared fixtures.
2037
2038If there are any exceptions raised during one of the shared fixture functions
2039the test is reported as an error. Because there is no corresponding test
2040instance an ``_ErrorHolder`` object (that has the same interface as a
2041:class:`TestCase`) is created to represent the error. If you are just using
2042the standard unittest test runner then this detail doesn't matter, but if you
2043are a framework author it may be relevant.
2044
2045
2046setUpClass and tearDownClass
2047~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2048
2049These must be implemented as class methods::
2050
2051 import unittest
2052
2053 class Test(unittest.TestCase):
2054 @classmethod
2055 def setUpClass(cls):
2056 cls._connection = createExpensiveConnectionObject()
2057
2058 @classmethod
2059 def tearDownClass(cls):
2060 cls._connection.destroy()
2061
2062If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2063then you must call up to them yourself. The implementations in
2064:class:`TestCase` are empty.
2065
2066If an exception is raised during a ``setUpClass`` then the tests in the class
2067are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002068have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
2069``SkipTest`` exception then the class will be reported as having been skipped
2070instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002071
2072
2073setUpModule and tearDownModule
2074~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2075
2076These should be implemented as functions::
2077
2078 def setUpModule():
2079 createConnection()
2080
2081 def tearDownModule():
2082 closeConnection()
2083
2084If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002085module will be run and the ``tearDownModule`` will not be run. If the exception is a
2086``SkipTest`` exception then the module will be reported as having been skipped
2087instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002088
2089
2090Signal Handling
2091---------------
2092
Georg Brandl419e3de2010-12-01 15:44:25 +00002093.. versionadded:: 3.2
2094
Éric Araujo8acb67c2010-11-26 23:31:07 +00002095The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002096along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2097more friendly handling of control-C during a test run. With catch break
2098behavior enabled control-C will allow the currently running test to complete,
2099and the test run will then end and report all the results so far. A second
2100control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002101
Michael Foordde4ceab2010-04-25 19:53:49 +00002102The control-c handling signal handler attempts to remain compatible with code or
2103tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2104handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2105i.e. it has been replaced by the system under test and delegated to, then it
2106calls the default handler. This will normally be the expected behavior by code
2107that replaces an installed handler and delegates to it. For individual tests
2108that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2109decorator can be used.
2110
2111There are a few utility functions for framework authors to enable control-c
2112handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002113
2114.. function:: installHandler()
2115
2116 Install the control-c handler. When a :const:`signal.SIGINT` is received
2117 (usually in response to the user pressing control-c) all registered results
2118 have :meth:`~TestResult.stop` called.
2119
Michael Foord469b1f02010-04-26 23:41:26 +00002120
Benjamin Petersonb48af542010-04-11 20:43:16 +00002121.. function:: registerResult(result)
2122
2123 Register a :class:`TestResult` object for control-c handling. Registering a
2124 result stores a weak reference to it, so it doesn't prevent the result from
2125 being garbage collected.
2126
Michael Foordde4ceab2010-04-25 19:53:49 +00002127 Registering a :class:`TestResult` object has no side-effects if control-c
2128 handling is not enabled, so test frameworks can unconditionally register
2129 all results they create independently of whether or not handling is enabled.
2130
Michael Foord469b1f02010-04-26 23:41:26 +00002131
Benjamin Petersonb48af542010-04-11 20:43:16 +00002132.. function:: removeResult(result)
2133
2134 Remove a registered result. Once a result has been removed then
2135 :meth:`~TestResult.stop` will no longer be called on that result object in
2136 response to a control-c.
2137
Michael Foord469b1f02010-04-26 23:41:26 +00002138
Michael Foordde4ceab2010-04-25 19:53:49 +00002139.. function:: removeHandler(function=None)
2140
2141 When called without arguments this function removes the control-c handler
2142 if it has been installed. This function can also be used as a test decorator
2143 to temporarily remove the handler whilst the test is being executed::
2144
2145 @unittest.removeHandler
2146 def test_signal_handling(self):
2147 ...