blob: 8482f207bd1f7407fabae6e1b100898e6ea5de74 [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
R David Murraya1005ed2015-07-04 15:44:14 -040050 `Simple Smalltalk Testing: With Patterns <https://web.archive.org/web/20150315073817/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
Berker Peksaga1a14092014-12-28 18:48:33 +020054 `Nose <https://nose.readthedocs.org/en/latest/>`_ 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
Georg Brandle73778c2014-10-29 08:36:35 +010058 `The Python Testing Tools Taxonomy <https://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
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030070 `Buildbot <https://buildbot.net/>`_, `Jenkins <https://jenkins.io/>`_
Senthil Kumaran847c33c2012-10-27 11:04:55 -070071 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
Ezio Melotti2e3998f2015-03-24 12:42:41 +020083Here is a short script to test three string methods::
Georg Brandl116aa622007-08-15 14:28:22 +000084
Ezio Melotti2e3998f2015-03-24 12:42:41 +020085 import unittest
Georg Brandl116aa622007-08-15 14:28:22 +000086
Ezio Melotti2e3998f2015-03-24 12:42:41 +020087 class TestStringMethods(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +000088
Serhiy Storchakadba90392016-05-10 12:01:23 +030089 def test_upper(self):
90 self.assertEqual('foo'.upper(), 'FOO')
Georg Brandl116aa622007-08-15 14:28:22 +000091
Serhiy Storchakadba90392016-05-10 12:01:23 +030092 def test_isupper(self):
93 self.assertTrue('FOO'.isupper())
94 self.assertFalse('Foo'.isupper())
Georg Brandl116aa622007-08-15 14:28:22 +000095
Serhiy Storchakadba90392016-05-10 12:01:23 +030096 def test_split(self):
97 s = 'hello world'
98 self.assertEqual(s.split(), ['hello', 'world'])
99 # check that s.split fails when the separator is not a string
100 with self.assertRaises(TypeError):
101 s.split(2)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000102
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200103 if __name__ == '__main__':
104 unittest.main()
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Benjamin Peterson52baa292009-03-24 00:56:30 +0000107A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000108individual tests are defined with methods whose names start with the letters
109``test``. This naming convention informs the test runner about which methods
110represent tests.
111
Benjamin Peterson52baa292009-03-24 00:56:30 +0000112The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200113expected result; :meth:`~TestCase.assertTrue` or :meth:`~TestCase.assertFalse`
114to verify a condition; or :meth:`~TestCase.assertRaises` to verify that a
115specific exception gets raised. These methods are used instead of the
116:keyword:`assert` statement so the test runner can accumulate all test results
117and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200119The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you
120to define instructions that will be executed before and after each test method.
Benjamin Peterson8a6ddb92016-01-07 22:01:26 -0800121They are covered in more detail in the section :ref:`organizing-tests`.
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000124provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000125line, the above script produces an output that looks like this::
126
127 ...
128 ----------------------------------------------------------------------
129 Ran 3 tests in 0.000s
130
131 OK
132
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100133Passing the ``-v`` option to your test script will instruct :func:`unittest.main`
134to enable a higher level of verbosity, and produce the following output::
Georg Brandl116aa622007-08-15 14:28:22 +0000135
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200136 test_isupper (__main__.TestStringMethods) ... ok
137 test_split (__main__.TestStringMethods) ... ok
138 test_upper (__main__.TestStringMethods) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140 ----------------------------------------------------------------------
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200141 Ran 3 tests in 0.001s
Georg Brandl116aa622007-08-15 14:28:22 +0000142
143 OK
144
145The above examples show the most commonly used :mod:`unittest` features which
146are sufficient to meet many everyday testing needs. The remainder of the
147documentation explores the full feature set from first principles.
148
Benjamin Petersonb48af542010-04-11 20:43:16 +0000149
150.. _unittest-command-line-interface:
151
Éric Araujo76338ec2010-11-26 23:46:18 +0000152Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000153----------------------
154
155The unittest module can be used from the command line to run tests from
156modules, classes or even individual test methods::
157
158 python -m unittest test_module1 test_module2
159 python -m unittest test_module.TestClass
160 python -m unittest test_module.TestClass.test_method
161
162You can pass in a list with any combination of module names, and fully
163qualified class or method names.
164
Michael Foord37d120a2010-12-04 01:11:21 +0000165Test modules can be specified by file path as well::
166
167 python -m unittest tests/test_something.py
168
169This allows you to use the shell filename completion to specify the test module.
170The file specified must still be importable as a module. The path is converted
171to a module name by removing the '.py' and converting path separators into '.'.
172If you want to execute a test file that isn't importable as a module you should
173execute the file directly instead.
174
Benjamin Petersonb48af542010-04-11 20:43:16 +0000175You can run tests with more detail (higher verbosity) by passing in the -v flag::
176
177 python -m unittest -v test_module
178
Michael Foord086f3082010-11-21 21:28:01 +0000179When executed without arguments :ref:`unittest-test-discovery` is started::
180
181 python -m unittest
182
Éric Araujo713d3032010-11-18 16:38:46 +0000183For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000184
185 python -m unittest -h
186
Georg Brandl67b21b72010-08-17 15:07:14 +0000187.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000188 In earlier versions it was only possible to run individual test methods and
189 not modules or classes.
190
191
Éric Araujo76338ec2010-11-26 23:46:18 +0000192Command-line options
193~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000194
Éric Araujod3309df2010-11-21 03:09:17 +0000195:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000196
Éric Araujo713d3032010-11-18 16:38:46 +0000197.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000198
Éric Araujo713d3032010-11-18 16:38:46 +0000199.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000200
Éric Araujo713d3032010-11-18 16:38:46 +0000201 The standard output and standard error streams are buffered during the test
202 run. Output during a passing test is discarded. Output is echoed normally
203 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000204
Éric Araujo713d3032010-11-18 16:38:46 +0000205.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000206
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300207 :kbd:`Control-C` during the test run waits for the current test to end and then
208 reports all the results so far. A second :kbd:`Control-C` raises the normal
Éric Araujo713d3032010-11-18 16:38:46 +0000209 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000210
Éric Araujo713d3032010-11-18 16:38:46 +0000211 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000212
Éric Araujo713d3032010-11-18 16:38:46 +0000213.. cmdoption:: -f, --failfast
214
215 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000216
Robert Collinsf0c819a2015-03-06 13:46:35 +1300217.. cmdoption:: --locals
218
219 Show local variables in tracebacks.
220
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000221.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000222 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000223
Robert Collinsf0c819a2015-03-06 13:46:35 +1300224.. versionadded:: 3.5
225 The command-line option ``--locals``.
226
Benjamin Petersonb48af542010-04-11 20:43:16 +0000227The command line can also be used for test discovery, for running all of the
228tests in a project or just a subset.
229
230
231.. _unittest-test-discovery:
232
233Test Discovery
234--------------
235
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000236.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000237
Ezio Melotti3d995842011-03-08 16:17:35 +0200238Unittest supports simple test discovery. In order to be compatible with test
239discovery, all of the test files must be :ref:`modules <tut-modules>` or
Larry Hastings3732ed22014-03-15 21:13:56 -0700240:ref:`packages <tut-packages>` (including :term:`namespace packages
241<namespace package>`) importable from the top-level directory of
242the project (this means that their filenames must be valid :ref:`identifiers
243<identifiers>`).
Benjamin Petersonb48af542010-04-11 20:43:16 +0000244
245Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000246used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000247
248 cd project_directory
249 python -m unittest discover
250
Michael Foord086f3082010-11-21 21:28:01 +0000251.. note::
252
253 As a shortcut, ``python -m unittest`` is the equivalent of
254 ``python -m unittest discover``. If you want to pass arguments to test
Éric Araujo941afed2011-09-01 02:47:34 +0200255 discovery the ``discover`` sub-command must be used explicitly.
Michael Foord086f3082010-11-21 21:28:01 +0000256
Benjamin Petersonb48af542010-04-11 20:43:16 +0000257The ``discover`` sub-command has the following options:
258
Éric Araujo713d3032010-11-18 16:38:46 +0000259.. program:: unittest discover
260
261.. cmdoption:: -v, --verbose
262
263 Verbose output
264
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800265.. cmdoption:: -s, --start-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000266
Éric Araujo941afed2011-09-01 02:47:34 +0200267 Directory to start discovery (``.`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000268
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800269.. cmdoption:: -p, --pattern pattern
Éric Araujo713d3032010-11-18 16:38:46 +0000270
Éric Araujo941afed2011-09-01 02:47:34 +0200271 Pattern to match test files (``test*.py`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000272
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800273.. cmdoption:: -t, --top-level-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000274
275 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000276
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000277The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
278as positional arguments in that order. The following two command lines
279are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000280
Robert Collinsa2b00552015-08-24 12:14:28 +1200281 python -m unittest discover -s project_directory -p "*_test.py"
282 python -m unittest discover project_directory "*_test.py"
Benjamin Petersonb48af542010-04-11 20:43:16 +0000283
Michael Foord16f3e902010-05-08 15:13:42 +0000284As well as being a path it is possible to pass a package name, for example
285``myproject.subpackage.test``, as the start directory. The package name you
286supply will then be imported and its location on the filesystem will be used
287as the start directory.
288
289.. caution::
290
Senthil Kumaran916bd382010-10-15 12:55:19 +0000291 Test discovery loads tests by importing them. Once test discovery has found
292 all the test files from the start directory you specify it turns the paths
293 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000294 imported as ``foo.bar.baz``.
295
296 If you have a package installed globally and attempt test discovery on
297 a different copy of the package then the import *could* happen from the
298 wrong place. If this happens test discovery will warn you and exit.
299
300 If you supply the start directory as a package name rather than a
301 path to a directory then discover assumes that whichever location it
302 imports from is the location you intended, so you will not get the
303 warning.
304
Benjamin Petersonb48af542010-04-11 20:43:16 +0000305Test modules and packages can customize test loading and discovery by through
306the `load_tests protocol`_.
307
Larry Hastings3732ed22014-03-15 21:13:56 -0700308.. versionchanged:: 3.4
309 Test discovery supports :term:`namespace packages <namespace package>`.
310
Benjamin Petersonb48af542010-04-11 20:43:16 +0000311
Georg Brandl116aa622007-08-15 14:28:22 +0000312.. _organizing-tests:
313
314Organizing test code
315--------------------
316
317The basic building blocks of unit testing are :dfn:`test cases` --- single
318scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000319test cases are represented by :class:`unittest.TestCase` instances.
320To make your own test cases you must write subclasses of
321:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000322
Georg Brandl116aa622007-08-15 14:28:22 +0000323The testing code of a :class:`TestCase` instance should be entirely self
324contained, such that it can be run either in isolation or in arbitrary
325combination with any number of other test cases.
326
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100327The simplest :class:`TestCase` subclass will simply implement a test method
328(i.e. a method whose name starts with ``test``) in order to perform specific
329testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331 import unittest
332
333 class DefaultWidgetSizeTestCase(unittest.TestCase):
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100334 def test_default_widget_size(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000335 widget = Widget('The widget')
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100336 self.assertEqual(widget.size(), (50, 50))
Georg Brandl116aa622007-08-15 14:28:22 +0000337
Sandro Tosi41b24042012-01-21 10:59:37 +0100338Note that in order to test something, we use one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000339methods provided by the :class:`TestCase` base class. If the test fails, an
340exception will be raised, and :mod:`unittest` will identify the test case as a
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100341:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`.
Georg Brandl116aa622007-08-15 14:28:22 +0000342
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100343Tests can be numerous, and their set-up can be repetitive. Luckily, we
344can factor out set-up code by implementing a method called
345:meth:`~TestCase.setUp`, which the testing framework will automatically
346call for every single test we run::
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348 import unittest
349
350 class SimpleWidgetTestCase(unittest.TestCase):
351 def setUp(self):
352 self.widget = Widget('The widget')
353
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100354 def test_default_widget_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000355 self.assertEqual(self.widget.size(), (50,50),
356 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000357
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100358 def test_widget_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000359 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000360 self.assertEqual(self.widget.size(), (100,150),
361 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100363.. note::
364 The order in which the various tests will be run is determined
365 by sorting the test method names with respect to the built-in
366 ordering for strings.
367
Benjamin Peterson52baa292009-03-24 00:56:30 +0000368If the :meth:`~TestCase.setUp` method raises an exception while the test is
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100369running, the framework will consider the test to have suffered an error, and
370the test method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000371
Benjamin Peterson52baa292009-03-24 00:56:30 +0000372Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100373after the test method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000374
375 import unittest
376
377 class SimpleWidgetTestCase(unittest.TestCase):
378 def setUp(self):
379 self.widget = Widget('The widget')
380
381 def tearDown(self):
382 self.widget.dispose()
Georg Brandl116aa622007-08-15 14:28:22 +0000383
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100384If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be
385run whether the test method succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387Such a working environment for the testing code is called a :dfn:`fixture`.
388
Georg Brandl116aa622007-08-15 14:28:22 +0000389Test case instances are grouped together according to the features they test.
390:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100391represented by :mod:`unittest`'s :class:`TestSuite` class. In most cases,
392calling :func:`unittest.main` will do the right thing and collect all the
393module's test cases for you, and then execute them.
Georg Brandl116aa622007-08-15 14:28:22 +0000394
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100395However, should you want to customize the building of your test suite,
396you can do it yourself::
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398 def suite():
399 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000400 suite.addTest(WidgetTestCase('test_default_size'))
401 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000402 return suite
403
Georg Brandl116aa622007-08-15 14:28:22 +0000404You can place the definitions of test cases and test suites in the same modules
405as the code they are to test (such as :file:`widget.py`), but there are several
406advantages to placing the test code in a separate module, such as
407:file:`test_widget.py`:
408
409* The test module can be run standalone from the command line.
410
411* The test code can more easily be separated from shipped code.
412
413* There is less temptation to change test code to fit the code it tests without
414 a good reason.
415
416* Test code should be modified much less frequently than the code it tests.
417
418* Tested code can be refactored more easily.
419
420* Tests for modules written in C must be in separate modules anyway, so why not
421 be consistent?
422
423* If the testing strategy changes, there is no need to change the source code.
424
425
426.. _legacy-unit-tests:
427
428Re-using old test code
429----------------------
430
431Some users will find that they have existing test code that they would like to
432run from :mod:`unittest`, without converting every old test function to a
433:class:`TestCase` subclass.
434
435For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
436This subclass of :class:`TestCase` can be used to wrap an existing test
437function. Set-up and tear-down functions can also be provided.
438
439Given the following test function::
440
441 def testSomething():
442 something = makeSomething()
443 assert something.name is not None
444 # ...
445
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100446one can create an equivalent test case instance as follows, with optional
447set-up and tear-down methods::
Georg Brandl116aa622007-08-15 14:28:22 +0000448
449 testcase = unittest.FunctionTestCase(testSomething,
450 setUp=makeSomethingDB,
451 tearDown=deleteSomethingDB)
452
Georg Brandl116aa622007-08-15 14:28:22 +0000453.. note::
454
Benjamin Petersond2397752009-06-27 23:45:02 +0000455 Even though :class:`FunctionTestCase` can be used to quickly convert an
456 existing test base over to a :mod:`unittest`\ -based system, this approach is
457 not recommended. Taking the time to set up proper :class:`TestCase`
458 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000459
Benjamin Peterson52baa292009-03-24 00:56:30 +0000460In some cases, the existing tests may have been written using the :mod:`doctest`
461module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
462automatically build :class:`unittest.TestSuite` instances from the existing
463:mod:`doctest`\ -based tests.
464
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Benjamin Peterson5254c042009-03-23 22:25:03 +0000466.. _unittest-skipping:
467
468Skipping tests and expected failures
469------------------------------------
470
Michael Foordf5c851a2010-02-05 21:48:03 +0000471.. versionadded:: 3.1
472
Benjamin Peterson5254c042009-03-23 22:25:03 +0000473Unittest supports skipping individual test methods and even whole classes of
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200474tests. In addition, it supports marking a test as an "expected failure," a test
Benjamin Peterson5254c042009-03-23 22:25:03 +0000475that is broken and will fail, but shouldn't be counted as a failure on a
476:class:`TestResult`.
477
478Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
479or one of its conditional variants.
480
Ezio Melottifed69ba2013-03-01 21:26:04 +0200481Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000482
483 class MyTestCase(unittest.TestCase):
484
485 @unittest.skip("demonstrating skipping")
486 def test_nothing(self):
487 self.fail("shouldn't happen")
488
Benjamin Petersond2397752009-06-27 23:45:02 +0000489 @unittest.skipIf(mylib.__version__ < (1, 3),
490 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000491 def test_format(self):
492 # Tests that work for only a certain version of the library.
493 pass
494
495 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
496 def test_windows_support(self):
497 # windows specific testing code
498 pass
499
Ezio Melottifed69ba2013-03-01 21:26:04 +0200500This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000501
Benjamin Petersonded31c42009-03-30 15:04:16 +0000502 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000503 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000504 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000505
506 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000507 Ran 3 tests in 0.005s
508
509 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000510
Ezio Melottifed69ba2013-03-01 21:26:04 +0200511Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000512
Sandro Tosi317075d2012-03-31 18:34:59 +0200513 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000514 class MySkippedTestCase(unittest.TestCase):
515 def test_not_run(self):
516 pass
517
Benjamin Peterson52baa292009-03-24 00:56:30 +0000518:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
519that needs to be set up is not available.
520
Benjamin Peterson5254c042009-03-23 22:25:03 +0000521Expected failures use the :func:`expectedFailure` decorator. ::
522
523 class ExpectedFailureTestCase(unittest.TestCase):
524 @unittest.expectedFailure
525 def test_fail(self):
526 self.assertEqual(1, 0, "broken")
527
528It's easy to roll your own skipping decorators by making a decorator that calls
529:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottifed69ba2013-03-01 21:26:04 +0200530the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000531
532 def skipUnlessHasattr(obj, attr):
533 if hasattr(obj, attr):
534 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200535 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000536
537The following decorators implement test skipping and expected failures:
538
Georg Brandl8a1caa22010-07-29 16:01:11 +0000539.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000540
541 Unconditionally skip the decorated test. *reason* should describe why the
542 test is being skipped.
543
Georg Brandl8a1caa22010-07-29 16:01:11 +0000544.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000545
546 Skip the decorated test if *condition* is true.
547
Georg Brandl8a1caa22010-07-29 16:01:11 +0000548.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000549
Georg Brandl6faee4e2010-09-21 14:48:28 +0000550 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000551
Georg Brandl8a1caa22010-07-29 16:01:11 +0000552.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000553
554 Mark the test as an expected failure. If the test fails when run, the test
555 is not counted as a failure.
556
Ezio Melotti265281a2013-03-27 20:11:55 +0200557.. exception:: SkipTest(reason)
558
559 This exception is raised to skip a test.
560
561 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
562 decorators instead of raising this directly.
563
R David Murray42fa1102014-01-03 13:03:36 -0500564Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them.
565Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run.
566Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000567
Benjamin Peterson5254c042009-03-23 22:25:03 +0000568
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100569.. _subtests:
570
571Distinguishing test iterations using subtests
572---------------------------------------------
573
574.. versionadded:: 3.4
575
576When some of your tests differ only by a some very small differences, for
577instance some parameters, unittest allows you to distinguish them inside
578the body of a test method using the :meth:`~TestCase.subTest` context manager.
579
580For example, the following test::
581
582 class NumbersTest(unittest.TestCase):
583
584 def test_even(self):
585 """
586 Test that numbers between 0 and 5 are all even.
587 """
588 for i in range(0, 6):
589 with self.subTest(i=i):
590 self.assertEqual(i % 2, 0)
591
592will produce the following output::
593
594 ======================================================================
595 FAIL: test_even (__main__.NumbersTest) (i=1)
596 ----------------------------------------------------------------------
597 Traceback (most recent call last):
598 File "subtests.py", line 32, in test_even
599 self.assertEqual(i % 2, 0)
600 AssertionError: 1 != 0
601
602 ======================================================================
603 FAIL: test_even (__main__.NumbersTest) (i=3)
604 ----------------------------------------------------------------------
605 Traceback (most recent call last):
606 File "subtests.py", line 32, in test_even
607 self.assertEqual(i % 2, 0)
608 AssertionError: 1 != 0
609
610 ======================================================================
611 FAIL: test_even (__main__.NumbersTest) (i=5)
612 ----------------------------------------------------------------------
613 Traceback (most recent call last):
614 File "subtests.py", line 32, in test_even
615 self.assertEqual(i % 2, 0)
616 AssertionError: 1 != 0
617
618Without using a subtest, execution would stop after the first failure,
619and the error would be less easy to diagnose because the value of ``i``
620wouldn't be displayed::
621
622 ======================================================================
623 FAIL: test_even (__main__.NumbersTest)
624 ----------------------------------------------------------------------
625 Traceback (most recent call last):
626 File "subtests.py", line 32, in test_even
627 self.assertEqual(i % 2, 0)
628 AssertionError: 1 != 0
629
630
Georg Brandl116aa622007-08-15 14:28:22 +0000631.. _unittest-contents:
632
633Classes and functions
634---------------------
635
Benjamin Peterson52baa292009-03-24 00:56:30 +0000636This section describes in depth the API of :mod:`unittest`.
637
638
639.. _testcase-objects:
640
641Test cases
642~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000643
Georg Brandl7f01a132009-09-16 15:58:14 +0000644.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100646 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000647 in the :mod:`unittest` universe. This class is intended to be used as a base
648 class, with specific tests being implemented by concrete subclasses. This class
649 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100650 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000651 kinds of failure.
652
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100653 Each instance of :class:`TestCase` will run a single base method: the method
Robert Collinse02f6c22015-07-23 06:37:26 +1200654 named *methodName*.
655 In most uses of :class:`TestCase`, you will neither change
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100656 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000657
Michael Foord1341bb02011-03-14 19:01:46 -0400658 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100659 :class:`TestCase` can be instantiated successfully without providing a
660 *methodName*. This makes it easier to experiment with :class:`TestCase`
661 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000662
663 :class:`TestCase` instances provide three groups of methods: one group used
664 to run the test, another used by the test implementation to check conditions
665 and report failures, and some inquiry methods allowing information about the
666 test itself to be gathered.
667
668 Methods in the first group (running the test) are:
669
Benjamin Peterson52baa292009-03-24 00:56:30 +0000670 .. method:: setUp()
671
672 Method called to prepare the test fixture. This is called immediately
Terry Jan Reedy7f84d1e2014-04-15 23:44:14 -0400673 before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`,
674 any exception raised by this method will be considered an error rather than
Terry Jan Reedy6ac42402014-04-15 23:38:18 -0400675 a test failure. The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000676
677
678 .. method:: tearDown()
679
680 Method called immediately after the test method has been called and the
681 result recorded. This is called even if the test method raised an
682 exception, so the implementation in subclasses may need to be particularly
Ezio Melotti8dea74f2016-03-13 09:40:09 +0200683 careful about checking internal state. Any exception, other than
684 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
685 considered an additional error rather than a test failure (thus increasing
686 the total number of reported errors). This method will only be called if
687 the :meth:`setUp` succeeds, regardless of the outcome of the test method.
688 The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000689
690
Benjamin Petersonb48af542010-04-11 20:43:16 +0000691 .. method:: setUpClass()
692
693 A class method called before tests in an individual class run.
694 ``setUpClass`` is called with the class as the only argument
695 and must be decorated as a :func:`classmethod`::
696
697 @classmethod
698 def setUpClass(cls):
699 ...
700
701 See `Class and Module Fixtures`_ for more details.
702
703 .. versionadded:: 3.2
704
705
706 .. method:: tearDownClass()
707
708 A class method called after tests in an individual class have run.
709 ``tearDownClass`` is called with the class as the only argument
710 and must be decorated as a :meth:`classmethod`::
711
712 @classmethod
713 def tearDownClass(cls):
714 ...
715
716 See `Class and Module Fixtures`_ for more details.
717
718 .. versionadded:: 3.2
719
720
Georg Brandl7f01a132009-09-16 15:58:14 +0000721 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000722
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100723 Run the test, collecting the result into the :class:`TestResult` object
724 passed as *result*. If *result* is omitted or ``None``, a temporary
725 result object is created (by calling the :meth:`defaultTestResult`
726 method) and used. The result object is returned to :meth:`run`'s
727 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000728
729 The same effect may be had by simply calling the :class:`TestCase`
730 instance.
731
Michael Foord1341bb02011-03-14 19:01:46 -0400732 .. versionchanged:: 3.3
733 Previous versions of ``run`` did not return the result. Neither did
734 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000735
Benjamin Petersone549ead2009-03-28 21:42:05 +0000736 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000737
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000738 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000739 test. See :ref:`unittest-skipping` for more information.
740
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000741 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000742
Benjamin Peterson52baa292009-03-24 00:56:30 +0000743
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100744 .. method:: subTest(msg=None, **params)
745
746 Return a context manager which executes the enclosed code block as a
747 subtest. *msg* and *params* are optional, arbitrary values which are
748 displayed whenever a subtest fails, allowing you to identify them
749 clearly.
750
751 A test case can contain any number of subtest declarations, and
752 they can be arbitrarily nested.
753
754 See :ref:`subtests` for more information.
755
756 .. versionadded:: 3.4
757
758
Benjamin Peterson52baa292009-03-24 00:56:30 +0000759 .. method:: debug()
760
761 Run the test without collecting the result. This allows exceptions raised
762 by the test to be propagated to the caller, and can be used to support
763 running tests under a debugger.
764
Ezio Melotti22170ed2010-11-20 09:57:27 +0000765 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000766
Ezio Melottif418db22016-01-12 11:03:31 +0200767 The :class:`TestCase` class provides several assert methods to check for and
768 report failures. The following table lists the most commonly used methods
769 (see the tables below for more assert methods):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000770
Ezio Melotti4370b302010-11-03 20:39:14 +0000771 +-----------------------------------------+-----------------------------+---------------+
772 | Method | Checks that | New in |
773 +=========================================+=============================+===============+
774 | :meth:`assertEqual(a, b) | ``a == b`` | |
775 | <TestCase.assertEqual>` | | |
776 +-----------------------------------------+-----------------------------+---------------+
777 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
778 | <TestCase.assertNotEqual>` | | |
779 +-----------------------------------------+-----------------------------+---------------+
780 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
781 | <TestCase.assertTrue>` | | |
782 +-----------------------------------------+-----------------------------+---------------+
783 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
784 | <TestCase.assertFalse>` | | |
785 +-----------------------------------------+-----------------------------+---------------+
786 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
787 | <TestCase.assertIs>` | | |
788 +-----------------------------------------+-----------------------------+---------------+
789 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
790 | <TestCase.assertIsNot>` | | |
791 +-----------------------------------------+-----------------------------+---------------+
792 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
793 | <TestCase.assertIsNone>` | | |
794 +-----------------------------------------+-----------------------------+---------------+
795 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
796 | <TestCase.assertIsNotNone>` | | |
797 +-----------------------------------------+-----------------------------+---------------+
798 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
799 | <TestCase.assertIn>` | | |
800 +-----------------------------------------+-----------------------------+---------------+
801 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
802 | <TestCase.assertNotIn>` | | |
803 +-----------------------------------------+-----------------------------+---------------+
804 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
805 | <TestCase.assertIsInstance>` | | |
806 +-----------------------------------------+-----------------------------+---------------+
807 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
808 | <TestCase.assertNotIsInstance>` | | |
809 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000810
Ezio Melottib4dc2502011-05-06 15:01:41 +0300811 All the assert methods accept a *msg* argument that, if specified, is used
812 as the error message on failure (see also :data:`longMessage`).
813 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
814 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
815 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000816
Michael Foorde180d392011-01-28 19:51:48 +0000817 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000818
Michael Foorde180d392011-01-28 19:51:48 +0000819 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000820 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000821
Michael Foorde180d392011-01-28 19:51:48 +0000822 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000823 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200824 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000825 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000826 error message (see also the :ref:`list of type-specific methods
827 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000828
Raymond Hettinger35a88362009-04-09 00:08:24 +0000829 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200830 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000831
Michael Foord28a817e2010-02-09 00:03:57 +0000832 .. versionchanged:: 3.2
833 :meth:`assertMultiLineEqual` added as the default type equality
834 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000835
Benjamin Peterson52baa292009-03-24 00:56:30 +0000836
Michael Foorde180d392011-01-28 19:51:48 +0000837 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000838
Michael Foorde180d392011-01-28 19:51:48 +0000839 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000840 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000841
Ezio Melotti4370b302010-11-03 20:39:14 +0000842 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000843 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000844
Ezio Melotti4841fd62010-11-05 15:43:40 +0000845 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000846
Ezio Melotti4841fd62010-11-05 15:43:40 +0000847 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
848 is True`` (use ``assertIs(expr, True)`` for the latter). This method
849 should also be avoided when more specific methods are available (e.g.
850 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
851 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000852
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000853
Michael Foorde180d392011-01-28 19:51:48 +0000854 .. method:: assertIs(first, second, msg=None)
855 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000856
Michael Foorde180d392011-01-28 19:51:48 +0000857 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000858 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000859
Raymond Hettinger35a88362009-04-09 00:08:24 +0000860 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000861
862
Ezio Melotti4370b302010-11-03 20:39:14 +0000863 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000864 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000865
Ezio Melotti9794a262010-11-04 14:52:13 +0000866 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000867
Ezio Melotti4370b302010-11-03 20:39:14 +0000868 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000869
870
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000871 .. method:: assertIn(first, second, msg=None)
872 assertNotIn(first, second, msg=None)
873
Ezio Melotti4841fd62010-11-05 15:43:40 +0000874 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000875
Raymond Hettinger35a88362009-04-09 00:08:24 +0000876 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000877
878
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000879 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000880 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000881
Ezio Melotti9794a262010-11-04 14:52:13 +0000882 Test that *obj* is (or is not) an instance of *cls* (which can be a
883 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200884 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000885
Ezio Melotti4370b302010-11-03 20:39:14 +0000886 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000887
888
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000889
Ezio Melottif418db22016-01-12 11:03:31 +0200890 It is also possible to check the production of exceptions, warnings, and
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200891 log messages using the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000892
Ezio Melotti4370b302010-11-03 20:39:14 +0000893 +---------------------------------------------------------+--------------------------------------+------------+
894 | Method | Checks that | New in |
895 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200896 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000897 | <TestCase.assertRaises>` | | |
898 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300899 | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
900 | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000901 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200902 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000903 | <TestCase.assertWarns>` | | |
904 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300905 | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
906 | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000907 +---------------------------------------------------------+--------------------------------------+------------+
Georg Brandled007d52013-11-24 16:09:26 +0100908 | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 |
909 | <TestCase.assertLogs>` | with minimum *level* | |
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200910 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000911
Georg Brandl7f01a132009-09-16 15:58:14 +0000912 .. method:: assertRaises(exception, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300913 assertRaises(exception, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000914
915 Test that an exception is raised when *callable* is called with any
916 positional or keyword arguments that are also passed to
917 :meth:`assertRaises`. The test passes if *exception* is raised, is an
918 error if another exception is raised, or fails if no exception is raised.
919 To catch any of a group of exceptions, a tuple containing the exception
920 classes may be passed as *exception*.
921
Ezio Melottib4dc2502011-05-06 15:01:41 +0300922 If only the *exception* and possibly the *msg* arguments are given,
923 return a context manager so that the code under test can be written
924 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000925
Michael Foord41531f22010-02-05 21:13:40 +0000926 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000927 do_something()
928
Ezio Melottib4dc2502011-05-06 15:01:41 +0300929 When used as a context manager, :meth:`assertRaises` accepts the
930 additional keyword argument *msg*.
931
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000932 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000933 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000934 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000935
Georg Brandl8a1caa22010-07-29 16:01:11 +0000936 with self.assertRaises(SomeException) as cm:
937 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000938
Georg Brandl8a1caa22010-07-29 16:01:11 +0000939 the_exception = cm.exception
940 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000941
Ezio Melotti49008232010-02-08 21:57:48 +0000942 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000943 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000944
Ezio Melotti49008232010-02-08 21:57:48 +0000945 .. versionchanged:: 3.2
946 Added the :attr:`exception` attribute.
947
Ezio Melottib4dc2502011-05-06 15:01:41 +0300948 .. versionchanged:: 3.3
949 Added the *msg* keyword argument when used as a context manager.
950
Benjamin Peterson52baa292009-03-24 00:56:30 +0000951
Ezio Melottied3a7d22010-12-01 02:32:32 +0000952 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300953 assertRaisesRegex(exception, regex, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000954
Ezio Melottied3a7d22010-12-01 02:32:32 +0000955 Like :meth:`assertRaises` but also tests that *regex* matches
956 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000957 a regular expression object or a string containing a regular expression
958 suitable for use by :func:`re.search`. Examples::
959
Terry Jan Reedyc4565a92013-06-29 13:15:43 -0400960 self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
Ezio Melottied3a7d22010-12-01 02:32:32 +0000961 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000962
963 or::
964
Ezio Melottied3a7d22010-12-01 02:32:32 +0000965 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000966 int('XYZ')
967
Georg Brandl419e3de2010-12-01 15:44:25 +0000968 .. versionadded:: 3.1
969 under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +0300970
Ezio Melottied3a7d22010-12-01 02:32:32 +0000971 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +0000972 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000973
Ezio Melottib4dc2502011-05-06 15:01:41 +0300974 .. versionchanged:: 3.3
975 Added the *msg* keyword argument when used as a context manager.
976
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000977
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000978 .. method:: assertWarns(warning, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300979 assertWarns(warning, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000980
981 Test that a warning is triggered when *callable* is called with any
982 positional or keyword arguments that are also passed to
983 :meth:`assertWarns`. The test passes if *warning* is triggered and
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400984 fails if it isn't. Any exception is an error.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000985 To catch any of a group of warnings, a tuple containing the warning
986 classes may be passed as *warnings*.
987
Ezio Melottib4dc2502011-05-06 15:01:41 +0300988 If only the *warning* and possibly the *msg* arguments are given,
Terry Jan Reedy778cba72013-07-30 22:31:06 -0400989 return a context manager so that the code under test can be written
Ezio Melottib4dc2502011-05-06 15:01:41 +0300990 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000991
992 with self.assertWarns(SomeWarning):
993 do_something()
994
Terry Jan Reedy9eda66d2013-07-27 16:15:29 -0400995 When used as a context manager, :meth:`assertWarns` accepts the
Ezio Melottib4dc2502011-05-06 15:01:41 +0300996 additional keyword argument *msg*.
997
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000998 The context manager will store the caught warning object in its
999 :attr:`warning` attribute, and the source line which triggered the
1000 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1001 This can be useful if the intention is to perform additional checks
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001002 on the warning caught::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001003
1004 with self.assertWarns(SomeWarning) as cm:
1005 do_something()
1006
1007 self.assertIn('myfile.py', cm.filename)
1008 self.assertEqual(320, cm.lineno)
1009
1010 This method works regardless of the warning filters in place when it
1011 is called.
1012
1013 .. versionadded:: 3.2
1014
Ezio Melottib4dc2502011-05-06 15:01:41 +03001015 .. versionchanged:: 3.3
1016 Added the *msg* keyword argument when used as a context manager.
1017
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001018
Ezio Melottied3a7d22010-12-01 02:32:32 +00001019 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001020 assertWarnsRegex(warning, regex, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001021
Ezio Melottied3a7d22010-12-01 02:32:32 +00001022 Like :meth:`assertWarns` but also tests that *regex* matches on the
1023 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001024 object or a string containing a regular expression suitable for use
1025 by :func:`re.search`. Example::
1026
Ezio Melottied3a7d22010-12-01 02:32:32 +00001027 self.assertWarnsRegex(DeprecationWarning,
1028 r'legacy_function\(\) is deprecated',
1029 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001030
1031 or::
1032
Ezio Melottied3a7d22010-12-01 02:32:32 +00001033 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001034 frobnicate('/etc/passwd')
1035
1036 .. versionadded:: 3.2
1037
Ezio Melottib4dc2502011-05-06 15:01:41 +03001038 .. versionchanged:: 3.3
1039 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001040
Antoine Pitrou0715b9f2013-09-14 19:45:47 +02001041 .. method:: assertLogs(logger=None, level=None)
1042
1043 A context manager to test that at least one message is logged on
1044 the *logger* or one of its children, with at least the given
1045 *level*.
1046
1047 If given, *logger* should be a :class:`logging.Logger` object or a
1048 :class:`str` giving the name of a logger. The default is the root
1049 logger, which will catch all messages.
1050
1051 If given, *level* should be either a numeric logging level or
1052 its string equivalent (for example either ``"ERROR"`` or
1053 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`.
1054
1055 The test passes if at least one message emitted inside the ``with``
1056 block matches the *logger* and *level* conditions, otherwise it fails.
1057
1058 The object returned by the context manager is a recording helper
1059 which keeps tracks of the matching log messages. It has two
1060 attributes:
1061
1062 .. attribute:: records
1063
1064 A list of :class:`logging.LogRecord` objects of the matching
1065 log messages.
1066
1067 .. attribute:: output
1068
1069 A list of :class:`str` objects with the formatted output of
1070 matching messages.
1071
1072 Example::
1073
1074 with self.assertLogs('foo', level='INFO') as cm:
1075 logging.getLogger('foo').info('first message')
1076 logging.getLogger('foo.bar').error('second message')
1077 self.assertEqual(cm.output, ['INFO:foo:first message',
1078 'ERROR:foo.bar:second message'])
1079
1080 .. versionadded:: 3.4
1081
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001082
Ezio Melotti4370b302010-11-03 20:39:14 +00001083 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001084
Ezio Melotti4370b302010-11-03 20:39:14 +00001085 +---------------------------------------+--------------------------------+--------------+
1086 | Method | Checks that | New in |
1087 +=======================================+================================+==============+
1088 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1089 | <TestCase.assertAlmostEqual>` | | |
1090 +---------------------------------------+--------------------------------+--------------+
1091 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1092 | <TestCase.assertNotAlmostEqual>` | | |
1093 +---------------------------------------+--------------------------------+--------------+
1094 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1095 | <TestCase.assertGreater>` | | |
1096 +---------------------------------------+--------------------------------+--------------+
1097 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1098 | <TestCase.assertGreaterEqual>` | | |
1099 +---------------------------------------+--------------------------------+--------------+
1100 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1101 | <TestCase.assertLess>` | | |
1102 +---------------------------------------+--------------------------------+--------------+
1103 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1104 | <TestCase.assertLessEqual>` | | |
1105 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001106 | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001107 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001108 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001109 | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001110 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001111 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001112 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001113 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001114 | | regardless of their order | |
1115 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001116
1117
Michael Foorde180d392011-01-28 19:51:48 +00001118 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1119 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001120
Michael Foorde180d392011-01-28 19:51:48 +00001121 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001122 equal by computing the difference, rounding to the given number of
1123 decimal *places* (default 7), and comparing to zero. Note that these
1124 methods round the values to the given number of *decimal places* (i.e.
1125 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001126
Ezio Melotti4370b302010-11-03 20:39:14 +00001127 If *delta* is supplied instead of *places* then the difference
Ezio Melottid51914c2013-08-11 13:04:50 +03001128 between *first* and *second* must be less or equal to (or greater than) *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001129
Ezio Melotti4370b302010-11-03 20:39:14 +00001130 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001131
Ezio Melotti4370b302010-11-03 20:39:14 +00001132 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001133 :meth:`assertAlmostEqual` automatically considers almost equal objects
1134 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1135 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001136
Ezio Melotti4370b302010-11-03 20:39:14 +00001137
Michael Foorde180d392011-01-28 19:51:48 +00001138 .. method:: assertGreater(first, second, msg=None)
1139 assertGreaterEqual(first, second, msg=None)
1140 assertLess(first, second, msg=None)
1141 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001142
Michael Foorde180d392011-01-28 19:51:48 +00001143 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001144 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001145
1146 >>> self.assertGreaterEqual(3, 4)
1147 AssertionError: "3" unexpectedly not greater than or equal to "4"
1148
1149 .. versionadded:: 3.1
1150
1151
Ezio Melottied3a7d22010-12-01 02:32:32 +00001152 .. method:: assertRegex(text, regex, msg=None)
1153 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001154
Ezio Melottied3a7d22010-12-01 02:32:32 +00001155 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001156 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001157 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001158 may be a regular expression object or a string containing a regular
1159 expression suitable for use by :func:`re.search`.
1160
Georg Brandl419e3de2010-12-01 15:44:25 +00001161 .. versionadded:: 3.1
1162 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001163 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001164 The method ``assertRegexpMatches()`` has been renamed to
1165 :meth:`.assertRegex`.
1166 .. versionadded:: 3.2
1167 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001168
1169
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001170 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001171
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001172 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001173 regardless of their order. When they don't, an error message listing the
1174 differences between the sequences will be generated.
1175
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001176 Duplicate elements are *not* ignored when comparing *first* and
1177 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001178 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001179 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001180 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001181
Ezio Melotti4370b302010-11-03 20:39:14 +00001182 .. versionadded:: 3.2
1183
Ezio Melotti4370b302010-11-03 20:39:14 +00001184
Ezio Melotti22170ed2010-11-20 09:57:27 +00001185 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001186
Ezio Melotti22170ed2010-11-20 09:57:27 +00001187 The :meth:`assertEqual` method dispatches the equality check for objects of
1188 the same type to different type-specific methods. These methods are already
1189 implemented for most of the built-in types, but it's also possible to
1190 register new methods using :meth:`addTypeEqualityFunc`:
1191
1192 .. method:: addTypeEqualityFunc(typeobj, function)
1193
1194 Registers a type-specific method called by :meth:`assertEqual` to check
1195 if two objects of exactly the same *typeobj* (not subclasses) compare
1196 equal. *function* must take two positional arguments and a third msg=None
1197 keyword argument just as :meth:`assertEqual` does. It must raise
1198 :data:`self.failureException(msg) <failureException>` when inequality
1199 between the first two parameters is detected -- possibly providing useful
1200 information and explaining the inequalities in details in the error
1201 message.
1202
1203 .. versionadded:: 3.1
1204
1205 The list of type-specific methods automatically used by
1206 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1207 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001208
1209 +-----------------------------------------+-----------------------------+--------------+
1210 | Method | Used to compare | New in |
1211 +=========================================+=============================+==============+
1212 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1213 | <TestCase.assertMultiLineEqual>` | | |
1214 +-----------------------------------------+-----------------------------+--------------+
1215 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1216 | <TestCase.assertSequenceEqual>` | | |
1217 +-----------------------------------------+-----------------------------+--------------+
1218 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1219 | <TestCase.assertListEqual>` | | |
1220 +-----------------------------------------+-----------------------------+--------------+
1221 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1222 | <TestCase.assertTupleEqual>` | | |
1223 +-----------------------------------------+-----------------------------+--------------+
1224 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1225 | <TestCase.assertSetEqual>` | | |
1226 +-----------------------------------------+-----------------------------+--------------+
1227 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1228 | <TestCase.assertDictEqual>` | | |
1229 +-----------------------------------------+-----------------------------+--------------+
1230
1231
1232
Michael Foorde180d392011-01-28 19:51:48 +00001233 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001234
Michael Foorde180d392011-01-28 19:51:48 +00001235 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001236 When not equal a diff of the two strings highlighting the differences
1237 will be included in the error message. This method is used by default
1238 when comparing strings with :meth:`assertEqual`.
1239
Ezio Melotti4370b302010-11-03 20:39:14 +00001240 .. versionadded:: 3.1
1241
1242
Michael Foorde180d392011-01-28 19:51:48 +00001243 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001244
1245 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001246 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001247 be raised. If the sequences are different an error message is
1248 constructed that shows the difference between the two.
1249
Ezio Melotti22170ed2010-11-20 09:57:27 +00001250 This method is not called directly by :meth:`assertEqual`, but
1251 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001252 :meth:`assertTupleEqual`.
1253
1254 .. versionadded:: 3.1
1255
1256
Michael Foorde180d392011-01-28 19:51:48 +00001257 .. method:: assertListEqual(first, second, msg=None)
1258 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001259
Ezio Melotti49ccd512012-08-29 17:50:42 +03001260 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001261 constructed that shows only the differences between the two. An error
1262 is also raised if either of the parameters are of the wrong type.
1263 These methods are used by default when comparing lists or tuples with
1264 :meth:`assertEqual`.
1265
Ezio Melotti4370b302010-11-03 20:39:14 +00001266 .. versionadded:: 3.1
1267
1268
Michael Foorde180d392011-01-28 19:51:48 +00001269 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001270
1271 Tests that two sets are equal. If not, an error message is constructed
1272 that lists the differences between the sets. This method is used by
1273 default when comparing sets or frozensets with :meth:`assertEqual`.
1274
Michael Foorde180d392011-01-28 19:51:48 +00001275 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001276 method.
1277
Ezio Melotti4370b302010-11-03 20:39:14 +00001278 .. versionadded:: 3.1
1279
1280
Michael Foorde180d392011-01-28 19:51:48 +00001281 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001282
1283 Test that two dictionaries are equal. If not, an error message is
1284 constructed that shows the differences in the dictionaries. This
1285 method will be used by default to compare dictionaries in
1286 calls to :meth:`assertEqual`.
1287
Ezio Melotti4370b302010-11-03 20:39:14 +00001288 .. versionadded:: 3.1
1289
1290
1291
Ezio Melotti22170ed2010-11-20 09:57:27 +00001292 .. _other-methods-and-attrs:
1293
Ezio Melotti4370b302010-11-03 20:39:14 +00001294 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001295
Benjamin Peterson52baa292009-03-24 00:56:30 +00001296
Georg Brandl7f01a132009-09-16 15:58:14 +00001297 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001298
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001299 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001300 the error message.
1301
1302
1303 .. attribute:: failureException
1304
1305 This class attribute gives the exception raised by the test method. If a
1306 test framework needs to use a specialized exception, possibly to carry
1307 additional information, it must subclass this exception in order to "play
1308 fair" with the framework. The initial value of this attribute is
1309 :exc:`AssertionError`.
1310
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001311
1312 .. attribute:: longMessage
1313
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001314 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001315 :ref:`assert methods <assert-methods>` will be appended to the end of the
1316 normal failure message. The normal messages contain useful information
1317 about the objects involved, for example the message from assertEqual
1318 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001319 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001320 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001321
Michael Foord5074df62010-12-03 00:53:09 +00001322 This attribute defaults to ``True``. If set to False then a custom message
1323 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001324
1325 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001326 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001327
Raymond Hettinger35a88362009-04-09 00:08:24 +00001328 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001329
1330
Michael Foord98b3e762010-06-05 21:59:55 +00001331 .. attribute:: maxDiff
1332
1333 This attribute controls the maximum length of diffs output by assert
1334 methods that report diffs on failure. It defaults to 80*8 characters.
1335 Assert methods affected by this attribute are
1336 :meth:`assertSequenceEqual` (including all the sequence comparison
1337 methods that delegate to it), :meth:`assertDictEqual` and
1338 :meth:`assertMultiLineEqual`.
1339
1340 Setting ``maxDiff`` to None means that there is no maximum length of
1341 diffs.
1342
1343 .. versionadded:: 3.2
1344
1345
Benjamin Peterson52baa292009-03-24 00:56:30 +00001346 Testing frameworks can use the following methods to collect information on
1347 the test:
1348
1349
1350 .. method:: countTestCases()
1351
1352 Return the number of tests represented by this test object. For
1353 :class:`TestCase` instances, this will always be ``1``.
1354
1355
1356 .. method:: defaultTestResult()
1357
1358 Return an instance of the test result class that should be used for this
1359 test case class (if no other result instance is provided to the
1360 :meth:`run` method).
1361
1362 For :class:`TestCase` instances, this will always be an instance of
1363 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1364 as necessary.
1365
1366
1367 .. method:: id()
1368
1369 Return a string identifying the specific test case. This is usually the
1370 full name of the test method, including the module and class name.
1371
1372
1373 .. method:: shortDescription()
1374
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001375 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001376 has been provided. The default implementation of this method
1377 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001378 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001379
Georg Brandl419e3de2010-12-01 15:44:25 +00001380 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001381 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001382 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001383 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001384 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001385
Georg Brandl116aa622007-08-15 14:28:22 +00001386
Georg Brandl7f01a132009-09-16 15:58:14 +00001387 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001388
1389 Add a function to be called after :meth:`tearDown` to cleanup resources
1390 used during the test. Functions will be called in reverse order to the
1391 order they are added (LIFO). They are called with any arguments and
1392 keyword arguments passed into :meth:`addCleanup` when they are
1393 added.
1394
1395 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1396 then any cleanup functions added will still be called.
1397
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001398 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001399
1400
1401 .. method:: doCleanups()
1402
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001403 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001404 after :meth:`setUp` if :meth:`setUp` raises an exception.
1405
1406 It is responsible for calling all the cleanup functions added by
1407 :meth:`addCleanup`. If you need cleanup functions to be called
1408 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1409 yourself.
1410
1411 :meth:`doCleanups` pops methods off the stack of cleanup
1412 functions one at a time, so it can be called at any time.
1413
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001414 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001415
1416
Georg Brandl7f01a132009-09-16 15:58:14 +00001417.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001418
1419 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001420 allows the test runner to drive the test, but does not provide the methods
1421 which test code can use to check and report errors. This is used to create
1422 test cases using legacy test code, allowing it to be integrated into a
1423 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001424
1425
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001426.. _deprecated-aliases:
1427
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001428Deprecated aliases
1429##################
1430
1431For historical reasons, some of the :class:`TestCase` methods had one or more
1432aliases that are now deprecated. The following table lists the correct names
1433along with their deprecated aliases:
1434
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001435 ============================== ====================== ======================
1436 Method Name Deprecated alias Deprecated alias
1437 ============================== ====================== ======================
1438 :meth:`.assertEqual` failUnlessEqual assertEquals
1439 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1440 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001441 :meth:`.assertFalse` failIf
1442 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001443 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1444 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001445 :meth:`.assertRegex` assertRegexpMatches
1446 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001447 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001448
Ezio Melotti361467e2011-04-03 17:37:58 +03001449 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001450 the fail* aliases listed in the second column.
1451 .. deprecated:: 3.2
1452 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001453 .. deprecated:: 3.2
1454 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1455 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001456
1457
Benjamin Peterson52baa292009-03-24 00:56:30 +00001458.. _testsuite-objects:
1459
Benjamin Peterson52baa292009-03-24 00:56:30 +00001460Grouping tests
1461~~~~~~~~~~~~~~
1462
Georg Brandl7f01a132009-09-16 15:58:14 +00001463.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001464
1465 This class represents an aggregation of individual tests cases and test suites.
1466 The class presents the interface needed by the test runner to allow it to be run
1467 as any other test case. Running a :class:`TestSuite` instance is the same as
1468 iterating over the suite, running each test individually.
1469
1470 If *tests* is given, it must be an iterable of individual test cases or other
1471 test suites that will be used to build the suite initially. Additional methods
1472 are provided to add test cases and suites to the collection later on.
1473
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001474 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1475 they do not actually implement a test. Instead, they are used to aggregate
1476 tests into groups of tests that should be run together. Some additional
1477 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001478
1479
1480 .. method:: TestSuite.addTest(test)
1481
1482 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1483
1484
1485 .. method:: TestSuite.addTests(tests)
1486
1487 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1488 instances to this test suite.
1489
Benjamin Petersond2397752009-06-27 23:45:02 +00001490 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1491 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001492
1493 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1494
1495
1496 .. method:: run(result)
1497
1498 Run the tests associated with this suite, collecting the result into the
1499 test result object passed as *result*. Note that unlike
1500 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1501 be passed in.
1502
1503
1504 .. method:: debug()
1505
1506 Run the tests associated with this suite without collecting the
1507 result. This allows exceptions raised by the test to be propagated to the
1508 caller and can be used to support running tests under a debugger.
1509
1510
1511 .. method:: countTestCases()
1512
1513 Return the number of tests represented by this test object, including all
1514 individual tests and sub-suites.
1515
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001516
1517 .. method:: __iter__()
1518
1519 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1520 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
Andrew Svetloveb973682013-08-28 21:28:38 +03001521 that this method may be called several times on a single suite (for
1522 example when counting tests or comparing for equality) so the tests
1523 returned by repeated iterations before :meth:`TestSuite.run` must be the
1524 same for each call iteration. After :meth:`TestSuite.run`, callers should
1525 not rely on the tests returned by this method unless the caller uses a
1526 subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
1527 test references.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001528
Georg Brandl853947a2010-01-31 18:53:23 +00001529 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001530 In earlier versions the :class:`TestSuite` accessed tests directly rather
1531 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1532 for providing tests.
1533
Andrew Svetloveb973682013-08-28 21:28:38 +03001534 .. versionchanged:: 3.4
1535 In earlier versions the :class:`TestSuite` held references to each
1536 :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
1537 that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
1538
Benjamin Peterson52baa292009-03-24 00:56:30 +00001539 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1540 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1541
1542
Benjamin Peterson52baa292009-03-24 00:56:30 +00001543Loading and running tests
1544~~~~~~~~~~~~~~~~~~~~~~~~~
1545
Georg Brandl116aa622007-08-15 14:28:22 +00001546.. class:: TestLoader()
1547
Benjamin Peterson52baa292009-03-24 00:56:30 +00001548 The :class:`TestLoader` class is used to create test suites from classes and
1549 modules. Normally, there is no need to create an instance of this class; the
1550 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001551 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1552 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001553
Robert Collinsf920c212014-10-20 13:24:05 +13001554 :class:`TestLoader` objects have the following attributes:
1555
1556
1557 .. attribute:: errors
1558
1559 A list of the non-fatal errors encountered while loading tests. Not reset
1560 by the loader at any point. Fatal errors are signalled by the relevant
1561 a method raising an exception to the caller. Non-fatal errors are also
1562 indicated by a synthetic test that will raise the original error when
1563 run.
1564
1565 .. versionadded:: 3.5
1566
1567
Benjamin Peterson52baa292009-03-24 00:56:30 +00001568 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001569
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001570
Benjamin Peterson52baa292009-03-24 00:56:30 +00001571 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001572
Benjamin Peterson52baa292009-03-24 00:56:30 +00001573 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1574 :class:`testCaseClass`.
1575
Robert Collinse02f6c22015-07-23 06:37:26 +12001576 A test case instance is created for each method named by
1577 :meth:`getTestCaseNames`. By default these are the method names
1578 beginning with ``test``. If :meth:`getTestCaseNames` returns no
1579 methods, but the :meth:`runTest` method is implemented, a single test
1580 case is created for that method instead.
1581
Benjamin Peterson52baa292009-03-24 00:56:30 +00001582
Barry Warsawd78742a2014-09-08 14:21:37 -04001583 .. method:: loadTestsFromModule(module, pattern=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001584
1585 Return a suite of all tests cases contained in the given module. This
1586 method searches *module* for classes derived from :class:`TestCase` and
1587 creates an instance of the class for each test method defined for the
1588 class.
1589
Georg Brandle720c0a2009-04-27 16:20:50 +00001590 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001591
1592 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1593 convenient in sharing fixtures and helper functions, defining test
1594 methods on base classes that are not intended to be instantiated
1595 directly does not play well with this method. Doing so, however, can
1596 be useful when the fixtures are different and defined in subclasses.
1597
Benjamin Petersond2397752009-06-27 23:45:02 +00001598 If a module provides a ``load_tests`` function it will be called to
1599 load the tests. This allows modules to customize test loading.
Barry Warsawd78742a2014-09-08 14:21:37 -04001600 This is the `load_tests protocol`_. The *pattern* argument is passed as
1601 the third argument to ``load_tests``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001602
Georg Brandl853947a2010-01-31 18:53:23 +00001603 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001604 Support for ``load_tests`` added.
1605
Barry Warsawd78742a2014-09-08 14:21:37 -04001606 .. versionchanged:: 3.5
1607 The undocumented and unofficial *use_load_tests* default argument is
1608 deprecated and ignored, although it is still accepted for backward
1609 compatibility. The method also now accepts a keyword-only argument
1610 *pattern* which is passed to ``load_tests`` as the third argument.
1611
Benjamin Peterson52baa292009-03-24 00:56:30 +00001612
Georg Brandl7f01a132009-09-16 15:58:14 +00001613 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001614
1615 Return a suite of all tests cases given a string specifier.
1616
1617 The specifier *name* is a "dotted name" that may resolve either to a
1618 module, a test case class, a test method within a test case class, a
1619 :class:`TestSuite` instance, or a callable object which returns a
1620 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1621 applied in the order listed here; that is, a method on a possible test
1622 case class will be picked up as "a test method within a test case class",
1623 rather than "a callable object".
1624
1625 For example, if you have a module :mod:`SampleTests` containing a
1626 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1627 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001628 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1629 return a suite which will run all three test methods. Using the specifier
1630 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1631 suite which will run only the :meth:`test_two` test method. The specifier
1632 can refer to modules and packages which have not been imported; they will
1633 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001634
1635 The method optionally resolves *name* relative to the given *module*.
1636
Robert Collins659dd622014-10-30 08:27:27 +13001637 .. versionchanged:: 3.5
1638 If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing
1639 *name* then a synthetic test that raises that error when run will be
1640 returned. These errors are included in the errors accumulated by
1641 self.errors.
1642
Benjamin Peterson52baa292009-03-24 00:56:30 +00001643
Georg Brandl7f01a132009-09-16 15:58:14 +00001644 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001645
1646 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1647 than a single name. The return value is a test suite which supports all
1648 the tests defined for each name.
1649
1650
1651 .. method:: getTestCaseNames(testCaseClass)
1652
1653 Return a sorted sequence of method names found within *testCaseClass*;
1654 this should be a subclass of :class:`TestCase`.
1655
Benjamin Petersond2397752009-06-27 23:45:02 +00001656
1657 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1658
Larry Hastings3732ed22014-03-15 21:13:56 -07001659 Find all the test modules by recursing into subdirectories from the
1660 specified start directory, and return a TestSuite object containing them.
1661 Only test files that match *pattern* will be loaded. (Using shell style
1662 pattern matching.) Only module names that are importable (i.e. are valid
1663 Python identifiers) will be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001664
1665 All test modules must be importable from the top level of the project. If
1666 the start directory is not the top level directory then the top level
1667 directory must be specified separately.
1668
Barry Warsawd78742a2014-09-08 14:21:37 -04001669 If importing a module fails, for example due to a syntax error, then
1670 this will be recorded as a single error and discovery will continue. If
1671 the import failure is due to :exc:`SkipTest` being raised, it will be
1672 recorded as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001673
Barry Warsawd78742a2014-09-08 14:21:37 -04001674 If a package (a directory containing a file named :file:`__init__.py`) is
1675 found, the package will be checked for a ``load_tests`` function. If this
Robert Collinsbf2bda32014-11-05 03:09:01 +13001676 exists then it will be called
1677 ``package.load_tests(loader, tests, pattern)``. Test discovery takes care
1678 to ensure that a package is only checked for tests once during an
1679 invocation, even if the load_tests function itself calls
1680 ``loader.discover``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001681
Barry Warsawd78742a2014-09-08 14:21:37 -04001682 If ``load_tests`` exists then discovery does *not* recurse into the
1683 package, ``load_tests`` is responsible for loading all tests in the
1684 package.
Benjamin Petersond2397752009-06-27 23:45:02 +00001685
1686 The pattern is deliberately not stored as a loader attribute so that
1687 packages can continue discovery themselves. *top_level_dir* is stored so
1688 ``load_tests`` does not need to pass this argument in to
1689 ``loader.discover()``.
1690
Benjamin Petersonb48af542010-04-11 20:43:16 +00001691 *start_dir* can be a dotted module name as well as a directory.
1692
Georg Brandl853947a2010-01-31 18:53:23 +00001693 .. versionadded:: 3.2
1694
Ezio Melottieae2b382013-03-01 14:47:50 +02001695 .. versionchanged:: 3.4
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001696 Modules that raise :exc:`SkipTest` on import are recorded as skips,
Larry Hastings3732ed22014-03-15 21:13:56 -07001697 not errors.
1698 Discovery works for :term:`namespace packages <namespace package>`.
1699 Paths are sorted before being imported so that execution order is
1700 the same even if the underlying file system's ordering is not
1701 dependent on file name.
Michael Foord80cbc9e2013-03-18 17:50:12 -07001702
Barry Warsawd78742a2014-09-08 14:21:37 -04001703 .. versionchanged:: 3.5
1704 Found packages are now checked for ``load_tests`` regardless of
1705 whether their path matches *pattern*, because it is impossible for
1706 a package name to match the default pattern.
1707
Benjamin Petersond2397752009-06-27 23:45:02 +00001708
Benjamin Peterson52baa292009-03-24 00:56:30 +00001709 The following attributes of a :class:`TestLoader` can be configured either by
1710 subclassing or assignment on an instance:
1711
1712
1713 .. attribute:: testMethodPrefix
1714
1715 String giving the prefix of method names which will be interpreted as test
1716 methods. The default value is ``'test'``.
1717
1718 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1719 methods.
1720
1721
1722 .. attribute:: sortTestMethodsUsing
1723
1724 Function to be used to compare method names when sorting them in
1725 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1726
1727
1728 .. attribute:: suiteClass
1729
1730 Callable object that constructs a test suite from a list of tests. No
1731 methods on the resulting object are needed. The default value is the
1732 :class:`TestSuite` class.
1733
1734 This affects all the :meth:`loadTestsFrom\*` methods.
1735
1736
Benjamin Peterson52baa292009-03-24 00:56:30 +00001737.. class:: TestResult
1738
1739 This class is used to compile information about which tests have succeeded
1740 and which have failed.
1741
1742 A :class:`TestResult` object stores the results of a set of tests. The
1743 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1744 properly recorded; test authors do not need to worry about recording the
1745 outcome of tests.
1746
1747 Testing frameworks built on top of :mod:`unittest` may want access to the
1748 :class:`TestResult` object generated by running a set of tests for reporting
1749 purposes; a :class:`TestResult` instance is returned by the
1750 :meth:`TestRunner.run` method for this purpose.
1751
1752 :class:`TestResult` instances have the following attributes that will be of
1753 interest when inspecting the results of running a set of tests:
1754
1755
1756 .. attribute:: errors
1757
1758 A list containing 2-tuples of :class:`TestCase` instances and strings
1759 holding formatted tracebacks. Each tuple represents a test which raised an
1760 unexpected exception.
1761
Benjamin Peterson52baa292009-03-24 00:56:30 +00001762 .. attribute:: failures
1763
1764 A list containing 2-tuples of :class:`TestCase` instances and strings
1765 holding formatted tracebacks. Each tuple represents a test where a failure
Ezio Melottie2202362013-09-07 15:19:30 +03001766 was explicitly signalled using the :meth:`TestCase.assert\*` methods.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001767
Benjamin Peterson52baa292009-03-24 00:56:30 +00001768 .. attribute:: skipped
1769
1770 A list containing 2-tuples of :class:`TestCase` instances and strings
1771 holding the reason for skipping the test.
1772
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001773 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001774
1775 .. attribute:: expectedFailures
1776
Georg Brandl6faee4e2010-09-21 14:48:28 +00001777 A list containing 2-tuples of :class:`TestCase` instances and strings
1778 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001779 of the test case.
1780
1781 .. attribute:: unexpectedSuccesses
1782
1783 A list containing :class:`TestCase` instances that were marked as expected
1784 failures, but succeeded.
1785
1786 .. attribute:: shouldStop
1787
1788 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1789
Benjamin Peterson52baa292009-03-24 00:56:30 +00001790 .. attribute:: testsRun
1791
1792 The total number of tests run so far.
1793
Georg Brandl12037202010-12-02 22:35:25 +00001794 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001795
1796 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1797 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1798 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1799 fails or errors. Any output is also attached to the failure / error message.
1800
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001801 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001802
Benjamin Petersonb48af542010-04-11 20:43:16 +00001803 .. attribute:: failfast
1804
1805 If set to true :meth:`stop` will be called on the first failure or error,
1806 halting the test run.
1807
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001808 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001809
Robert Collinsf0c819a2015-03-06 13:46:35 +13001810 .. attribute:: tb_locals
1811
1812 If set to true then local variables will be shown in tracebacks.
1813
1814 .. versionadded:: 3.5
Benjamin Petersonb48af542010-04-11 20:43:16 +00001815
Benjamin Peterson52baa292009-03-24 00:56:30 +00001816 .. method:: wasSuccessful()
1817
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001818 Return ``True`` if all tests run so far have passed, otherwise returns
1819 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001820
Gregory P. Smith5a6d4bf2014-01-20 01:11:18 -08001821 .. versionchanged:: 3.4
1822 Returns ``False`` if there were any :attr:`unexpectedSuccesses`
1823 from tests marked with the :func:`expectedFailure` decorator.
1824
Benjamin Peterson52baa292009-03-24 00:56:30 +00001825 .. method:: stop()
1826
1827 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001828 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001829 :class:`TestRunner` objects should respect this flag and return without
1830 running any additional tests.
1831
1832 For example, this feature is used by the :class:`TextTestRunner` class to
1833 stop the test framework when the user signals an interrupt from the
1834 keyboard. Interactive tools which provide :class:`TestRunner`
1835 implementations can use this in a similar manner.
1836
1837 The following methods of the :class:`TestResult` class are used to maintain
1838 the internal data structures, and may be extended in subclasses to support
1839 additional reporting requirements. This is particularly useful in building
1840 tools which support interactive reporting while tests are being run.
1841
1842
1843 .. method:: startTest(test)
1844
1845 Called when the test case *test* is about to be run.
1846
Benjamin Peterson52baa292009-03-24 00:56:30 +00001847 .. method:: stopTest(test)
1848
1849 Called after the test case *test* has been executed, regardless of the
1850 outcome.
1851
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001852 .. method:: startTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001853
1854 Called once before any tests are executed.
1855
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001856 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001857
1858
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001859 .. method:: stopTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001860
Ezio Melotti176d6c42010-01-27 20:58:07 +00001861 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001862
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001863 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001864
1865
Benjamin Peterson52baa292009-03-24 00:56:30 +00001866 .. method:: addError(test, err)
1867
Ezio Melottie64a91a2013-09-07 15:23:36 +03001868 Called when the test case *test* raises an unexpected exception. *err* is a
Benjamin Peterson52baa292009-03-24 00:56:30 +00001869 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1870 traceback)``.
1871
1872 The default implementation appends a tuple ``(test, formatted_err)`` to
1873 the instance's :attr:`errors` attribute, where *formatted_err* is a
1874 formatted traceback derived from *err*.
1875
1876
1877 .. method:: addFailure(test, err)
1878
Benjamin Petersond2397752009-06-27 23:45:02 +00001879 Called when the test case *test* signals a failure. *err* is a tuple of
1880 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001881
1882 The default implementation appends a tuple ``(test, formatted_err)`` to
1883 the instance's :attr:`failures` attribute, where *formatted_err* is a
1884 formatted traceback derived from *err*.
1885
1886
1887 .. method:: addSuccess(test)
1888
1889 Called when the test case *test* succeeds.
1890
1891 The default implementation does nothing.
1892
1893
1894 .. method:: addSkip(test, reason)
1895
1896 Called when the test case *test* is skipped. *reason* is the reason the
1897 test gave for skipping.
1898
1899 The default implementation appends a tuple ``(test, reason)`` to the
1900 instance's :attr:`skipped` attribute.
1901
1902
1903 .. method:: addExpectedFailure(test, err)
1904
1905 Called when the test case *test* fails, but was marked with the
1906 :func:`expectedFailure` decorator.
1907
1908 The default implementation appends a tuple ``(test, formatted_err)`` to
1909 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1910 is a formatted traceback derived from *err*.
1911
1912
1913 .. method:: addUnexpectedSuccess(test)
1914
1915 Called when the test case *test* was marked with the
1916 :func:`expectedFailure` decorator, but succeeded.
1917
1918 The default implementation appends the test to the instance's
1919 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001920
Georg Brandl67b21b72010-08-17 15:07:14 +00001921
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001922 .. method:: addSubTest(test, subtest, outcome)
1923
1924 Called when a subtest finishes. *test* is the test case
1925 corresponding to the test method. *subtest* is a custom
1926 :class:`TestCase` instance describing the subtest.
1927
1928 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
1929 it failed with an exception where *outcome* is a tuple of the form
1930 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1931
1932 The default implementation does nothing when the outcome is a
1933 success, and records subtest failures as normal failures.
1934
1935 .. versionadded:: 3.4
1936
1937
Michael Foord34c94622010-02-10 15:51:42 +00001938.. class:: TextTestResult(stream, descriptions, verbosity)
1939
Georg Brandl67b21b72010-08-17 15:07:14 +00001940 A concrete implementation of :class:`TestResult` used by the
1941 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001942
Georg Brandl67b21b72010-08-17 15:07:14 +00001943 .. versionadded:: 3.2
1944 This class was previously named ``_TextTestResult``. The old name still
1945 exists as an alias but is deprecated.
1946
Georg Brandl116aa622007-08-15 14:28:22 +00001947
1948.. data:: defaultTestLoader
1949
1950 Instance of the :class:`TestLoader` class intended to be shared. If no
1951 customization of the :class:`TestLoader` is needed, this instance can be used
1952 instead of repeatedly creating new instances.
1953
1954
Ezio Melotti9c939bc2013-05-07 09:46:30 +03001955.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \
Robert Collinsf0c819a2015-03-06 13:46:35 +13001956 buffer=False, resultclass=None, warnings=None, *, tb_locals=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001957
Michael Foordd218e952011-01-03 12:55:11 +00001958 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001959 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001960 has a few configurable parameters, but is essentially very simple. Graphical
Robert Collinsf0c819a2015-03-06 13:46:35 +13001961 applications which run test suites should provide alternate implementations. Such
1962 implementations should accept ``**kwargs`` as the interface to construct runners
1963 changes when features are added to unittest.
Georg Brandl116aa622007-08-15 14:28:22 +00001964
Ezio Melotti60901872010-12-01 00:56:10 +00001965 By default this runner shows :exc:`DeprecationWarning`,
Senthil Kumaran409ea5d2014-02-08 14:28:03 -08001966 :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and
Larry Hastingsad88d7a2014-02-10 04:26:10 -08001967 :exc:`ImportWarning` even if they are :ref:`ignored by default
1968 <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest
1969 methods <deprecated-aliases>` are also special-cased and, when the warning
1970 filters are ``'default'`` or ``'always'``, they will appear only once
1971 per-module, in order to avoid too many warning messages. This behavior can
1972 be overridden using the :option:`-Wd` or :option:`-Wa` options and leaving
1973 *warnings* to ``None``.
Ezio Melotti60901872010-12-01 00:56:10 +00001974
Michael Foordd218e952011-01-03 12:55:11 +00001975 .. versionchanged:: 3.2
1976 Added the ``warnings`` argument.
1977
1978 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001979 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001980 than import time.
1981
Robert Collinsf0c819a2015-03-06 13:46:35 +13001982 .. versionchanged:: 3.5
1983 Added the tb_locals parameter.
1984
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001985 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001986
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001987 This method returns the instance of ``TestResult`` used by :meth:`run`.
1988 It is not intended to be called directly, but can be overridden in
1989 subclasses to provide a custom ``TestResult``.
1990
Michael Foord34c94622010-02-10 15:51:42 +00001991 ``_makeResult()`` instantiates the class or callable passed in the
1992 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001993 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001994 The result class is instantiated with the following arguments::
1995
1996 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001997
Michael Foord4d1639f2013-12-29 23:38:55 +00001998 .. method:: run(test)
1999
2000 This method is the main public interface to the `TextTestRunner`. This
2001 method takes a :class:`TestSuite` or :class:`TestCase` instance. A
2002 :class:`TestResult` is created by calling
2003 :func:`_makeResult` and the test(s) are run and the
2004 results printed to stdout.
2005
Ezio Melotti60901872010-12-01 00:56:10 +00002006
Georg Brandl419e3de2010-12-01 15:44:25 +00002007.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02002008 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00002009 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002010
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002011 A command-line program that loads a set of tests from *module* and runs them;
2012 this is primarily for making test modules conveniently executable.
2013 The simplest use for this function is to include the following line at the
2014 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00002015
2016 if __name__ == '__main__':
2017 unittest.main()
2018
Benjamin Petersond2397752009-06-27 23:45:02 +00002019 You can run tests with more detailed information by passing in the verbosity
2020 argument::
2021
2022 if __name__ == '__main__':
2023 unittest.main(verbosity=2)
2024
R David Murray6e731b02014-01-02 13:43:02 -05002025 The *defaultTest* argument is either the name of a single test or an
2026 iterable of test names to run if no test names are specified via *argv*. If
2027 not specified or ``None`` and no test names are provided via *argv*, all
2028 tests found in *module* are run.
R David Murray12e930f2014-01-02 13:37:26 -05002029
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002030 The *argv* argument can be a list of options passed to the program, with the
2031 first element being the program name. If not specified or ``None``,
2032 the values of :data:`sys.argv` are used.
2033
Georg Brandl116aa622007-08-15 14:28:22 +00002034 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002035 created instance of it. By default ``main`` calls :func:`sys.exit` with
2036 an exit code indicating success or failure of the tests run.
2037
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002038 The *testLoader* argument has to be a :class:`TestLoader` instance,
2039 and defaults to :data:`defaultTestLoader`.
2040
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002041 ``main`` supports being used from the interactive interpreter by passing in the
2042 argument ``exit=False``. This displays the result on standard output without
2043 calling :func:`sys.exit`::
2044
2045 >>> from unittest import main
2046 >>> main(module='test_module', exit=False)
2047
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002048 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00002049 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002050
Ezio Melotti60901872010-12-01 00:56:10 +00002051 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
2052 that should be used while running the tests. If it's not specified, it will
2053 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
2054 otherwise it will be set to ``'default'``.
2055
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002056 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
2057 This stores the result of the tests run as the ``result`` attribute.
2058
Éric Araujo971dc012010-12-16 03:13:05 +00002059 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002060 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00002061
Georg Brandl853947a2010-01-31 18:53:23 +00002062 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002063 The *verbosity*, *failfast*, *catchbreak*, *buffer*
2064 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00002065
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08002066 .. versionchanged:: 3.4
2067 The *defaultTest* parameter was changed to also accept an iterable of
2068 test names.
2069
Benjamin Petersond2397752009-06-27 23:45:02 +00002070
2071load_tests Protocol
2072###################
2073
Georg Brandl853947a2010-01-31 18:53:23 +00002074.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002075
Benjamin Petersond2397752009-06-27 23:45:02 +00002076Modules or packages can customize how tests are loaded from them during normal
2077test runs or test discovery by implementing a function called ``load_tests``.
2078
2079If a test module defines ``load_tests`` it will be called by
2080:meth:`TestLoader.loadTestsFromModule` with the following arguments::
2081
Barry Warsawd78742a2014-09-08 14:21:37 -04002082 load_tests(loader, standard_tests, pattern)
2083
2084where *pattern* is passed straight through from ``loadTestsFromModule``. It
2085defaults to ``None``.
Benjamin Petersond2397752009-06-27 23:45:02 +00002086
2087It should return a :class:`TestSuite`.
2088
2089*loader* is the instance of :class:`TestLoader` doing the loading.
2090*standard_tests* are the tests that would be loaded by default from the
2091module. It is common for test modules to only want to add or remove tests
2092from the standard set of tests.
2093The third argument is used when loading packages as part of test discovery.
2094
2095A typical ``load_tests`` function that loads tests from a specific set of
2096:class:`TestCase` classes may look like::
2097
2098 test_cases = (TestCase1, TestCase2, TestCase3)
2099
2100 def load_tests(loader, tests, pattern):
2101 suite = TestSuite()
2102 for test_class in test_cases:
2103 tests = loader.loadTestsFromTestCase(test_class)
2104 suite.addTests(tests)
2105 return suite
2106
Barry Warsawd78742a2014-09-08 14:21:37 -04002107If discovery is started in a directory containing a package, either from the
2108command line or by calling :meth:`TestLoader.discover`, then the package
2109:file:`__init__.py` will be checked for ``load_tests``. If that function does
2110not exist, discovery will recurse into the package as though it were just
2111another directory. Otherwise, discovery of the package's tests will be left up
2112to ``load_tests`` which is called with the following arguments::
Benjamin Petersond2397752009-06-27 23:45:02 +00002113
2114 load_tests(loader, standard_tests, pattern)
2115
2116This should return a :class:`TestSuite` representing all the tests
2117from the package. (``standard_tests`` will only contain tests
2118collected from :file:`__init__.py`.)
2119
2120Because the pattern is passed into ``load_tests`` the package is free to
2121continue (and potentially modify) test discovery. A 'do nothing'
2122``load_tests`` function for a test package would look like::
2123
2124 def load_tests(loader, standard_tests, pattern):
2125 # top level directory cached on loader instance
2126 this_dir = os.path.dirname(__file__)
2127 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2128 standard_tests.addTests(package_tests)
2129 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002130
Barry Warsawd78742a2014-09-08 14:21:37 -04002131.. versionchanged:: 3.5
2132 Discovery no longer checks package names for matching *pattern* due to the
2133 impossibility of package names matching the default pattern.
2134
2135
Benjamin Petersonb48af542010-04-11 20:43:16 +00002136
2137Class and Module Fixtures
2138-------------------------
2139
2140Class and module level fixtures are implemented in :class:`TestSuite`. When
2141the test suite encounters a test from a new class then :meth:`tearDownClass`
2142from the previous class (if there is one) is called, followed by
2143:meth:`setUpClass` from the new class.
2144
2145Similarly if a test is from a different module from the previous test then
2146``tearDownModule`` from the previous module is run, followed by
2147``setUpModule`` from the new module.
2148
2149After all the tests have run the final ``tearDownClass`` and
2150``tearDownModule`` are run.
2151
2152Note that shared fixtures do not play well with [potential] features like test
2153parallelization and they break test isolation. They should be used with care.
2154
2155The default ordering of tests created by the unittest test loaders is to group
2156all tests from the same modules and classes together. This will lead to
2157``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2158module. If you randomize the order, so that tests from different modules and
2159classes are adjacent to each other, then these shared fixture functions may be
2160called multiple times in a single test run.
2161
2162Shared fixtures are not intended to work with suites with non-standard
2163ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2164support shared fixtures.
2165
2166If there are any exceptions raised during one of the shared fixture functions
2167the test is reported as an error. Because there is no corresponding test
2168instance an ``_ErrorHolder`` object (that has the same interface as a
2169:class:`TestCase`) is created to represent the error. If you are just using
2170the standard unittest test runner then this detail doesn't matter, but if you
2171are a framework author it may be relevant.
2172
2173
2174setUpClass and tearDownClass
2175~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2176
2177These must be implemented as class methods::
2178
2179 import unittest
2180
2181 class Test(unittest.TestCase):
2182 @classmethod
2183 def setUpClass(cls):
2184 cls._connection = createExpensiveConnectionObject()
2185
2186 @classmethod
2187 def tearDownClass(cls):
2188 cls._connection.destroy()
2189
2190If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2191then you must call up to them yourself. The implementations in
2192:class:`TestCase` are empty.
2193
2194If an exception is raised during a ``setUpClass`` then the tests in the class
2195are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002196have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002197:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002198instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002199
2200
2201setUpModule and tearDownModule
2202~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2203
2204These should be implemented as functions::
2205
2206 def setUpModule():
2207 createConnection()
2208
2209 def tearDownModule():
2210 closeConnection()
2211
2212If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002213module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002214:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002215instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002216
2217
2218Signal Handling
2219---------------
2220
Georg Brandl419e3de2010-12-01 15:44:25 +00002221.. versionadded:: 3.2
2222
Éric Araujo8acb67c2010-11-26 23:31:07 +00002223The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002224along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2225more friendly handling of control-C during a test run. With catch break
2226behavior enabled control-C will allow the currently running test to complete,
2227and the test run will then end and report all the results so far. A second
2228control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002229
Michael Foordde4ceab2010-04-25 19:53:49 +00002230The control-c handling signal handler attempts to remain compatible with code or
2231tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2232handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2233i.e. it has been replaced by the system under test and delegated to, then it
2234calls the default handler. This will normally be the expected behavior by code
2235that replaces an installed handler and delegates to it. For individual tests
2236that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2237decorator can be used.
2238
2239There are a few utility functions for framework authors to enable control-c
2240handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002241
2242.. function:: installHandler()
2243
2244 Install the control-c handler. When a :const:`signal.SIGINT` is received
2245 (usually in response to the user pressing control-c) all registered results
2246 have :meth:`~TestResult.stop` called.
2247
Michael Foord469b1f02010-04-26 23:41:26 +00002248
Benjamin Petersonb48af542010-04-11 20:43:16 +00002249.. function:: registerResult(result)
2250
2251 Register a :class:`TestResult` object for control-c handling. Registering a
2252 result stores a weak reference to it, so it doesn't prevent the result from
2253 being garbage collected.
2254
Michael Foordde4ceab2010-04-25 19:53:49 +00002255 Registering a :class:`TestResult` object has no side-effects if control-c
2256 handling is not enabled, so test frameworks can unconditionally register
2257 all results they create independently of whether or not handling is enabled.
2258
Michael Foord469b1f02010-04-26 23:41:26 +00002259
Benjamin Petersonb48af542010-04-11 20:43:16 +00002260.. function:: removeResult(result)
2261
2262 Remove a registered result. Once a result has been removed then
2263 :meth:`~TestResult.stop` will no longer be called on that result object in
2264 response to a control-c.
2265
Michael Foord469b1f02010-04-26 23:41:26 +00002266
Michael Foordde4ceab2010-04-25 19:53:49 +00002267.. function:: removeHandler(function=None)
2268
2269 When called without arguments this function removes the control-c handler
2270 if it has been installed. This function can also be used as a test decorator
2271 to temporarily remove the handler whilst the test is being executed::
2272
2273 @unittest.removeHandler
2274 def test_signal_handling(self):
2275 ...