blob: 766122b0c540ab0640bf914a16a7ed6f949cc890 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`unittest` --- Unit testing framework
2==========================================
3
4.. module:: unittest
5 :synopsis: Unit testing framework for Python.
6.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
7.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9.. sectionauthor:: Raymond Hettinger <python@rcn.com>
10
Ezio Melotti22170ed2010-11-20 09:57:27 +000011(If you are already familiar with the basic concepts of testing, you might want
12to skip to :ref:`the list of assert methods <assert-methods>`.)
Georg Brandl116aa622007-08-15 14:28:22 +000013
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010014The :mod:`unittest` unit testing framework was originally inspired by JUnit
15and has a similar flavor as major unit testing frameworks in other
16languages. It supports test automation, sharing of setup and shutdown code
17for tests, aggregation of tests into collections, and independence of the
18tests from the reporting framework.
Georg Brandl116aa622007-08-15 14:28:22 +000019
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010020To achieve this, :mod:`unittest` supports some important concepts in an
21object-oriented way:
Georg Brandl116aa622007-08-15 14:28:22 +000022
23test fixture
24 A :dfn:`test fixture` represents the preparation needed to perform one or more
25 tests, and any associate cleanup actions. This may involve, for example,
26 creating temporary or proxy databases, directories, or starting a server
27 process.
28
29test case
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010030 A :dfn:`test case` is the individual unit of testing. It checks for a specific
Georg Brandl116aa622007-08-15 14:28:22 +000031 response to a particular set of inputs. :mod:`unittest` provides a base class,
32 :class:`TestCase`, which may be used to create new test cases.
33
34test suite
35 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
36 used to aggregate tests that should be executed together.
37
38test runner
39 A :dfn:`test runner` is a component which orchestrates the execution of tests
40 and provides the outcome to the user. The runner may use a graphical interface,
41 a textual interface, or return a special value to indicate the results of
42 executing the tests.
43
Georg Brandl116aa622007-08-15 14:28:22 +000044
45.. seealso::
46
47 Module :mod:`doctest`
48 Another test-support module with a very different flavor.
49
50 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000051 Kent Beck's original paper on testing frameworks using the pattern shared
52 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000053
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000054 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000055 Third-party unittest frameworks with a lighter-weight syntax for writing
56 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000057
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010058 `The Python Testing Tools Taxonomy <http://wiki.python.org/moin/PythonTestingToolsTaxonomy>`_
Benjamin Petersonb48af542010-04-11 20:43:16 +000059 An extensive list of Python testing tools including functional testing
60 frameworks and mock object libraries.
Benjamin Petersond2397752009-06-27 23:45:02 +000061
Benjamin Petersonb48af542010-04-11 20:43:16 +000062 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
63 A special-interest-group for discussion of testing, and testing tools,
64 in Python.
Benjamin Petersond2397752009-06-27 23:45:02 +000065
Michael Foord90efac72011-01-03 15:39:49 +000066 The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is
67 a GUI tool for test discovery and execution. This is intended largely for ease of use
Senthil Kumaran847c33c2012-10-27 11:04:55 -070068 for those new to unit testing. For production environments it is
69 recommended that tests be driven by a continuous integration system such as
70 `Buildbot <http://buildbot.net/trac>`_, `Jenkins <http://jenkins-ci.org>`_
71 or `Hudson <http://hudson-ci.org/>`_.
Michael Foord90efac72011-01-03 15:39:49 +000072
73
Georg Brandl116aa622007-08-15 14:28:22 +000074.. _unittest-minimal-example:
75
76Basic example
77-------------
78
79The :mod:`unittest` module provides a rich set of tools for constructing and
80running tests. This section demonstrates that a small subset of the tools
81suffice to meet the needs of most users.
82
83Here is a short script to test three functions from the :mod:`random` module::
84
85 import random
86 import unittest
87
88 class TestSequenceFunctions(unittest.TestCase):
89
90 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +000091 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +000092
Benjamin Peterson52baa292009-03-24 00:56:30 +000093 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +000094 # make sure the shuffled sequence does not lose any elements
95 random.shuffle(self.seq)
96 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +000097 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +000098
Benjamin Peterson847a4112010-03-14 15:04:17 +000099 # should raise an exception for an immutable sequence
100 self.assertRaises(TypeError, random.shuffle, (1,2,3))
101
Benjamin Peterson52baa292009-03-24 00:56:30 +0000102 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000103 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000104 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Benjamin Peterson52baa292009-03-24 00:56:30 +0000106 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000107 with self.assertRaises(ValueError):
108 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000109 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000110 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112 if __name__ == '__main__':
113 unittest.main()
114
Benjamin Peterson52baa292009-03-24 00:56:30 +0000115A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000116individual tests are defined with methods whose names start with the letters
117``test``. This naming convention informs the test runner about which methods
118represent tests.
119
Benjamin Peterson52baa292009-03-24 00:56:30 +0000120The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000121expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000122:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
123These methods are used instead of the :keyword:`assert` statement so the test
124runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000125
Benjamin Peterson52baa292009-03-24 00:56:30 +0000126When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
127method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
128defined, the test runner will invoke that method after each test. In the
129example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
130test.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000133provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000134line, the above script produces an output that looks like this::
135
136 ...
137 ----------------------------------------------------------------------
138 Ran 3 tests in 0.000s
139
140 OK
141
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100142Passing the ``-v`` option to your test script will instruct :func:`unittest.main`
143to enable a higher level of verbosity, and produce the following output::
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Ezio Melottid59e44a2010-02-28 03:46:13 +0000145 test_choice (__main__.TestSequenceFunctions) ... ok
146 test_sample (__main__.TestSequenceFunctions) ... ok
147 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149 ----------------------------------------------------------------------
150 Ran 3 tests in 0.110s
151
152 OK
153
154The above examples show the most commonly used :mod:`unittest` features which
155are sufficient to meet many everyday testing needs. The remainder of the
156documentation explores the full feature set from first principles.
157
Benjamin Petersonb48af542010-04-11 20:43:16 +0000158
159.. _unittest-command-line-interface:
160
Éric Araujo76338ec2010-11-26 23:46:18 +0000161Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000162----------------------
163
164The unittest module can be used from the command line to run tests from
165modules, classes or even individual test methods::
166
167 python -m unittest test_module1 test_module2
168 python -m unittest test_module.TestClass
169 python -m unittest test_module.TestClass.test_method
170
171You can pass in a list with any combination of module names, and fully
172qualified class or method names.
173
Michael Foord37d120a2010-12-04 01:11:21 +0000174Test modules can be specified by file path as well::
175
176 python -m unittest tests/test_something.py
177
178This allows you to use the shell filename completion to specify the test module.
179The file specified must still be importable as a module. The path is converted
180to a module name by removing the '.py' and converting path separators into '.'.
181If you want to execute a test file that isn't importable as a module you should
182execute the file directly instead.
183
Benjamin Petersonb48af542010-04-11 20:43:16 +0000184You can run tests with more detail (higher verbosity) by passing in the -v flag::
185
186 python -m unittest -v test_module
187
Michael Foord086f3082010-11-21 21:28:01 +0000188When executed without arguments :ref:`unittest-test-discovery` is started::
189
190 python -m unittest
191
Éric Araujo713d3032010-11-18 16:38:46 +0000192For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000193
194 python -m unittest -h
195
Georg Brandl67b21b72010-08-17 15:07:14 +0000196.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000197 In earlier versions it was only possible to run individual test methods and
198 not modules or classes.
199
200
Éric Araujo76338ec2010-11-26 23:46:18 +0000201Command-line options
202~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000203
Éric Araujod3309df2010-11-21 03:09:17 +0000204:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000205
Éric Araujo713d3032010-11-18 16:38:46 +0000206.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000207
Éric Araujo713d3032010-11-18 16:38:46 +0000208.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000209
Éric Araujo713d3032010-11-18 16:38:46 +0000210 The standard output and standard error streams are buffered during the test
211 run. Output during a passing test is discarded. Output is echoed normally
212 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000213
Éric Araujo713d3032010-11-18 16:38:46 +0000214.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000215
Éric Araujo713d3032010-11-18 16:38:46 +0000216 Control-C during the test run waits for the current test to end and then
217 reports all the results so far. A second control-C raises the normal
218 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000219
Éric Araujo713d3032010-11-18 16:38:46 +0000220 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000221
Éric Araujo713d3032010-11-18 16:38:46 +0000222.. cmdoption:: -f, --failfast
223
224 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000225
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000226.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000227 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000228
229The command line can also be used for test discovery, for running all of the
230tests in a project or just a subset.
231
232
233.. _unittest-test-discovery:
234
235Test Discovery
236--------------
237
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000238.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000239
Ezio Melotti3d995842011-03-08 16:17:35 +0200240Unittest supports simple test discovery. In order to be compatible with test
241discovery, all of the test files must be :ref:`modules <tut-modules>` or
242:ref:`packages <tut-packages>` importable from the top-level directory of
243the project (this means that their filenames must be valid
244:ref:`identifiers <identifiers>`).
Benjamin Petersonb48af542010-04-11 20:43:16 +0000245
246Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000247used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000248
249 cd project_directory
250 python -m unittest discover
251
Michael Foord086f3082010-11-21 21:28:01 +0000252.. note::
253
254 As a shortcut, ``python -m unittest`` is the equivalent of
255 ``python -m unittest discover``. If you want to pass arguments to test
Éric Araujo941afed2011-09-01 02:47:34 +0200256 discovery the ``discover`` sub-command must be used explicitly.
Michael Foord086f3082010-11-21 21:28:01 +0000257
Benjamin Petersonb48af542010-04-11 20:43:16 +0000258The ``discover`` sub-command has the following options:
259
Éric Araujo713d3032010-11-18 16:38:46 +0000260.. program:: unittest discover
261
262.. cmdoption:: -v, --verbose
263
264 Verbose output
265
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800266.. cmdoption:: -s, --start-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000267
Éric Araujo941afed2011-09-01 02:47:34 +0200268 Directory to start discovery (``.`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000269
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800270.. cmdoption:: -p, --pattern pattern
Éric Araujo713d3032010-11-18 16:38:46 +0000271
Éric Araujo941afed2011-09-01 02:47:34 +0200272 Pattern to match test files (``test*.py`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000273
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800274.. cmdoption:: -t, --top-level-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000275
276 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000277
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000278The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
279as positional arguments in that order. The following two command lines
280are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000281
282 python -m unittest discover -s project_directory -p '*_test.py'
283 python -m unittest discover project_directory '*_test.py'
284
Michael Foord16f3e902010-05-08 15:13:42 +0000285As well as being a path it is possible to pass a package name, for example
286``myproject.subpackage.test``, as the start directory. The package name you
287supply will then be imported and its location on the filesystem will be used
288as the start directory.
289
290.. caution::
291
Senthil Kumaran916bd382010-10-15 12:55:19 +0000292 Test discovery loads tests by importing them. Once test discovery has found
293 all the test files from the start directory you specify it turns the paths
294 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000295 imported as ``foo.bar.baz``.
296
297 If you have a package installed globally and attempt test discovery on
298 a different copy of the package then the import *could* happen from the
299 wrong place. If this happens test discovery will warn you and exit.
300
301 If you supply the start directory as a package name rather than a
302 path to a directory then discover assumes that whichever location it
303 imports from is the location you intended, so you will not get the
304 warning.
305
Benjamin Petersonb48af542010-04-11 20:43:16 +0000306Test modules and packages can customize test loading and discovery by through
307the `load_tests protocol`_.
308
309
Georg Brandl116aa622007-08-15 14:28:22 +0000310.. _organizing-tests:
311
312Organizing test code
313--------------------
314
315The basic building blocks of unit testing are :dfn:`test cases` --- single
316scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000317test cases are represented by :class:`unittest.TestCase` instances.
318To make your own test cases you must write subclasses of
319:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000320
Georg Brandl116aa622007-08-15 14:28:22 +0000321The testing code of a :class:`TestCase` instance should be entirely self
322contained, such that it can be run either in isolation or in arbitrary
323combination with any number of other test cases.
324
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100325The simplest :class:`TestCase` subclass will simply implement a test method
326(i.e. a method whose name starts with ``test``) in order to perform specific
327testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000328
329 import unittest
330
331 class DefaultWidgetSizeTestCase(unittest.TestCase):
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100332 def test_default_widget_size(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000333 widget = Widget('The widget')
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100334 self.assertEqual(widget.size(), (50, 50))
Georg Brandl116aa622007-08-15 14:28:22 +0000335
Sandro Tosi41b24042012-01-21 10:59:37 +0100336Note that in order to test something, we use one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000337methods provided by the :class:`TestCase` base class. If the test fails, an
338exception will be raised, and :mod:`unittest` will identify the test case as a
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100339:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`.
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100341Tests can be numerous, and their set-up can be repetitive. Luckily, we
342can factor out set-up code by implementing a method called
343:meth:`~TestCase.setUp`, which the testing framework will automatically
344call for every single test we run::
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346 import unittest
347
348 class SimpleWidgetTestCase(unittest.TestCase):
349 def setUp(self):
350 self.widget = Widget('The widget')
351
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100352 def test_default_widget_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000353 self.assertEqual(self.widget.size(), (50,50),
354 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100356 def test_widget_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000357 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000358 self.assertEqual(self.widget.size(), (100,150),
359 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100361.. note::
362 The order in which the various tests will be run is determined
363 by sorting the test method names with respect to the built-in
364 ordering for strings.
365
Benjamin Peterson52baa292009-03-24 00:56:30 +0000366If the :meth:`~TestCase.setUp` method raises an exception while the test is
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100367running, the framework will consider the test to have suffered an error, and
368the test method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Benjamin Peterson52baa292009-03-24 00:56:30 +0000370Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100371after the test method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373 import unittest
374
375 class SimpleWidgetTestCase(unittest.TestCase):
376 def setUp(self):
377 self.widget = Widget('The widget')
378
379 def tearDown(self):
380 self.widget.dispose()
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100382If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be
383run whether the test method succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385Such a working environment for the testing code is called a :dfn:`fixture`.
386
Georg Brandl116aa622007-08-15 14:28:22 +0000387Test case instances are grouped together according to the features they test.
388:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100389represented by :mod:`unittest`'s :class:`TestSuite` class. In most cases,
390calling :func:`unittest.main` will do the right thing and collect all the
391module's test cases for you, and then execute them.
Georg Brandl116aa622007-08-15 14:28:22 +0000392
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100393However, should you want to customize the building of your test suite,
394you can do it yourself::
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396 def suite():
397 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000398 suite.addTest(WidgetTestCase('test_default_size'))
399 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000400 return suite
401
Georg Brandl116aa622007-08-15 14:28:22 +0000402You can place the definitions of test cases and test suites in the same modules
403as the code they are to test (such as :file:`widget.py`), but there are several
404advantages to placing the test code in a separate module, such as
405:file:`test_widget.py`:
406
407* The test module can be run standalone from the command line.
408
409* The test code can more easily be separated from shipped code.
410
411* There is less temptation to change test code to fit the code it tests without
412 a good reason.
413
414* Test code should be modified much less frequently than the code it tests.
415
416* Tested code can be refactored more easily.
417
418* Tests for modules written in C must be in separate modules anyway, so why not
419 be consistent?
420
421* If the testing strategy changes, there is no need to change the source code.
422
423
424.. _legacy-unit-tests:
425
426Re-using old test code
427----------------------
428
429Some users will find that they have existing test code that they would like to
430run from :mod:`unittest`, without converting every old test function to a
431:class:`TestCase` subclass.
432
433For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
434This subclass of :class:`TestCase` can be used to wrap an existing test
435function. Set-up and tear-down functions can also be provided.
436
437Given the following test function::
438
439 def testSomething():
440 something = makeSomething()
441 assert something.name is not None
442 # ...
443
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100444one can create an equivalent test case instance as follows, with optional
445set-up and tear-down methods::
Georg Brandl116aa622007-08-15 14:28:22 +0000446
447 testcase = unittest.FunctionTestCase(testSomething,
448 setUp=makeSomethingDB,
449 tearDown=deleteSomethingDB)
450
Georg Brandl116aa622007-08-15 14:28:22 +0000451.. note::
452
Benjamin Petersond2397752009-06-27 23:45:02 +0000453 Even though :class:`FunctionTestCase` can be used to quickly convert an
454 existing test base over to a :mod:`unittest`\ -based system, this approach is
455 not recommended. Taking the time to set up proper :class:`TestCase`
456 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000457
Benjamin Peterson52baa292009-03-24 00:56:30 +0000458In some cases, the existing tests may have been written using the :mod:`doctest`
459module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
460automatically build :class:`unittest.TestSuite` instances from the existing
461:mod:`doctest`\ -based tests.
462
Georg Brandl116aa622007-08-15 14:28:22 +0000463
Benjamin Peterson5254c042009-03-23 22:25:03 +0000464.. _unittest-skipping:
465
466Skipping tests and expected failures
467------------------------------------
468
Michael Foordf5c851a2010-02-05 21:48:03 +0000469.. versionadded:: 3.1
470
Benjamin Peterson5254c042009-03-23 22:25:03 +0000471Unittest supports skipping individual test methods and even whole classes of
472tests. In addition, it supports marking a test as a "expected failure," a test
473that is broken and will fail, but shouldn't be counted as a failure on a
474:class:`TestResult`.
475
476Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
477or one of its conditional variants.
478
Ezio Melottifed69ba2013-03-01 21:26:04 +0200479Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000480
481 class MyTestCase(unittest.TestCase):
482
483 @unittest.skip("demonstrating skipping")
484 def test_nothing(self):
485 self.fail("shouldn't happen")
486
Benjamin Petersond2397752009-06-27 23:45:02 +0000487 @unittest.skipIf(mylib.__version__ < (1, 3),
488 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000489 def test_format(self):
490 # Tests that work for only a certain version of the library.
491 pass
492
493 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
494 def test_windows_support(self):
495 # windows specific testing code
496 pass
497
Ezio Melottifed69ba2013-03-01 21:26:04 +0200498This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000499
Benjamin Petersonded31c42009-03-30 15:04:16 +0000500 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000501 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000502 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000503
504 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000505 Ran 3 tests in 0.005s
506
507 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000508
Ezio Melottifed69ba2013-03-01 21:26:04 +0200509Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000510
Sandro Tosi317075d2012-03-31 18:34:59 +0200511 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000512 class MySkippedTestCase(unittest.TestCase):
513 def test_not_run(self):
514 pass
515
Benjamin Peterson52baa292009-03-24 00:56:30 +0000516:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
517that needs to be set up is not available.
518
Benjamin Peterson5254c042009-03-23 22:25:03 +0000519Expected failures use the :func:`expectedFailure` decorator. ::
520
521 class ExpectedFailureTestCase(unittest.TestCase):
522 @unittest.expectedFailure
523 def test_fail(self):
524 self.assertEqual(1, 0, "broken")
525
526It's easy to roll your own skipping decorators by making a decorator that calls
527:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottifed69ba2013-03-01 21:26:04 +0200528the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000529
530 def skipUnlessHasattr(obj, attr):
531 if hasattr(obj, attr):
532 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200533 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000534
535The following decorators implement test skipping and expected failures:
536
Georg Brandl8a1caa22010-07-29 16:01:11 +0000537.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000538
539 Unconditionally skip the decorated test. *reason* should describe why the
540 test is being skipped.
541
Georg Brandl8a1caa22010-07-29 16:01:11 +0000542.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000543
544 Skip the decorated test if *condition* is true.
545
Georg Brandl8a1caa22010-07-29 16:01:11 +0000546.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000547
Georg Brandl6faee4e2010-09-21 14:48:28 +0000548 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000549
Georg Brandl8a1caa22010-07-29 16:01:11 +0000550.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000551
552 Mark the test as an expected failure. If the test fails when run, the test
553 is not counted as a failure.
554
Ezio Melotti265281a2013-03-27 20:11:55 +0200555.. exception:: SkipTest(reason)
556
557 This exception is raised to skip a test.
558
559 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
560 decorators instead of raising this directly.
561
Benjamin Petersonb48af542010-04-11 20:43:16 +0000562Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
563Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
564
Benjamin Peterson5254c042009-03-23 22:25:03 +0000565
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100566.. _subtests:
567
568Distinguishing test iterations using subtests
569---------------------------------------------
570
571.. versionadded:: 3.4
572
573When some of your tests differ only by a some very small differences, for
574instance some parameters, unittest allows you to distinguish them inside
575the body of a test method using the :meth:`~TestCase.subTest` context manager.
576
577For example, the following test::
578
579 class NumbersTest(unittest.TestCase):
580
581 def test_even(self):
582 """
583 Test that numbers between 0 and 5 are all even.
584 """
585 for i in range(0, 6):
586 with self.subTest(i=i):
587 self.assertEqual(i % 2, 0)
588
589will produce the following output::
590
591 ======================================================================
592 FAIL: test_even (__main__.NumbersTest) (i=1)
593 ----------------------------------------------------------------------
594 Traceback (most recent call last):
595 File "subtests.py", line 32, in test_even
596 self.assertEqual(i % 2, 0)
597 AssertionError: 1 != 0
598
599 ======================================================================
600 FAIL: test_even (__main__.NumbersTest) (i=3)
601 ----------------------------------------------------------------------
602 Traceback (most recent call last):
603 File "subtests.py", line 32, in test_even
604 self.assertEqual(i % 2, 0)
605 AssertionError: 1 != 0
606
607 ======================================================================
608 FAIL: test_even (__main__.NumbersTest) (i=5)
609 ----------------------------------------------------------------------
610 Traceback (most recent call last):
611 File "subtests.py", line 32, in test_even
612 self.assertEqual(i % 2, 0)
613 AssertionError: 1 != 0
614
615Without using a subtest, execution would stop after the first failure,
616and the error would be less easy to diagnose because the value of ``i``
617wouldn't be displayed::
618
619 ======================================================================
620 FAIL: test_even (__main__.NumbersTest)
621 ----------------------------------------------------------------------
622 Traceback (most recent call last):
623 File "subtests.py", line 32, in test_even
624 self.assertEqual(i % 2, 0)
625 AssertionError: 1 != 0
626
627
Georg Brandl116aa622007-08-15 14:28:22 +0000628.. _unittest-contents:
629
630Classes and functions
631---------------------
632
Benjamin Peterson52baa292009-03-24 00:56:30 +0000633This section describes in depth the API of :mod:`unittest`.
634
635
636.. _testcase-objects:
637
638Test cases
639~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000640
Georg Brandl7f01a132009-09-16 15:58:14 +0000641.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000642
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100643 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000644 in the :mod:`unittest` universe. This class is intended to be used as a base
645 class, with specific tests being implemented by concrete subclasses. This class
646 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100647 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000648 kinds of failure.
649
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100650 Each instance of :class:`TestCase` will run a single base method: the method
651 named *methodName*. However, the standard implementation of the default
652 *methodName*, ``runTest()``, will run every method starting with ``test``
653 as an individual test, and count successes and failures accordingly.
654 Therefore, in most uses of :class:`TestCase`, you will neither change
655 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000656
Michael Foord1341bb02011-03-14 19:01:46 -0400657 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100658 :class:`TestCase` can be instantiated successfully without providing a
659 *methodName*. This makes it easier to experiment with :class:`TestCase`
660 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000661
662 :class:`TestCase` instances provide three groups of methods: one group used
663 to run the test, another used by the test implementation to check conditions
664 and report failures, and some inquiry methods allowing information about the
665 test itself to be gathered.
666
667 Methods in the first group (running the test) are:
668
Benjamin Peterson52baa292009-03-24 00:56:30 +0000669 .. method:: setUp()
670
671 Method called to prepare the test fixture. This is called immediately
672 before calling the test method; any exception raised by this method will
673 be considered an error rather than a test failure. The default
674 implementation does nothing.
675
676
677 .. method:: tearDown()
678
679 Method called immediately after the test method has been called and the
680 result recorded. This is called even if the test method raised an
681 exception, so the implementation in subclasses may need to be particularly
682 careful about checking internal state. Any exception raised by this
683 method will be considered an error rather than a test failure. This
684 method will only be called if the :meth:`setUp` succeeds, regardless of
685 the outcome of the test method. The default implementation does nothing.
686
687
Benjamin Petersonb48af542010-04-11 20:43:16 +0000688 .. method:: setUpClass()
689
690 A class method called before tests in an individual class run.
691 ``setUpClass`` is called with the class as the only argument
692 and must be decorated as a :func:`classmethod`::
693
694 @classmethod
695 def setUpClass(cls):
696 ...
697
698 See `Class and Module Fixtures`_ for more details.
699
700 .. versionadded:: 3.2
701
702
703 .. method:: tearDownClass()
704
705 A class method called after tests in an individual class have run.
706 ``tearDownClass`` is called with the class as the only argument
707 and must be decorated as a :meth:`classmethod`::
708
709 @classmethod
710 def tearDownClass(cls):
711 ...
712
713 See `Class and Module Fixtures`_ for more details.
714
715 .. versionadded:: 3.2
716
717
Georg Brandl7f01a132009-09-16 15:58:14 +0000718 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000719
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100720 Run the test, collecting the result into the :class:`TestResult` object
721 passed as *result*. If *result* is omitted or ``None``, a temporary
722 result object is created (by calling the :meth:`defaultTestResult`
723 method) and used. The result object is returned to :meth:`run`'s
724 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000725
726 The same effect may be had by simply calling the :class:`TestCase`
727 instance.
728
Michael Foord1341bb02011-03-14 19:01:46 -0400729 .. versionchanged:: 3.3
730 Previous versions of ``run`` did not return the result. Neither did
731 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000732
Benjamin Petersone549ead2009-03-28 21:42:05 +0000733 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000734
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000735 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000736 test. See :ref:`unittest-skipping` for more information.
737
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000738 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000739
Benjamin Peterson52baa292009-03-24 00:56:30 +0000740
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100741 .. method:: subTest(msg=None, **params)
742
743 Return a context manager which executes the enclosed code block as a
744 subtest. *msg* and *params* are optional, arbitrary values which are
745 displayed whenever a subtest fails, allowing you to identify them
746 clearly.
747
748 A test case can contain any number of subtest declarations, and
749 they can be arbitrarily nested.
750
751 See :ref:`subtests` for more information.
752
753 .. versionadded:: 3.4
754
755
Benjamin Peterson52baa292009-03-24 00:56:30 +0000756 .. method:: debug()
757
758 Run the test without collecting the result. This allows exceptions raised
759 by the test to be propagated to the caller, and can be used to support
760 running tests under a debugger.
761
Ezio Melotti22170ed2010-11-20 09:57:27 +0000762 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000763
Ezio Melotti4370b302010-11-03 20:39:14 +0000764 The :class:`TestCase` class provides a number of methods to check for and
765 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000766
Ezio Melotti4370b302010-11-03 20:39:14 +0000767 +-----------------------------------------+-----------------------------+---------------+
768 | Method | Checks that | New in |
769 +=========================================+=============================+===============+
770 | :meth:`assertEqual(a, b) | ``a == b`` | |
771 | <TestCase.assertEqual>` | | |
772 +-----------------------------------------+-----------------------------+---------------+
773 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
774 | <TestCase.assertNotEqual>` | | |
775 +-----------------------------------------+-----------------------------+---------------+
776 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
777 | <TestCase.assertTrue>` | | |
778 +-----------------------------------------+-----------------------------+---------------+
779 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
780 | <TestCase.assertFalse>` | | |
781 +-----------------------------------------+-----------------------------+---------------+
782 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
783 | <TestCase.assertIs>` | | |
784 +-----------------------------------------+-----------------------------+---------------+
785 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
786 | <TestCase.assertIsNot>` | | |
787 +-----------------------------------------+-----------------------------+---------------+
788 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
789 | <TestCase.assertIsNone>` | | |
790 +-----------------------------------------+-----------------------------+---------------+
791 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
792 | <TestCase.assertIsNotNone>` | | |
793 +-----------------------------------------+-----------------------------+---------------+
794 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
795 | <TestCase.assertIn>` | | |
796 +-----------------------------------------+-----------------------------+---------------+
797 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
798 | <TestCase.assertNotIn>` | | |
799 +-----------------------------------------+-----------------------------+---------------+
800 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
801 | <TestCase.assertIsInstance>` | | |
802 +-----------------------------------------+-----------------------------+---------------+
803 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
804 | <TestCase.assertNotIsInstance>` | | |
805 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000806
Ezio Melottib4dc2502011-05-06 15:01:41 +0300807 All the assert methods accept a *msg* argument that, if specified, is used
808 as the error message on failure (see also :data:`longMessage`).
809 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
810 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
811 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000812
Michael Foorde180d392011-01-28 19:51:48 +0000813 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000814
Michael Foorde180d392011-01-28 19:51:48 +0000815 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000816 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000817
Michael Foorde180d392011-01-28 19:51:48 +0000818 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000819 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200820 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000821 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000822 error message (see also the :ref:`list of type-specific methods
823 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000824
Raymond Hettinger35a88362009-04-09 00:08:24 +0000825 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200826 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000827
Michael Foord28a817e2010-02-09 00:03:57 +0000828 .. versionchanged:: 3.2
829 :meth:`assertMultiLineEqual` added as the default type equality
830 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000831
Benjamin Peterson52baa292009-03-24 00:56:30 +0000832
Michael Foorde180d392011-01-28 19:51:48 +0000833 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000834
Michael Foorde180d392011-01-28 19:51:48 +0000835 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000836 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000837
Ezio Melotti4370b302010-11-03 20:39:14 +0000838 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000839 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000840
Ezio Melotti4841fd62010-11-05 15:43:40 +0000841 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000842
Ezio Melotti4841fd62010-11-05 15:43:40 +0000843 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
844 is True`` (use ``assertIs(expr, True)`` for the latter). This method
845 should also be avoided when more specific methods are available (e.g.
846 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
847 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000848
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000849
Michael Foorde180d392011-01-28 19:51:48 +0000850 .. method:: assertIs(first, second, msg=None)
851 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000852
Michael Foorde180d392011-01-28 19:51:48 +0000853 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000854 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000855
Raymond Hettinger35a88362009-04-09 00:08:24 +0000856 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000857
858
Ezio Melotti4370b302010-11-03 20:39:14 +0000859 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000860 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000861
Ezio Melotti9794a262010-11-04 14:52:13 +0000862 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000863
Ezio Melotti4370b302010-11-03 20:39:14 +0000864 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000865
866
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000867 .. method:: assertIn(first, second, msg=None)
868 assertNotIn(first, second, msg=None)
869
Ezio Melotti4841fd62010-11-05 15:43:40 +0000870 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000871
Raymond Hettinger35a88362009-04-09 00:08:24 +0000872 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000873
874
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000875 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000876 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000877
Ezio Melotti9794a262010-11-04 14:52:13 +0000878 Test that *obj* is (or is not) an instance of *cls* (which can be a
879 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200880 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000881
Ezio Melotti4370b302010-11-03 20:39:14 +0000882 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000883
884
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000885
Ezio Melotti4370b302010-11-03 20:39:14 +0000886 It is also possible to check that exceptions and warnings are raised using
887 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000888
Ezio Melotti4370b302010-11-03 20:39:14 +0000889 +---------------------------------------------------------+--------------------------------------+------------+
890 | Method | Checks that | New in |
891 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200892 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000893 | <TestCase.assertRaises>` | | |
894 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200895 | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
896 | <TestCase.assertRaisesRegex>` | and the message matches *re* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000897 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200898 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000899 | <TestCase.assertWarns>` | | |
900 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200901 | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
902 | <TestCase.assertWarnsRegex>` | and the message matches *re* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000903 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000904
Georg Brandl7f01a132009-09-16 15:58:14 +0000905 .. method:: assertRaises(exception, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300906 assertRaises(exception, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000907
908 Test that an exception is raised when *callable* is called with any
909 positional or keyword arguments that are also passed to
910 :meth:`assertRaises`. The test passes if *exception* is raised, is an
911 error if another exception is raised, or fails if no exception is raised.
912 To catch any of a group of exceptions, a tuple containing the exception
913 classes may be passed as *exception*.
914
Ezio Melottib4dc2502011-05-06 15:01:41 +0300915 If only the *exception* and possibly the *msg* arguments are given,
916 return a context manager so that the code under test can be written
917 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000918
Michael Foord41531f22010-02-05 21:13:40 +0000919 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000920 do_something()
921
Ezio Melottib4dc2502011-05-06 15:01:41 +0300922 When used as a context manager, :meth:`assertRaises` accepts the
923 additional keyword argument *msg*.
924
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000925 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000926 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000927 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000928
Georg Brandl8a1caa22010-07-29 16:01:11 +0000929 with self.assertRaises(SomeException) as cm:
930 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000931
Georg Brandl8a1caa22010-07-29 16:01:11 +0000932 the_exception = cm.exception
933 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000934
Ezio Melotti49008232010-02-08 21:57:48 +0000935 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000936 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000937
Ezio Melotti49008232010-02-08 21:57:48 +0000938 .. versionchanged:: 3.2
939 Added the :attr:`exception` attribute.
940
Ezio Melottib4dc2502011-05-06 15:01:41 +0300941 .. versionchanged:: 3.3
942 Added the *msg* keyword argument when used as a context manager.
943
Benjamin Peterson52baa292009-03-24 00:56:30 +0000944
Ezio Melottied3a7d22010-12-01 02:32:32 +0000945 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300946 assertRaisesRegex(exception, regex, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000947
Ezio Melottied3a7d22010-12-01 02:32:32 +0000948 Like :meth:`assertRaises` but also tests that *regex* matches
949 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000950 a regular expression object or a string containing a regular expression
951 suitable for use by :func:`re.search`. Examples::
952
Ezio Melottied3a7d22010-12-01 02:32:32 +0000953 self.assertRaisesRegex(ValueError, 'invalid literal for.*XYZ$',
954 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000955
956 or::
957
Ezio Melottied3a7d22010-12-01 02:32:32 +0000958 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000959 int('XYZ')
960
Georg Brandl419e3de2010-12-01 15:44:25 +0000961 .. versionadded:: 3.1
962 under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +0300963
Ezio Melottied3a7d22010-12-01 02:32:32 +0000964 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +0000965 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000966
Ezio Melottib4dc2502011-05-06 15:01:41 +0300967 .. versionchanged:: 3.3
968 Added the *msg* keyword argument when used as a context manager.
969
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000970
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000971 .. method:: assertWarns(warning, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300972 assertWarns(warning, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000973
974 Test that a warning is triggered when *callable* is called with any
975 positional or keyword arguments that are also passed to
976 :meth:`assertWarns`. The test passes if *warning* is triggered and
977 fails if it isn't. Also, any unexpected exception is an error.
978 To catch any of a group of warnings, a tuple containing the warning
979 classes may be passed as *warnings*.
980
Ezio Melottib4dc2502011-05-06 15:01:41 +0300981 If only the *warning* and possibly the *msg* arguments are given,
982 returns a context manager so that the code under test can be written
983 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000984
985 with self.assertWarns(SomeWarning):
986 do_something()
987
Ezio Melottib4dc2502011-05-06 15:01:41 +0300988 When used as a context manager, :meth:`assertRaises` accepts the
989 additional keyword argument *msg*.
990
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000991 The context manager will store the caught warning object in its
992 :attr:`warning` attribute, and the source line which triggered the
993 warnings in the :attr:`filename` and :attr:`lineno` attributes.
994 This can be useful if the intention is to perform additional checks
995 on the exception raised::
996
997 with self.assertWarns(SomeWarning) as cm:
998 do_something()
999
1000 self.assertIn('myfile.py', cm.filename)
1001 self.assertEqual(320, cm.lineno)
1002
1003 This method works regardless of the warning filters in place when it
1004 is called.
1005
1006 .. versionadded:: 3.2
1007
Ezio Melottib4dc2502011-05-06 15:01:41 +03001008 .. versionchanged:: 3.3
1009 Added the *msg* keyword argument when used as a context manager.
1010
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001011
Ezio Melottied3a7d22010-12-01 02:32:32 +00001012 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001013 assertWarnsRegex(warning, regex, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001014
Ezio Melottied3a7d22010-12-01 02:32:32 +00001015 Like :meth:`assertWarns` but also tests that *regex* matches on the
1016 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001017 object or a string containing a regular expression suitable for use
1018 by :func:`re.search`. Example::
1019
Ezio Melottied3a7d22010-12-01 02:32:32 +00001020 self.assertWarnsRegex(DeprecationWarning,
1021 r'legacy_function\(\) is deprecated',
1022 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001023
1024 or::
1025
Ezio Melottied3a7d22010-12-01 02:32:32 +00001026 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001027 frobnicate('/etc/passwd')
1028
1029 .. versionadded:: 3.2
1030
Ezio Melottib4dc2502011-05-06 15:01:41 +03001031 .. versionchanged:: 3.3
1032 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001033
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001034
Ezio Melotti4370b302010-11-03 20:39:14 +00001035 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001036
Ezio Melotti4370b302010-11-03 20:39:14 +00001037 +---------------------------------------+--------------------------------+--------------+
1038 | Method | Checks that | New in |
1039 +=======================================+================================+==============+
1040 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1041 | <TestCase.assertAlmostEqual>` | | |
1042 +---------------------------------------+--------------------------------+--------------+
1043 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1044 | <TestCase.assertNotAlmostEqual>` | | |
1045 +---------------------------------------+--------------------------------+--------------+
1046 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1047 | <TestCase.assertGreater>` | | |
1048 +---------------------------------------+--------------------------------+--------------+
1049 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1050 | <TestCase.assertGreaterEqual>` | | |
1051 +---------------------------------------+--------------------------------+--------------+
1052 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1053 | <TestCase.assertLess>` | | |
1054 +---------------------------------------+--------------------------------+--------------+
1055 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1056 | <TestCase.assertLessEqual>` | | |
1057 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001058 | :meth:`assertRegex(s, re) | ``regex.search(s)`` | 3.1 |
1059 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001060 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001061 | :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 |
1062 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001063 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001064 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001065 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001066 | | regardless of their order | |
1067 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001068
1069
Michael Foorde180d392011-01-28 19:51:48 +00001070 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1071 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001072
Michael Foorde180d392011-01-28 19:51:48 +00001073 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001074 equal by computing the difference, rounding to the given number of
1075 decimal *places* (default 7), and comparing to zero. Note that these
1076 methods round the values to the given number of *decimal places* (i.e.
1077 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001078
Ezio Melotti4370b302010-11-03 20:39:14 +00001079 If *delta* is supplied instead of *places* then the difference
Michael Foorde180d392011-01-28 19:51:48 +00001080 between *first* and *second* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001081
Ezio Melotti4370b302010-11-03 20:39:14 +00001082 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001083
Ezio Melotti4370b302010-11-03 20:39:14 +00001084 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001085 :meth:`assertAlmostEqual` automatically considers almost equal objects
1086 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1087 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001088
Ezio Melotti4370b302010-11-03 20:39:14 +00001089
Michael Foorde180d392011-01-28 19:51:48 +00001090 .. method:: assertGreater(first, second, msg=None)
1091 assertGreaterEqual(first, second, msg=None)
1092 assertLess(first, second, msg=None)
1093 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001094
Michael Foorde180d392011-01-28 19:51:48 +00001095 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001096 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001097
1098 >>> self.assertGreaterEqual(3, 4)
1099 AssertionError: "3" unexpectedly not greater than or equal to "4"
1100
1101 .. versionadded:: 3.1
1102
1103
Ezio Melottied3a7d22010-12-01 02:32:32 +00001104 .. method:: assertRegex(text, regex, msg=None)
1105 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001106
Ezio Melottied3a7d22010-12-01 02:32:32 +00001107 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001108 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001109 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001110 may be a regular expression object or a string containing a regular
1111 expression suitable for use by :func:`re.search`.
1112
Georg Brandl419e3de2010-12-01 15:44:25 +00001113 .. versionadded:: 3.1
1114 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001115 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001116 The method ``assertRegexpMatches()`` has been renamed to
1117 :meth:`.assertRegex`.
1118 .. versionadded:: 3.2
1119 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001120
1121
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001122 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001123
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001124 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001125 regardless of their order. When they don't, an error message listing the
1126 differences between the sequences will be generated.
1127
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001128 Duplicate elements are *not* ignored when comparing *first* and
1129 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001130 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001131 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001132 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001133
Ezio Melotti4370b302010-11-03 20:39:14 +00001134 .. versionadded:: 3.2
1135
Ezio Melotti4370b302010-11-03 20:39:14 +00001136
Ezio Melotti22170ed2010-11-20 09:57:27 +00001137 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001138
Ezio Melotti22170ed2010-11-20 09:57:27 +00001139 The :meth:`assertEqual` method dispatches the equality check for objects of
1140 the same type to different type-specific methods. These methods are already
1141 implemented for most of the built-in types, but it's also possible to
1142 register new methods using :meth:`addTypeEqualityFunc`:
1143
1144 .. method:: addTypeEqualityFunc(typeobj, function)
1145
1146 Registers a type-specific method called by :meth:`assertEqual` to check
1147 if two objects of exactly the same *typeobj* (not subclasses) compare
1148 equal. *function* must take two positional arguments and a third msg=None
1149 keyword argument just as :meth:`assertEqual` does. It must raise
1150 :data:`self.failureException(msg) <failureException>` when inequality
1151 between the first two parameters is detected -- possibly providing useful
1152 information and explaining the inequalities in details in the error
1153 message.
1154
1155 .. versionadded:: 3.1
1156
1157 The list of type-specific methods automatically used by
1158 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1159 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001160
1161 +-----------------------------------------+-----------------------------+--------------+
1162 | Method | Used to compare | New in |
1163 +=========================================+=============================+==============+
1164 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1165 | <TestCase.assertMultiLineEqual>` | | |
1166 +-----------------------------------------+-----------------------------+--------------+
1167 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1168 | <TestCase.assertSequenceEqual>` | | |
1169 +-----------------------------------------+-----------------------------+--------------+
1170 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1171 | <TestCase.assertListEqual>` | | |
1172 +-----------------------------------------+-----------------------------+--------------+
1173 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1174 | <TestCase.assertTupleEqual>` | | |
1175 +-----------------------------------------+-----------------------------+--------------+
1176 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1177 | <TestCase.assertSetEqual>` | | |
1178 +-----------------------------------------+-----------------------------+--------------+
1179 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1180 | <TestCase.assertDictEqual>` | | |
1181 +-----------------------------------------+-----------------------------+--------------+
1182
1183
1184
Michael Foorde180d392011-01-28 19:51:48 +00001185 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001186
Michael Foorde180d392011-01-28 19:51:48 +00001187 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001188 When not equal a diff of the two strings highlighting the differences
1189 will be included in the error message. This method is used by default
1190 when comparing strings with :meth:`assertEqual`.
1191
Ezio Melotti4370b302010-11-03 20:39:14 +00001192 .. versionadded:: 3.1
1193
1194
Michael Foorde180d392011-01-28 19:51:48 +00001195 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001196
1197 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001198 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001199 be raised. If the sequences are different an error message is
1200 constructed that shows the difference between the two.
1201
Ezio Melotti22170ed2010-11-20 09:57:27 +00001202 This method is not called directly by :meth:`assertEqual`, but
1203 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001204 :meth:`assertTupleEqual`.
1205
1206 .. versionadded:: 3.1
1207
1208
Michael Foorde180d392011-01-28 19:51:48 +00001209 .. method:: assertListEqual(first, second, msg=None)
1210 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001211
Ezio Melotti49ccd512012-08-29 17:50:42 +03001212 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001213 constructed that shows only the differences between the two. An error
1214 is also raised if either of the parameters are of the wrong type.
1215 These methods are used by default when comparing lists or tuples with
1216 :meth:`assertEqual`.
1217
Ezio Melotti4370b302010-11-03 20:39:14 +00001218 .. versionadded:: 3.1
1219
1220
Michael Foorde180d392011-01-28 19:51:48 +00001221 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001222
1223 Tests that two sets are equal. If not, an error message is constructed
1224 that lists the differences between the sets. This method is used by
1225 default when comparing sets or frozensets with :meth:`assertEqual`.
1226
Michael Foorde180d392011-01-28 19:51:48 +00001227 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001228 method.
1229
Ezio Melotti4370b302010-11-03 20:39:14 +00001230 .. versionadded:: 3.1
1231
1232
Michael Foorde180d392011-01-28 19:51:48 +00001233 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001234
1235 Test that two dictionaries are equal. If not, an error message is
1236 constructed that shows the differences in the dictionaries. This
1237 method will be used by default to compare dictionaries in
1238 calls to :meth:`assertEqual`.
1239
Ezio Melotti4370b302010-11-03 20:39:14 +00001240 .. versionadded:: 3.1
1241
1242
1243
Ezio Melotti22170ed2010-11-20 09:57:27 +00001244 .. _other-methods-and-attrs:
1245
Ezio Melotti4370b302010-11-03 20:39:14 +00001246 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001247
Benjamin Peterson52baa292009-03-24 00:56:30 +00001248
Georg Brandl7f01a132009-09-16 15:58:14 +00001249 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001250
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001251 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001252 the error message.
1253
1254
1255 .. attribute:: failureException
1256
1257 This class attribute gives the exception raised by the test method. If a
1258 test framework needs to use a specialized exception, possibly to carry
1259 additional information, it must subclass this exception in order to "play
1260 fair" with the framework. The initial value of this attribute is
1261 :exc:`AssertionError`.
1262
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001263
1264 .. attribute:: longMessage
1265
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001266 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001267 :ref:`assert methods <assert-methods>` will be appended to the end of the
1268 normal failure message. The normal messages contain useful information
1269 about the objects involved, for example the message from assertEqual
1270 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001271 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001272 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001273
Michael Foord5074df62010-12-03 00:53:09 +00001274 This attribute defaults to ``True``. If set to False then a custom message
1275 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001276
1277 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001278 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001279
Raymond Hettinger35a88362009-04-09 00:08:24 +00001280 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001281
1282
Michael Foord98b3e762010-06-05 21:59:55 +00001283 .. attribute:: maxDiff
1284
1285 This attribute controls the maximum length of diffs output by assert
1286 methods that report diffs on failure. It defaults to 80*8 characters.
1287 Assert methods affected by this attribute are
1288 :meth:`assertSequenceEqual` (including all the sequence comparison
1289 methods that delegate to it), :meth:`assertDictEqual` and
1290 :meth:`assertMultiLineEqual`.
1291
1292 Setting ``maxDiff`` to None means that there is no maximum length of
1293 diffs.
1294
1295 .. versionadded:: 3.2
1296
1297
Benjamin Peterson52baa292009-03-24 00:56:30 +00001298 Testing frameworks can use the following methods to collect information on
1299 the test:
1300
1301
1302 .. method:: countTestCases()
1303
1304 Return the number of tests represented by this test object. For
1305 :class:`TestCase` instances, this will always be ``1``.
1306
1307
1308 .. method:: defaultTestResult()
1309
1310 Return an instance of the test result class that should be used for this
1311 test case class (if no other result instance is provided to the
1312 :meth:`run` method).
1313
1314 For :class:`TestCase` instances, this will always be an instance of
1315 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1316 as necessary.
1317
1318
1319 .. method:: id()
1320
1321 Return a string identifying the specific test case. This is usually the
1322 full name of the test method, including the module and class name.
1323
1324
1325 .. method:: shortDescription()
1326
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001327 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001328 has been provided. The default implementation of this method
1329 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001330 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001331
Georg Brandl419e3de2010-12-01 15:44:25 +00001332 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001333 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001334 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001335 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001336 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001337
Georg Brandl116aa622007-08-15 14:28:22 +00001338
Georg Brandl7f01a132009-09-16 15:58:14 +00001339 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001340
1341 Add a function to be called after :meth:`tearDown` to cleanup resources
1342 used during the test. Functions will be called in reverse order to the
1343 order they are added (LIFO). They are called with any arguments and
1344 keyword arguments passed into :meth:`addCleanup` when they are
1345 added.
1346
1347 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1348 then any cleanup functions added will still be called.
1349
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001350 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001351
1352
1353 .. method:: doCleanups()
1354
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001355 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001356 after :meth:`setUp` if :meth:`setUp` raises an exception.
1357
1358 It is responsible for calling all the cleanup functions added by
1359 :meth:`addCleanup`. If you need cleanup functions to be called
1360 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1361 yourself.
1362
1363 :meth:`doCleanups` pops methods off the stack of cleanup
1364 functions one at a time, so it can be called at any time.
1365
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001366 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001367
1368
Georg Brandl7f01a132009-09-16 15:58:14 +00001369.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001370
1371 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001372 allows the test runner to drive the test, but does not provide the methods
1373 which test code can use to check and report errors. This is used to create
1374 test cases using legacy test code, allowing it to be integrated into a
1375 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001376
1377
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001378.. _deprecated-aliases:
1379
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001380Deprecated aliases
1381##################
1382
1383For historical reasons, some of the :class:`TestCase` methods had one or more
1384aliases that are now deprecated. The following table lists the correct names
1385along with their deprecated aliases:
1386
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001387 ============================== ====================== ======================
1388 Method Name Deprecated alias Deprecated alias
1389 ============================== ====================== ======================
1390 :meth:`.assertEqual` failUnlessEqual assertEquals
1391 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1392 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001393 :meth:`.assertFalse` failIf
1394 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001395 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1396 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001397 :meth:`.assertRegex` assertRegexpMatches
1398 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001399 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001400
Ezio Melotti361467e2011-04-03 17:37:58 +03001401 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001402 the fail* aliases listed in the second column.
1403 .. deprecated:: 3.2
1404 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001405 .. deprecated:: 3.2
1406 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1407 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001408
1409
Benjamin Peterson52baa292009-03-24 00:56:30 +00001410.. _testsuite-objects:
1411
Benjamin Peterson52baa292009-03-24 00:56:30 +00001412Grouping tests
1413~~~~~~~~~~~~~~
1414
Georg Brandl7f01a132009-09-16 15:58:14 +00001415.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001416
1417 This class represents an aggregation of individual tests cases and test suites.
1418 The class presents the interface needed by the test runner to allow it to be run
1419 as any other test case. Running a :class:`TestSuite` instance is the same as
1420 iterating over the suite, running each test individually.
1421
1422 If *tests* is given, it must be an iterable of individual test cases or other
1423 test suites that will be used to build the suite initially. Additional methods
1424 are provided to add test cases and suites to the collection later on.
1425
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001426 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1427 they do not actually implement a test. Instead, they are used to aggregate
1428 tests into groups of tests that should be run together. Some additional
1429 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001430
1431
1432 .. method:: TestSuite.addTest(test)
1433
1434 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1435
1436
1437 .. method:: TestSuite.addTests(tests)
1438
1439 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1440 instances to this test suite.
1441
Benjamin Petersond2397752009-06-27 23:45:02 +00001442 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1443 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001444
1445 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1446
1447
1448 .. method:: run(result)
1449
1450 Run the tests associated with this suite, collecting the result into the
1451 test result object passed as *result*. Note that unlike
1452 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1453 be passed in.
1454
1455
1456 .. method:: debug()
1457
1458 Run the tests associated with this suite without collecting the
1459 result. This allows exceptions raised by the test to be propagated to the
1460 caller and can be used to support running tests under a debugger.
1461
1462
1463 .. method:: countTestCases()
1464
1465 Return the number of tests represented by this test object, including all
1466 individual tests and sub-suites.
1467
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001468
1469 .. method:: __iter__()
1470
1471 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1472 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1473 that this method maybe called several times on a single suite
1474 (for example when counting tests or comparing for equality)
1475 so the tests returned must be the same for repeated iterations.
1476
Georg Brandl853947a2010-01-31 18:53:23 +00001477 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001478 In earlier versions the :class:`TestSuite` accessed tests directly rather
1479 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1480 for providing tests.
1481
Benjamin Peterson52baa292009-03-24 00:56:30 +00001482 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1483 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1484
1485
Benjamin Peterson52baa292009-03-24 00:56:30 +00001486Loading and running tests
1487~~~~~~~~~~~~~~~~~~~~~~~~~
1488
Georg Brandl116aa622007-08-15 14:28:22 +00001489.. class:: TestLoader()
1490
Benjamin Peterson52baa292009-03-24 00:56:30 +00001491 The :class:`TestLoader` class is used to create test suites from classes and
1492 modules. Normally, there is no need to create an instance of this class; the
1493 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001494 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1495 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001496
1497 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001498
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001499
Benjamin Peterson52baa292009-03-24 00:56:30 +00001500 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001501
Benjamin Peterson52baa292009-03-24 00:56:30 +00001502 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1503 :class:`testCaseClass`.
1504
1505
1506 .. method:: loadTestsFromModule(module)
1507
1508 Return a suite of all tests cases contained in the given module. This
1509 method searches *module* for classes derived from :class:`TestCase` and
1510 creates an instance of the class for each test method defined for the
1511 class.
1512
Georg Brandle720c0a2009-04-27 16:20:50 +00001513 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001514
1515 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1516 convenient in sharing fixtures and helper functions, defining test
1517 methods on base classes that are not intended to be instantiated
1518 directly does not play well with this method. Doing so, however, can
1519 be useful when the fixtures are different and defined in subclasses.
1520
Benjamin Petersond2397752009-06-27 23:45:02 +00001521 If a module provides a ``load_tests`` function it will be called to
1522 load the tests. This allows modules to customize test loading.
1523 This is the `load_tests protocol`_.
1524
Georg Brandl853947a2010-01-31 18:53:23 +00001525 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001526 Support for ``load_tests`` added.
1527
Benjamin Peterson52baa292009-03-24 00:56:30 +00001528
Georg Brandl7f01a132009-09-16 15:58:14 +00001529 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001530
1531 Return a suite of all tests cases given a string specifier.
1532
1533 The specifier *name* is a "dotted name" that may resolve either to a
1534 module, a test case class, a test method within a test case class, a
1535 :class:`TestSuite` instance, or a callable object which returns a
1536 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1537 applied in the order listed here; that is, a method on a possible test
1538 case class will be picked up as "a test method within a test case class",
1539 rather than "a callable object".
1540
1541 For example, if you have a module :mod:`SampleTests` containing a
1542 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1543 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001544 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1545 return a suite which will run all three test methods. Using the specifier
1546 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1547 suite which will run only the :meth:`test_two` test method. The specifier
1548 can refer to modules and packages which have not been imported; they will
1549 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001550
1551 The method optionally resolves *name* relative to the given *module*.
1552
1553
Georg Brandl7f01a132009-09-16 15:58:14 +00001554 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001555
1556 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1557 than a single name. The return value is a test suite which supports all
1558 the tests defined for each name.
1559
1560
1561 .. method:: getTestCaseNames(testCaseClass)
1562
1563 Return a sorted sequence of method names found within *testCaseClass*;
1564 this should be a subclass of :class:`TestCase`.
1565
Benjamin Petersond2397752009-06-27 23:45:02 +00001566
1567 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1568
1569 Find and return all test modules from the specified start directory,
1570 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001571 *pattern* will be loaded. (Using shell style pattern matching.) Only
1572 module names that are importable (i.e. are valid Python identifiers) will
1573 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001574
1575 All test modules must be importable from the top level of the project. If
1576 the start directory is not the top level directory then the top level
1577 directory must be specified separately.
1578
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001579 If importing a module fails, for example due to a syntax error, then this
Ezio Melottieae2b382013-03-01 14:47:50 +02001580 will be recorded as a single error and discovery will continue. If the
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001581 import failure is due to :exc:`SkipTest` being raised, it will be recorded
Ezio Melottieae2b382013-03-01 14:47:50 +02001582 as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001583
Benjamin Petersond2397752009-06-27 23:45:02 +00001584 If a test package name (directory with :file:`__init__.py`) matches the
1585 pattern then the package will be checked for a ``load_tests``
1586 function. If this exists then it will be called with *loader*, *tests*,
1587 *pattern*.
1588
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001589 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001590 ``load_tests`` is responsible for loading all tests in the package.
1591
1592 The pattern is deliberately not stored as a loader attribute so that
1593 packages can continue discovery themselves. *top_level_dir* is stored so
1594 ``load_tests`` does not need to pass this argument in to
1595 ``loader.discover()``.
1596
Benjamin Petersonb48af542010-04-11 20:43:16 +00001597 *start_dir* can be a dotted module name as well as a directory.
1598
Georg Brandl853947a2010-01-31 18:53:23 +00001599 .. versionadded:: 3.2
1600
Ezio Melottieae2b382013-03-01 14:47:50 +02001601 .. versionchanged:: 3.4
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001602 Modules that raise :exc:`SkipTest` on import are recorded as skips,
1603 not errors.
Ezio Melottieae2b382013-03-01 14:47:50 +02001604
Michael Foord80cbc9e2013-03-18 17:50:12 -07001605 .. versionchanged:: 3.4
1606 Paths are sorted before being imported to ensure execution order for a
1607 given test suite is the same even if the underlying file system's ordering
1608 is not dependent on file name like in ext3/4.
1609
Benjamin Petersond2397752009-06-27 23:45:02 +00001610
Benjamin Peterson52baa292009-03-24 00:56:30 +00001611 The following attributes of a :class:`TestLoader` can be configured either by
1612 subclassing or assignment on an instance:
1613
1614
1615 .. attribute:: testMethodPrefix
1616
1617 String giving the prefix of method names which will be interpreted as test
1618 methods. The default value is ``'test'``.
1619
1620 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1621 methods.
1622
1623
1624 .. attribute:: sortTestMethodsUsing
1625
1626 Function to be used to compare method names when sorting them in
1627 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1628
1629
1630 .. attribute:: suiteClass
1631
1632 Callable object that constructs a test suite from a list of tests. No
1633 methods on the resulting object are needed. The default value is the
1634 :class:`TestSuite` class.
1635
1636 This affects all the :meth:`loadTestsFrom\*` methods.
1637
1638
Benjamin Peterson52baa292009-03-24 00:56:30 +00001639.. class:: TestResult
1640
1641 This class is used to compile information about which tests have succeeded
1642 and which have failed.
1643
1644 A :class:`TestResult` object stores the results of a set of tests. The
1645 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1646 properly recorded; test authors do not need to worry about recording the
1647 outcome of tests.
1648
1649 Testing frameworks built on top of :mod:`unittest` may want access to the
1650 :class:`TestResult` object generated by running a set of tests for reporting
1651 purposes; a :class:`TestResult` instance is returned by the
1652 :meth:`TestRunner.run` method for this purpose.
1653
1654 :class:`TestResult` instances have the following attributes that will be of
1655 interest when inspecting the results of running a set of tests:
1656
1657
1658 .. attribute:: errors
1659
1660 A list containing 2-tuples of :class:`TestCase` instances and strings
1661 holding formatted tracebacks. Each tuple represents a test which raised an
1662 unexpected exception.
1663
Benjamin Peterson52baa292009-03-24 00:56:30 +00001664 .. attribute:: failures
1665
1666 A list containing 2-tuples of :class:`TestCase` instances and strings
1667 holding formatted tracebacks. Each tuple represents a test where a failure
1668 was explicitly signalled using the :meth:`TestCase.fail\*` or
1669 :meth:`TestCase.assert\*` methods.
1670
Benjamin Peterson52baa292009-03-24 00:56:30 +00001671 .. attribute:: skipped
1672
1673 A list containing 2-tuples of :class:`TestCase` instances and strings
1674 holding the reason for skipping the test.
1675
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001676 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001677
1678 .. attribute:: expectedFailures
1679
Georg Brandl6faee4e2010-09-21 14:48:28 +00001680 A list containing 2-tuples of :class:`TestCase` instances and strings
1681 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001682 of the test case.
1683
1684 .. attribute:: unexpectedSuccesses
1685
1686 A list containing :class:`TestCase` instances that were marked as expected
1687 failures, but succeeded.
1688
1689 .. attribute:: shouldStop
1690
1691 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1692
1693
1694 .. attribute:: testsRun
1695
1696 The total number of tests run so far.
1697
1698
Georg Brandl12037202010-12-02 22:35:25 +00001699 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001700
1701 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1702 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1703 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1704 fails or errors. Any output is also attached to the failure / error message.
1705
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001706 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001707
1708
1709 .. attribute:: failfast
1710
1711 If set to true :meth:`stop` will be called on the first failure or error,
1712 halting the test run.
1713
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001714 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001715
1716
Benjamin Peterson52baa292009-03-24 00:56:30 +00001717 .. method:: wasSuccessful()
1718
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001719 Return ``True`` if all tests run so far have passed, otherwise returns
1720 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001721
1722
1723 .. method:: stop()
1724
1725 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001726 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001727 :class:`TestRunner` objects should respect this flag and return without
1728 running any additional tests.
1729
1730 For example, this feature is used by the :class:`TextTestRunner` class to
1731 stop the test framework when the user signals an interrupt from the
1732 keyboard. Interactive tools which provide :class:`TestRunner`
1733 implementations can use this in a similar manner.
1734
1735 The following methods of the :class:`TestResult` class are used to maintain
1736 the internal data structures, and may be extended in subclasses to support
1737 additional reporting requirements. This is particularly useful in building
1738 tools which support interactive reporting while tests are being run.
1739
1740
1741 .. method:: startTest(test)
1742
1743 Called when the test case *test* is about to be run.
1744
Benjamin Peterson52baa292009-03-24 00:56:30 +00001745 .. method:: stopTest(test)
1746
1747 Called after the test case *test* has been executed, regardless of the
1748 outcome.
1749
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001750 .. method:: startTestRun(test)
1751
1752 Called once before any tests are executed.
1753
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001754 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001755
1756
1757 .. method:: stopTestRun(test)
1758
Ezio Melotti176d6c42010-01-27 20:58:07 +00001759 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001760
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001761 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001762
1763
Benjamin Peterson52baa292009-03-24 00:56:30 +00001764 .. method:: addError(test, err)
1765
1766 Called when the test case *test* raises an unexpected exception *err* is a
1767 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1768 traceback)``.
1769
1770 The default implementation appends a tuple ``(test, formatted_err)`` to
1771 the instance's :attr:`errors` attribute, where *formatted_err* is a
1772 formatted traceback derived from *err*.
1773
1774
1775 .. method:: addFailure(test, err)
1776
Benjamin Petersond2397752009-06-27 23:45:02 +00001777 Called when the test case *test* signals a failure. *err* is a tuple of
1778 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001779
1780 The default implementation appends a tuple ``(test, formatted_err)`` to
1781 the instance's :attr:`failures` attribute, where *formatted_err* is a
1782 formatted traceback derived from *err*.
1783
1784
1785 .. method:: addSuccess(test)
1786
1787 Called when the test case *test* succeeds.
1788
1789 The default implementation does nothing.
1790
1791
1792 .. method:: addSkip(test, reason)
1793
1794 Called when the test case *test* is skipped. *reason* is the reason the
1795 test gave for skipping.
1796
1797 The default implementation appends a tuple ``(test, reason)`` to the
1798 instance's :attr:`skipped` attribute.
1799
1800
1801 .. method:: addExpectedFailure(test, err)
1802
1803 Called when the test case *test* fails, but was marked with the
1804 :func:`expectedFailure` decorator.
1805
1806 The default implementation appends a tuple ``(test, formatted_err)`` to
1807 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1808 is a formatted traceback derived from *err*.
1809
1810
1811 .. method:: addUnexpectedSuccess(test)
1812
1813 Called when the test case *test* was marked with the
1814 :func:`expectedFailure` decorator, but succeeded.
1815
1816 The default implementation appends the test to the instance's
1817 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001818
Georg Brandl67b21b72010-08-17 15:07:14 +00001819
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001820 .. method:: addSubTest(test, subtest, outcome)
1821
1822 Called when a subtest finishes. *test* is the test case
1823 corresponding to the test method. *subtest* is a custom
1824 :class:`TestCase` instance describing the subtest.
1825
1826 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
1827 it failed with an exception where *outcome* is a tuple of the form
1828 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1829
1830 The default implementation does nothing when the outcome is a
1831 success, and records subtest failures as normal failures.
1832
1833 .. versionadded:: 3.4
1834
1835
Michael Foord34c94622010-02-10 15:51:42 +00001836.. class:: TextTestResult(stream, descriptions, verbosity)
1837
Georg Brandl67b21b72010-08-17 15:07:14 +00001838 A concrete implementation of :class:`TestResult` used by the
1839 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001840
Georg Brandl67b21b72010-08-17 15:07:14 +00001841 .. versionadded:: 3.2
1842 This class was previously named ``_TextTestResult``. The old name still
1843 exists as an alias but is deprecated.
1844
Georg Brandl116aa622007-08-15 14:28:22 +00001845
1846.. data:: defaultTestLoader
1847
1848 Instance of the :class:`TestLoader` class intended to be shared. If no
1849 customization of the :class:`TestLoader` is needed, this instance can be used
1850 instead of repeatedly creating new instances.
1851
1852
Michael Foordd218e952011-01-03 12:55:11 +00001853.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, runnerclass=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001854
Michael Foordd218e952011-01-03 12:55:11 +00001855 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001856 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001857 has a few configurable parameters, but is essentially very simple. Graphical
1858 applications which run test suites should provide alternate implementations.
1859
Ezio Melotti60901872010-12-01 00:56:10 +00001860 By default this runner shows :exc:`DeprecationWarning`,
1861 :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` even if they are
1862 :ref:`ignored by default <warning-ignored>`. Deprecation warnings caused by
1863 :ref:`deprecated unittest methods <deprecated-aliases>` are also
1864 special-cased and, when the warning filters are ``'default'`` or ``'always'``,
1865 they will appear only once per-module, in order to avoid too many warning
Georg Brandl46402372010-12-04 19:06:18 +00001866 messages. This behavior can be overridden using the :option:`-Wd` or
Ezio Melotti60901872010-12-01 00:56:10 +00001867 :option:`-Wa` options and leaving *warnings* to ``None``.
1868
Michael Foordd218e952011-01-03 12:55:11 +00001869 .. versionchanged:: 3.2
1870 Added the ``warnings`` argument.
1871
1872 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001873 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001874 than import time.
1875
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001876 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001877
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001878 This method returns the instance of ``TestResult`` used by :meth:`run`.
1879 It is not intended to be called directly, but can be overridden in
1880 subclasses to provide a custom ``TestResult``.
1881
Michael Foord34c94622010-02-10 15:51:42 +00001882 ``_makeResult()`` instantiates the class or callable passed in the
1883 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001884 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001885 The result class is instantiated with the following arguments::
1886
1887 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001888
Ezio Melotti60901872010-12-01 00:56:10 +00001889
Georg Brandl419e3de2010-12-01 15:44:25 +00001890.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02001891 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00001892 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001893
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001894 A command-line program that loads a set of tests from *module* and runs them;
1895 this is primarily for making test modules conveniently executable.
1896 The simplest use for this function is to include the following line at the
1897 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00001898
1899 if __name__ == '__main__':
1900 unittest.main()
1901
Benjamin Petersond2397752009-06-27 23:45:02 +00001902 You can run tests with more detailed information by passing in the verbosity
1903 argument::
1904
1905 if __name__ == '__main__':
1906 unittest.main(verbosity=2)
1907
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001908 The *argv* argument can be a list of options passed to the program, with the
1909 first element being the program name. If not specified or ``None``,
1910 the values of :data:`sys.argv` are used.
1911
Georg Brandl116aa622007-08-15 14:28:22 +00001912 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001913 created instance of it. By default ``main`` calls :func:`sys.exit` with
1914 an exit code indicating success or failure of the tests run.
1915
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001916 The *testLoader* argument has to be a :class:`TestLoader` instance,
1917 and defaults to :data:`defaultTestLoader`.
1918
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001919 ``main`` supports being used from the interactive interpreter by passing in the
1920 argument ``exit=False``. This displays the result on standard output without
1921 calling :func:`sys.exit`::
1922
1923 >>> from unittest import main
1924 >>> main(module='test_module', exit=False)
1925
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001926 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00001927 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001928
Ezio Melotti60901872010-12-01 00:56:10 +00001929 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
1930 that should be used while running the tests. If it's not specified, it will
1931 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
1932 otherwise it will be set to ``'default'``.
1933
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001934 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1935 This stores the result of the tests run as the ``result`` attribute.
1936
Éric Araujo971dc012010-12-16 03:13:05 +00001937 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001938 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00001939
Georg Brandl853947a2010-01-31 18:53:23 +00001940 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03001941 The *verbosity*, *failfast*, *catchbreak*, *buffer*
1942 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001943
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08001944 .. versionchanged:: 3.4
1945 The *defaultTest* parameter was changed to also accept an iterable of
1946 test names.
1947
Benjamin Petersond2397752009-06-27 23:45:02 +00001948
1949load_tests Protocol
1950###################
1951
Georg Brandl853947a2010-01-31 18:53:23 +00001952.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001953
Benjamin Petersond2397752009-06-27 23:45:02 +00001954Modules or packages can customize how tests are loaded from them during normal
1955test runs or test discovery by implementing a function called ``load_tests``.
1956
1957If a test module defines ``load_tests`` it will be called by
1958:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1959
1960 load_tests(loader, standard_tests, None)
1961
1962It should return a :class:`TestSuite`.
1963
1964*loader* is the instance of :class:`TestLoader` doing the loading.
1965*standard_tests* are the tests that would be loaded by default from the
1966module. It is common for test modules to only want to add or remove tests
1967from the standard set of tests.
1968The third argument is used when loading packages as part of test discovery.
1969
1970A typical ``load_tests`` function that loads tests from a specific set of
1971:class:`TestCase` classes may look like::
1972
1973 test_cases = (TestCase1, TestCase2, TestCase3)
1974
1975 def load_tests(loader, tests, pattern):
1976 suite = TestSuite()
1977 for test_class in test_cases:
1978 tests = loader.loadTestsFromTestCase(test_class)
1979 suite.addTests(tests)
1980 return suite
1981
1982If discovery is started, either from the command line or by calling
1983:meth:`TestLoader.discover`, with a pattern that matches a package
1984name then the package :file:`__init__.py` will be checked for ``load_tests``.
1985
1986.. note::
1987
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02001988 The default pattern is ``'test*.py'``. This matches all Python files
1989 that start with ``'test'`` but *won't* match any test directories.
Benjamin Petersond2397752009-06-27 23:45:02 +00001990
Ezio Melotti4d6cb0f2013-02-28 08:28:11 +02001991 A pattern like ``'test*'`` will match test packages as well as
Benjamin Petersond2397752009-06-27 23:45:02 +00001992 modules.
1993
1994If the package :file:`__init__.py` defines ``load_tests`` then it will be
1995called and discovery not continued into the package. ``load_tests``
1996is called with the following arguments::
1997
1998 load_tests(loader, standard_tests, pattern)
1999
2000This should return a :class:`TestSuite` representing all the tests
2001from the package. (``standard_tests`` will only contain tests
2002collected from :file:`__init__.py`.)
2003
2004Because the pattern is passed into ``load_tests`` the package is free to
2005continue (and potentially modify) test discovery. A 'do nothing'
2006``load_tests`` function for a test package would look like::
2007
2008 def load_tests(loader, standard_tests, pattern):
2009 # top level directory cached on loader instance
2010 this_dir = os.path.dirname(__file__)
2011 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2012 standard_tests.addTests(package_tests)
2013 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002014
2015
2016Class and Module Fixtures
2017-------------------------
2018
2019Class and module level fixtures are implemented in :class:`TestSuite`. When
2020the test suite encounters a test from a new class then :meth:`tearDownClass`
2021from the previous class (if there is one) is called, followed by
2022:meth:`setUpClass` from the new class.
2023
2024Similarly if a test is from a different module from the previous test then
2025``tearDownModule`` from the previous module is run, followed by
2026``setUpModule`` from the new module.
2027
2028After all the tests have run the final ``tearDownClass`` and
2029``tearDownModule`` are run.
2030
2031Note that shared fixtures do not play well with [potential] features like test
2032parallelization and they break test isolation. They should be used with care.
2033
2034The default ordering of tests created by the unittest test loaders is to group
2035all tests from the same modules and classes together. This will lead to
2036``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2037module. If you randomize the order, so that tests from different modules and
2038classes are adjacent to each other, then these shared fixture functions may be
2039called multiple times in a single test run.
2040
2041Shared fixtures are not intended to work with suites with non-standard
2042ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2043support shared fixtures.
2044
2045If there are any exceptions raised during one of the shared fixture functions
2046the test is reported as an error. Because there is no corresponding test
2047instance an ``_ErrorHolder`` object (that has the same interface as a
2048:class:`TestCase`) is created to represent the error. If you are just using
2049the standard unittest test runner then this detail doesn't matter, but if you
2050are a framework author it may be relevant.
2051
2052
2053setUpClass and tearDownClass
2054~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2055
2056These must be implemented as class methods::
2057
2058 import unittest
2059
2060 class Test(unittest.TestCase):
2061 @classmethod
2062 def setUpClass(cls):
2063 cls._connection = createExpensiveConnectionObject()
2064
2065 @classmethod
2066 def tearDownClass(cls):
2067 cls._connection.destroy()
2068
2069If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2070then you must call up to them yourself. The implementations in
2071:class:`TestCase` are empty.
2072
2073If an exception is raised during a ``setUpClass`` then the tests in the class
2074are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002075have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002076:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002077instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002078
2079
2080setUpModule and tearDownModule
2081~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2082
2083These should be implemented as functions::
2084
2085 def setUpModule():
2086 createConnection()
2087
2088 def tearDownModule():
2089 closeConnection()
2090
2091If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002092module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002093:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002094instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002095
2096
2097Signal Handling
2098---------------
2099
Georg Brandl419e3de2010-12-01 15:44:25 +00002100.. versionadded:: 3.2
2101
Éric Araujo8acb67c2010-11-26 23:31:07 +00002102The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002103along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2104more friendly handling of control-C during a test run. With catch break
2105behavior enabled control-C will allow the currently running test to complete,
2106and the test run will then end and report all the results so far. A second
2107control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002108
Michael Foordde4ceab2010-04-25 19:53:49 +00002109The control-c handling signal handler attempts to remain compatible with code or
2110tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2111handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2112i.e. it has been replaced by the system under test and delegated to, then it
2113calls the default handler. This will normally be the expected behavior by code
2114that replaces an installed handler and delegates to it. For individual tests
2115that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2116decorator can be used.
2117
2118There are a few utility functions for framework authors to enable control-c
2119handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002120
2121.. function:: installHandler()
2122
2123 Install the control-c handler. When a :const:`signal.SIGINT` is received
2124 (usually in response to the user pressing control-c) all registered results
2125 have :meth:`~TestResult.stop` called.
2126
Michael Foord469b1f02010-04-26 23:41:26 +00002127
Benjamin Petersonb48af542010-04-11 20:43:16 +00002128.. function:: registerResult(result)
2129
2130 Register a :class:`TestResult` object for control-c handling. Registering a
2131 result stores a weak reference to it, so it doesn't prevent the result from
2132 being garbage collected.
2133
Michael Foordde4ceab2010-04-25 19:53:49 +00002134 Registering a :class:`TestResult` object has no side-effects if control-c
2135 handling is not enabled, so test frameworks can unconditionally register
2136 all results they create independently of whether or not handling is enabled.
2137
Michael Foord469b1f02010-04-26 23:41:26 +00002138
Benjamin Petersonb48af542010-04-11 20:43:16 +00002139.. function:: removeResult(result)
2140
2141 Remove a registered result. Once a result has been removed then
2142 :meth:`~TestResult.stop` will no longer be called on that result object in
2143 response to a control-c.
2144
Michael Foord469b1f02010-04-26 23:41:26 +00002145
Michael Foordde4ceab2010-04-25 19:53:49 +00002146.. function:: removeHandler(function=None)
2147
2148 When called without arguments this function removes the control-c handler
2149 if it has been installed. This function can also be used as a test decorator
2150 to temporarily remove the handler whilst the test is being executed::
2151
2152 @unittest.removeHandler
2153 def test_signal_handling(self):
2154 ...