blob: 93ccd0fd61139c322948c79758639adbd723c6f5 [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.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
9.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
10.. sectionauthor:: Raymond Hettinger <python@rcn.com>
11
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040012**Source code:** :source:`Lib/unittest/__init__.py`
13
14--------------
15
Ezio Melotti22170ed2010-11-20 09:57:27 +000016(If you are already familiar with the basic concepts of testing, you might want
17to skip to :ref:`the list of assert methods <assert-methods>`.)
Georg Brandl116aa622007-08-15 14:28:22 +000018
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010019The :mod:`unittest` unit testing framework was originally inspired by JUnit
20and has a similar flavor as major unit testing frameworks in other
21languages. It supports test automation, sharing of setup and shutdown code
22for tests, aggregation of tests into collections, and independence of the
23tests from the reporting framework.
Georg Brandl116aa622007-08-15 14:28:22 +000024
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010025To achieve this, :mod:`unittest` supports some important concepts in an
26object-oriented way:
Georg Brandl116aa622007-08-15 14:28:22 +000027
28test fixture
29 A :dfn:`test fixture` represents the preparation needed to perform one or more
30 tests, and any associate cleanup actions. This may involve, for example,
31 creating temporary or proxy databases, directories, or starting a server
32 process.
33
34test case
Antoine Pitrou2c5e9502013-01-20 01:29:39 +010035 A :dfn:`test case` is the individual unit of testing. It checks for a specific
Georg Brandl116aa622007-08-15 14:28:22 +000036 response to a particular set of inputs. :mod:`unittest` provides a base class,
37 :class:`TestCase`, which may be used to create new test cases.
38
39test suite
40 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
41 used to aggregate tests that should be executed together.
42
43test runner
44 A :dfn:`test runner` is a component which orchestrates the execution of tests
45 and provides the outcome to the user. The runner may use a graphical interface,
46 a textual interface, or return a special value to indicate the results of
47 executing the tests.
48
Georg Brandl116aa622007-08-15 14:28:22 +000049
50.. seealso::
51
52 Module :mod:`doctest`
53 Another test-support module with a very different flavor.
54
R David Murraya1005ed2015-07-04 15:44:14 -040055 `Simple Smalltalk Testing: With Patterns <https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000056 Kent Beck's original paper on testing frameworks using the pattern shared
57 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000058
Sanyam Khurana1b4587a2017-12-06 22:09:33 +053059 `Nose <https://nose.readthedocs.io/>`_ and `py.test <https://docs.pytest.org/>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000060 Third-party unittest frameworks with a lighter-weight syntax for writing
61 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000062
Georg Brandle73778c2014-10-29 08:36:35 +010063 `The Python Testing Tools Taxonomy <https://wiki.python.org/moin/PythonTestingToolsTaxonomy>`_
Benjamin Petersonb48af542010-04-11 20:43:16 +000064 An extensive list of Python testing tools including functional testing
65 frameworks and mock object libraries.
Benjamin Petersond2397752009-06-27 23:45:02 +000066
Benjamin Petersonb48af542010-04-11 20:43:16 +000067 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
68 A special-interest-group for discussion of testing, and testing tools,
69 in Python.
Benjamin Petersond2397752009-06-27 23:45:02 +000070
Michael Foord90efac72011-01-03 15:39:49 +000071 The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is
72 a GUI tool for test discovery and execution. This is intended largely for ease of use
Senthil Kumaran847c33c2012-10-27 11:04:55 -070073 for those new to unit testing. For production environments it is
74 recommended that tests be driven by a continuous integration system such as
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030075 `Buildbot <https://buildbot.net/>`_, `Jenkins <https://jenkins.io/>`_
Senthil Kumaran847c33c2012-10-27 11:04:55 -070076 or `Hudson <http://hudson-ci.org/>`_.
Michael Foord90efac72011-01-03 15:39:49 +000077
78
Georg Brandl116aa622007-08-15 14:28:22 +000079.. _unittest-minimal-example:
80
81Basic example
82-------------
83
84The :mod:`unittest` module provides a rich set of tools for constructing and
85running tests. This section demonstrates that a small subset of the tools
86suffice to meet the needs of most users.
87
Ezio Melotti2e3998f2015-03-24 12:42:41 +020088Here is a short script to test three string methods::
Georg Brandl116aa622007-08-15 14:28:22 +000089
Ezio Melotti2e3998f2015-03-24 12:42:41 +020090 import unittest
Georg Brandl116aa622007-08-15 14:28:22 +000091
Ezio Melotti2e3998f2015-03-24 12:42:41 +020092 class TestStringMethods(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +000093
Serhiy Storchakadba90392016-05-10 12:01:23 +030094 def test_upper(self):
95 self.assertEqual('foo'.upper(), 'FOO')
Georg Brandl116aa622007-08-15 14:28:22 +000096
Serhiy Storchakadba90392016-05-10 12:01:23 +030097 def test_isupper(self):
98 self.assertTrue('FOO'.isupper())
99 self.assertFalse('Foo'.isupper())
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Serhiy Storchakadba90392016-05-10 12:01:23 +0300101 def test_split(self):
102 s = 'hello world'
103 self.assertEqual(s.split(), ['hello', 'world'])
104 # check that s.split fails when the separator is not a string
105 with self.assertRaises(TypeError):
106 s.split(2)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000107
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200108 if __name__ == '__main__':
109 unittest.main()
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Benjamin Peterson52baa292009-03-24 00:56:30 +0000112A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000113individual tests are defined with methods whose names start with the letters
114``test``. This naming convention informs the test runner about which methods
115represent tests.
116
Benjamin Peterson52baa292009-03-24 00:56:30 +0000117The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200118expected result; :meth:`~TestCase.assertTrue` or :meth:`~TestCase.assertFalse`
119to verify a condition; or :meth:`~TestCase.assertRaises` to verify that a
120specific exception gets raised. These methods are used instead of the
121:keyword:`assert` statement so the test runner can accumulate all test results
122and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200124The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you
125to define instructions that will be executed before and after each test method.
Benjamin Peterson8a6ddb92016-01-07 22:01:26 -0800126They are covered in more detail in the section :ref:`organizing-tests`.
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000129provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000130line, the above script produces an output that looks like this::
131
132 ...
133 ----------------------------------------------------------------------
134 Ran 3 tests in 0.000s
135
136 OK
137
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100138Passing the ``-v`` option to your test script will instruct :func:`unittest.main`
139to enable a higher level of verbosity, and produce the following output::
Georg Brandl116aa622007-08-15 14:28:22 +0000140
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200141 test_isupper (__main__.TestStringMethods) ... ok
142 test_split (__main__.TestStringMethods) ... ok
143 test_upper (__main__.TestStringMethods) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145 ----------------------------------------------------------------------
Ezio Melotti2e3998f2015-03-24 12:42:41 +0200146 Ran 3 tests in 0.001s
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148 OK
149
150The above examples show the most commonly used :mod:`unittest` features which
151are sufficient to meet many everyday testing needs. The remainder of the
152documentation explores the full feature set from first principles.
153
Benjamin Petersonb48af542010-04-11 20:43:16 +0000154
155.. _unittest-command-line-interface:
156
Éric Araujo76338ec2010-11-26 23:46:18 +0000157Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000158----------------------
159
160The unittest module can be used from the command line to run tests from
161modules, classes or even individual test methods::
162
163 python -m unittest test_module1 test_module2
164 python -m unittest test_module.TestClass
165 python -m unittest test_module.TestClass.test_method
166
167You can pass in a list with any combination of module names, and fully
168qualified class or method names.
169
Michael Foord37d120a2010-12-04 01:11:21 +0000170Test modules can be specified by file path as well::
171
172 python -m unittest tests/test_something.py
173
174This allows you to use the shell filename completion to specify the test module.
175The file specified must still be importable as a module. The path is converted
176to a module name by removing the '.py' and converting path separators into '.'.
177If you want to execute a test file that isn't importable as a module you should
178execute the file directly instead.
179
Benjamin Petersonb48af542010-04-11 20:43:16 +0000180You can run tests with more detail (higher verbosity) by passing in the -v flag::
181
182 python -m unittest -v test_module
183
Michael Foord086f3082010-11-21 21:28:01 +0000184When executed without arguments :ref:`unittest-test-discovery` is started::
185
186 python -m unittest
187
Éric Araujo713d3032010-11-18 16:38:46 +0000188For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000189
190 python -m unittest -h
191
Georg Brandl67b21b72010-08-17 15:07:14 +0000192.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000193 In earlier versions it was only possible to run individual test methods and
194 not modules or classes.
195
196
Éric Araujo76338ec2010-11-26 23:46:18 +0000197Command-line options
198~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000199
Éric Araujod3309df2010-11-21 03:09:17 +0000200:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000201
Éric Araujo713d3032010-11-18 16:38:46 +0000202.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000203
Éric Araujo713d3032010-11-18 16:38:46 +0000204.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000205
Éric Araujo713d3032010-11-18 16:38:46 +0000206 The standard output and standard error streams are buffered during the test
207 run. Output during a passing test is discarded. Output is echoed normally
208 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000209
Éric Araujo713d3032010-11-18 16:38:46 +0000210.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000211
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300212 :kbd:`Control-C` during the test run waits for the current test to end and then
213 reports all the results so far. A second :kbd:`Control-C` raises the normal
Éric Araujo713d3032010-11-18 16:38:46 +0000214 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000215
Éric Araujo713d3032010-11-18 16:38:46 +0000216 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000217
Éric Araujo713d3032010-11-18 16:38:46 +0000218.. cmdoption:: -f, --failfast
219
220 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000221
Jonas Haag5b48dc62017-11-25 16:23:52 +0100222.. cmdoption:: -k
223
224 Only run test methods and classes that match the pattern or substring.
225 This option may be used multiple times, in which case all test cases that
226 match of the given patterns are included.
227
228 Patterns that contain a wildcard character (``*``) are matched against the
229 test name using :meth:`fnmatch.fnmatchcase`; otherwise simple case-sensitive
230 substring matching is used.
231
232 Patterns are matched against the fully qualified test method name as
233 imported by the test loader.
234
235 For example, ``-k foo`` matches ``foo_tests.SomeTest.test_something``,
236 ``bar_tests.SomeTest.test_foo``, but not ``bar_tests.FooTest.test_something``.
237
Robert Collinsf0c819a2015-03-06 13:46:35 +1300238.. cmdoption:: --locals
239
240 Show local variables in tracebacks.
241
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000242.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000243 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000244
Robert Collinsf0c819a2015-03-06 13:46:35 +1300245.. versionadded:: 3.5
246 The command-line option ``--locals``.
247
Jonas Haag5b48dc62017-11-25 16:23:52 +0100248.. versionadded:: 3.7
249 The command-line option ``-k``.
250
Benjamin Petersonb48af542010-04-11 20:43:16 +0000251The command line can also be used for test discovery, for running all of the
252tests in a project or just a subset.
253
254
255.. _unittest-test-discovery:
256
257Test Discovery
258--------------
259
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000260.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000261
Ezio Melotti3d995842011-03-08 16:17:35 +0200262Unittest supports simple test discovery. In order to be compatible with test
263discovery, all of the test files must be :ref:`modules <tut-modules>` or
Larry Hastings3732ed22014-03-15 21:13:56 -0700264:ref:`packages <tut-packages>` (including :term:`namespace packages
265<namespace package>`) importable from the top-level directory of
266the project (this means that their filenames must be valid :ref:`identifiers
267<identifiers>`).
Benjamin Petersonb48af542010-04-11 20:43:16 +0000268
269Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000270used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000271
272 cd project_directory
273 python -m unittest discover
274
Michael Foord086f3082010-11-21 21:28:01 +0000275.. note::
276
277 As a shortcut, ``python -m unittest`` is the equivalent of
278 ``python -m unittest discover``. If you want to pass arguments to test
Éric Araujo941afed2011-09-01 02:47:34 +0200279 discovery the ``discover`` sub-command must be used explicitly.
Michael Foord086f3082010-11-21 21:28:01 +0000280
Benjamin Petersonb48af542010-04-11 20:43:16 +0000281The ``discover`` sub-command has the following options:
282
Éric Araujo713d3032010-11-18 16:38:46 +0000283.. program:: unittest discover
284
285.. cmdoption:: -v, --verbose
286
287 Verbose output
288
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800289.. cmdoption:: -s, --start-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000290
Éric Araujo941afed2011-09-01 02:47:34 +0200291 Directory to start discovery (``.`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000292
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800293.. cmdoption:: -p, --pattern pattern
Éric Araujo713d3032010-11-18 16:38:46 +0000294
Éric Araujo941afed2011-09-01 02:47:34 +0200295 Pattern to match test files (``test*.py`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000296
Chris Jerdonekd69ad552013-02-21 18:54:43 -0800297.. cmdoption:: -t, --top-level-directory directory
Éric Araujo713d3032010-11-18 16:38:46 +0000298
299 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000300
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000301The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
302as positional arguments in that order. The following two command lines
303are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000304
Robert Collinsa2b00552015-08-24 12:14:28 +1200305 python -m unittest discover -s project_directory -p "*_test.py"
306 python -m unittest discover project_directory "*_test.py"
Benjamin Petersonb48af542010-04-11 20:43:16 +0000307
Michael Foord16f3e902010-05-08 15:13:42 +0000308As well as being a path it is possible to pass a package name, for example
309``myproject.subpackage.test``, as the start directory. The package name you
310supply will then be imported and its location on the filesystem will be used
311as the start directory.
312
313.. caution::
314
Senthil Kumaran916bd382010-10-15 12:55:19 +0000315 Test discovery loads tests by importing them. Once test discovery has found
316 all the test files from the start directory you specify it turns the paths
317 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000318 imported as ``foo.bar.baz``.
319
320 If you have a package installed globally and attempt test discovery on
321 a different copy of the package then the import *could* happen from the
322 wrong place. If this happens test discovery will warn you and exit.
323
324 If you supply the start directory as a package name rather than a
325 path to a directory then discover assumes that whichever location it
326 imports from is the location you intended, so you will not get the
327 warning.
328
Benjamin Petersonb48af542010-04-11 20:43:16 +0000329Test modules and packages can customize test loading and discovery by through
330the `load_tests protocol`_.
331
Larry Hastings3732ed22014-03-15 21:13:56 -0700332.. versionchanged:: 3.4
333 Test discovery supports :term:`namespace packages <namespace package>`.
334
Benjamin Petersonb48af542010-04-11 20:43:16 +0000335
Georg Brandl116aa622007-08-15 14:28:22 +0000336.. _organizing-tests:
337
338Organizing test code
339--------------------
340
341The basic building blocks of unit testing are :dfn:`test cases` --- single
342scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000343test cases are represented by :class:`unittest.TestCase` instances.
344To make your own test cases you must write subclasses of
345:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
Georg Brandl116aa622007-08-15 14:28:22 +0000347The testing code of a :class:`TestCase` instance should be entirely self
348contained, such that it can be run either in isolation or in arbitrary
349combination with any number of other test cases.
350
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100351The simplest :class:`TestCase` subclass will simply implement a test method
352(i.e. a method whose name starts with ``test``) in order to perform specific
353testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355 import unittest
356
357 class DefaultWidgetSizeTestCase(unittest.TestCase):
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100358 def test_default_widget_size(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000359 widget = Widget('The widget')
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100360 self.assertEqual(widget.size(), (50, 50))
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Sandro Tosi41b24042012-01-21 10:59:37 +0100362Note that in order to test something, we use one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000363methods provided by the :class:`TestCase` base class. If the test fails, an
364exception will be raised, and :mod:`unittest` will identify the test case as a
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100365:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100367Tests can be numerous, and their set-up can be repetitive. Luckily, we
368can factor out set-up code by implementing a method called
369:meth:`~TestCase.setUp`, which the testing framework will automatically
370call for every single test we run::
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372 import unittest
373
Berker Peksagab75e022016-08-06 03:00:03 +0300374 class WidgetTestCase(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000375 def setUp(self):
376 self.widget = Widget('The widget')
377
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100378 def test_default_widget_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000379 self.assertEqual(self.widget.size(), (50,50),
380 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100382 def test_widget_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000383 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000384 self.assertEqual(self.widget.size(), (100,150),
385 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000386
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100387.. note::
388 The order in which the various tests will be run is determined
389 by sorting the test method names with respect to the built-in
390 ordering for strings.
391
Benjamin Peterson52baa292009-03-24 00:56:30 +0000392If the :meth:`~TestCase.setUp` method raises an exception while the test is
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100393running, the framework will consider the test to have suffered an error, and
394the test method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000395
Benjamin Peterson52baa292009-03-24 00:56:30 +0000396Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100397after the test method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399 import unittest
400
Berker Peksagab75e022016-08-06 03:00:03 +0300401 class WidgetTestCase(unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000402 def setUp(self):
403 self.widget = Widget('The widget')
404
405 def tearDown(self):
406 self.widget.dispose()
Georg Brandl116aa622007-08-15 14:28:22 +0000407
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100408If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be
409run whether the test method succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000410
411Such a working environment for the testing code is called a :dfn:`fixture`.
412
Georg Brandl116aa622007-08-15 14:28:22 +0000413Test case instances are grouped together according to the features they test.
414:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100415represented by :mod:`unittest`'s :class:`TestSuite` class. In most cases,
416calling :func:`unittest.main` will do the right thing and collect all the
417module's test cases for you, and then execute them.
Georg Brandl116aa622007-08-15 14:28:22 +0000418
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100419However, should you want to customize the building of your test suite,
420you can do it yourself::
Georg Brandl116aa622007-08-15 14:28:22 +0000421
422 def suite():
423 suite = unittest.TestSuite()
Berker Peksag92551042017-10-13 06:41:57 +0300424 suite.addTest(WidgetTestCase('test_default_widget_size'))
425 suite.addTest(WidgetTestCase('test_widget_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000426 return suite
427
Berker Peksag92551042017-10-13 06:41:57 +0300428 if __name__ == '__main__':
429 runner = unittest.TextTestRunner()
430 runner.run(suite())
431
Georg Brandl116aa622007-08-15 14:28:22 +0000432You can place the definitions of test cases and test suites in the same modules
433as the code they are to test (such as :file:`widget.py`), but there are several
434advantages to placing the test code in a separate module, such as
435:file:`test_widget.py`:
436
437* The test module can be run standalone from the command line.
438
439* The test code can more easily be separated from shipped code.
440
441* There is less temptation to change test code to fit the code it tests without
442 a good reason.
443
444* Test code should be modified much less frequently than the code it tests.
445
446* Tested code can be refactored more easily.
447
448* Tests for modules written in C must be in separate modules anyway, so why not
449 be consistent?
450
451* If the testing strategy changes, there is no need to change the source code.
452
453
454.. _legacy-unit-tests:
455
456Re-using old test code
457----------------------
458
459Some users will find that they have existing test code that they would like to
460run from :mod:`unittest`, without converting every old test function to a
461:class:`TestCase` subclass.
462
463For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
464This subclass of :class:`TestCase` can be used to wrap an existing test
465function. Set-up and tear-down functions can also be provided.
466
467Given the following test function::
468
469 def testSomething():
470 something = makeSomething()
471 assert something.name is not None
472 # ...
473
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100474one can create an equivalent test case instance as follows, with optional
475set-up and tear-down methods::
Georg Brandl116aa622007-08-15 14:28:22 +0000476
477 testcase = unittest.FunctionTestCase(testSomething,
478 setUp=makeSomethingDB,
479 tearDown=deleteSomethingDB)
480
Georg Brandl116aa622007-08-15 14:28:22 +0000481.. note::
482
Benjamin Petersond2397752009-06-27 23:45:02 +0000483 Even though :class:`FunctionTestCase` can be used to quickly convert an
484 existing test base over to a :mod:`unittest`\ -based system, this approach is
485 not recommended. Taking the time to set up proper :class:`TestCase`
486 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000487
Benjamin Peterson52baa292009-03-24 00:56:30 +0000488In some cases, the existing tests may have been written using the :mod:`doctest`
489module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
490automatically build :class:`unittest.TestSuite` instances from the existing
491:mod:`doctest`\ -based tests.
492
Georg Brandl116aa622007-08-15 14:28:22 +0000493
Benjamin Peterson5254c042009-03-23 22:25:03 +0000494.. _unittest-skipping:
495
496Skipping tests and expected failures
497------------------------------------
498
Michael Foordf5c851a2010-02-05 21:48:03 +0000499.. versionadded:: 3.1
500
Benjamin Peterson5254c042009-03-23 22:25:03 +0000501Unittest supports skipping individual test methods and even whole classes of
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200502tests. In addition, it supports marking a test as an "expected failure," a test
Benjamin Peterson5254c042009-03-23 22:25:03 +0000503that is broken and will fail, but shouldn't be counted as a failure on a
504:class:`TestResult`.
505
506Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
507or one of its conditional variants.
508
Ezio Melottifed69ba2013-03-01 21:26:04 +0200509Basic skipping looks like this::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000510
511 class MyTestCase(unittest.TestCase):
512
513 @unittest.skip("demonstrating skipping")
514 def test_nothing(self):
515 self.fail("shouldn't happen")
516
Benjamin Petersond2397752009-06-27 23:45:02 +0000517 @unittest.skipIf(mylib.__version__ < (1, 3),
518 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000519 def test_format(self):
520 # Tests that work for only a certain version of the library.
521 pass
522
523 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
524 def test_windows_support(self):
525 # windows specific testing code
526 pass
527
Ezio Melottifed69ba2013-03-01 21:26:04 +0200528This is the output of running the example above in verbose mode::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000529
Benjamin Petersonded31c42009-03-30 15:04:16 +0000530 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000531 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000532 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000533
534 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000535 Ran 3 tests in 0.005s
536
537 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000538
Ezio Melottifed69ba2013-03-01 21:26:04 +0200539Classes can be skipped just like methods::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000540
Sandro Tosi317075d2012-03-31 18:34:59 +0200541 @unittest.skip("showing class skipping")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000542 class MySkippedTestCase(unittest.TestCase):
543 def test_not_run(self):
544 pass
545
Benjamin Peterson52baa292009-03-24 00:56:30 +0000546:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
547that needs to be set up is not available.
548
Benjamin Peterson5254c042009-03-23 22:25:03 +0000549Expected failures use the :func:`expectedFailure` decorator. ::
550
551 class ExpectedFailureTestCase(unittest.TestCase):
552 @unittest.expectedFailure
553 def test_fail(self):
554 self.assertEqual(1, 0, "broken")
555
556It's easy to roll your own skipping decorators by making a decorator that calls
557:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottifed69ba2013-03-01 21:26:04 +0200558the test unless the passed object has a certain attribute::
Benjamin Peterson5254c042009-03-23 22:25:03 +0000559
560 def skipUnlessHasattr(obj, attr):
561 if hasattr(obj, attr):
562 return lambda func: func
Ezio Melotti265281a2013-03-27 20:11:55 +0200563 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson5254c042009-03-23 22:25:03 +0000564
565The following decorators implement test skipping and expected failures:
566
Georg Brandl8a1caa22010-07-29 16:01:11 +0000567.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000568
569 Unconditionally skip the decorated test. *reason* should describe why the
570 test is being skipped.
571
Georg Brandl8a1caa22010-07-29 16:01:11 +0000572.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000573
574 Skip the decorated test if *condition* is true.
575
Georg Brandl8a1caa22010-07-29 16:01:11 +0000576.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000577
Georg Brandl6faee4e2010-09-21 14:48:28 +0000578 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000579
Georg Brandl8a1caa22010-07-29 16:01:11 +0000580.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000581
582 Mark the test as an expected failure. If the test fails when run, the test
583 is not counted as a failure.
584
Ezio Melotti265281a2013-03-27 20:11:55 +0200585.. exception:: SkipTest(reason)
586
587 This exception is raised to skip a test.
588
589 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
590 decorators instead of raising this directly.
591
R David Murray42fa1102014-01-03 13:03:36 -0500592Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them.
593Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run.
594Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000595
Benjamin Peterson5254c042009-03-23 22:25:03 +0000596
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100597.. _subtests:
598
599Distinguishing test iterations using subtests
600---------------------------------------------
601
602.. versionadded:: 3.4
603
604When some of your tests differ only by a some very small differences, for
605instance some parameters, unittest allows you to distinguish them inside
606the body of a test method using the :meth:`~TestCase.subTest` context manager.
607
608For example, the following test::
609
610 class NumbersTest(unittest.TestCase):
611
612 def test_even(self):
613 """
614 Test that numbers between 0 and 5 are all even.
615 """
616 for i in range(0, 6):
617 with self.subTest(i=i):
618 self.assertEqual(i % 2, 0)
619
620will produce the following output::
621
622 ======================================================================
623 FAIL: test_even (__main__.NumbersTest) (i=1)
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 ======================================================================
631 FAIL: test_even (__main__.NumbersTest) (i=3)
632 ----------------------------------------------------------------------
633 Traceback (most recent call last):
634 File "subtests.py", line 32, in test_even
635 self.assertEqual(i % 2, 0)
636 AssertionError: 1 != 0
637
638 ======================================================================
639 FAIL: test_even (__main__.NumbersTest) (i=5)
640 ----------------------------------------------------------------------
641 Traceback (most recent call last):
642 File "subtests.py", line 32, in test_even
643 self.assertEqual(i % 2, 0)
644 AssertionError: 1 != 0
645
646Without using a subtest, execution would stop after the first failure,
647and the error would be less easy to diagnose because the value of ``i``
648wouldn't be displayed::
649
650 ======================================================================
651 FAIL: test_even (__main__.NumbersTest)
652 ----------------------------------------------------------------------
653 Traceback (most recent call last):
654 File "subtests.py", line 32, in test_even
655 self.assertEqual(i % 2, 0)
656 AssertionError: 1 != 0
657
658
Georg Brandl116aa622007-08-15 14:28:22 +0000659.. _unittest-contents:
660
661Classes and functions
662---------------------
663
Benjamin Peterson52baa292009-03-24 00:56:30 +0000664This section describes in depth the API of :mod:`unittest`.
665
666
667.. _testcase-objects:
668
669Test cases
670~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000671
Georg Brandl7f01a132009-09-16 15:58:14 +0000672.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000673
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100674 Instances of the :class:`TestCase` class represent the logical test units
Georg Brandl116aa622007-08-15 14:28:22 +0000675 in the :mod:`unittest` universe. This class is intended to be used as a base
676 class, with specific tests being implemented by concrete subclasses. This class
677 implements the interface needed by the test runner to allow it to drive the
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100678 tests, and methods that the test code can use to check for and report various
Georg Brandl116aa622007-08-15 14:28:22 +0000679 kinds of failure.
680
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100681 Each instance of :class:`TestCase` will run a single base method: the method
Robert Collinse02f6c22015-07-23 06:37:26 +1200682 named *methodName*.
683 In most uses of :class:`TestCase`, you will neither change
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100684 the *methodName* nor reimplement the default ``runTest()`` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Michael Foord1341bb02011-03-14 19:01:46 -0400686 .. versionchanged:: 3.2
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100687 :class:`TestCase` can be instantiated successfully without providing a
688 *methodName*. This makes it easier to experiment with :class:`TestCase`
689 from the interactive interpreter.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000690
691 :class:`TestCase` instances provide three groups of methods: one group used
692 to run the test, another used by the test implementation to check conditions
693 and report failures, and some inquiry methods allowing information about the
694 test itself to be gathered.
695
696 Methods in the first group (running the test) are:
697
Benjamin Peterson52baa292009-03-24 00:56:30 +0000698 .. method:: setUp()
699
700 Method called to prepare the test fixture. This is called immediately
Terry Jan Reedy7f84d1e2014-04-15 23:44:14 -0400701 before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`,
702 any exception raised by this method will be considered an error rather than
Terry Jan Reedy6ac42402014-04-15 23:38:18 -0400703 a test failure. The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000704
705
706 .. method:: tearDown()
707
708 Method called immediately after the test method has been called and the
709 result recorded. This is called even if the test method raised an
710 exception, so the implementation in subclasses may need to be particularly
Ezio Melotti8dea74f2016-03-13 09:40:09 +0200711 careful about checking internal state. Any exception, other than
712 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
713 considered an additional error rather than a test failure (thus increasing
714 the total number of reported errors). This method will only be called if
715 the :meth:`setUp` succeeds, regardless of the outcome of the test method.
716 The default implementation does nothing.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000717
718
Benjamin Petersonb48af542010-04-11 20:43:16 +0000719 .. method:: setUpClass()
720
721 A class method called before tests in an individual class run.
722 ``setUpClass`` is called with the class as the only argument
723 and must be decorated as a :func:`classmethod`::
724
725 @classmethod
726 def setUpClass(cls):
727 ...
728
729 See `Class and Module Fixtures`_ for more details.
730
731 .. versionadded:: 3.2
732
733
734 .. method:: tearDownClass()
735
736 A class method called after tests in an individual class have run.
737 ``tearDownClass`` is called with the class as the only argument
738 and must be decorated as a :meth:`classmethod`::
739
740 @classmethod
741 def tearDownClass(cls):
742 ...
743
744 See `Class and Module Fixtures`_ for more details.
745
746 .. versionadded:: 3.2
747
748
Georg Brandl7f01a132009-09-16 15:58:14 +0000749 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000750
Antoine Pitrou2c5e9502013-01-20 01:29:39 +0100751 Run the test, collecting the result into the :class:`TestResult` object
752 passed as *result*. If *result* is omitted or ``None``, a temporary
753 result object is created (by calling the :meth:`defaultTestResult`
754 method) and used. The result object is returned to :meth:`run`'s
755 caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000756
757 The same effect may be had by simply calling the :class:`TestCase`
758 instance.
759
Michael Foord1341bb02011-03-14 19:01:46 -0400760 .. versionchanged:: 3.3
761 Previous versions of ``run`` did not return the result. Neither did
762 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000763
Benjamin Petersone549ead2009-03-28 21:42:05 +0000764 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000765
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000766 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000767 test. See :ref:`unittest-skipping` for more information.
768
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000769 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000770
Benjamin Peterson52baa292009-03-24 00:56:30 +0000771
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100772 .. method:: subTest(msg=None, **params)
773
774 Return a context manager which executes the enclosed code block as a
775 subtest. *msg* and *params* are optional, arbitrary values which are
776 displayed whenever a subtest fails, allowing you to identify them
777 clearly.
778
779 A test case can contain any number of subtest declarations, and
780 they can be arbitrarily nested.
781
782 See :ref:`subtests` for more information.
783
784 .. versionadded:: 3.4
785
786
Benjamin Peterson52baa292009-03-24 00:56:30 +0000787 .. method:: debug()
788
789 Run the test without collecting the result. This allows exceptions raised
790 by the test to be propagated to the caller, and can be used to support
791 running tests under a debugger.
792
Ezio Melotti22170ed2010-11-20 09:57:27 +0000793 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000794
Ezio Melottif418db22016-01-12 11:03:31 +0200795 The :class:`TestCase` class provides several assert methods to check for and
796 report failures. The following table lists the most commonly used methods
797 (see the tables below for more assert methods):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000798
Ezio Melotti4370b302010-11-03 20:39:14 +0000799 +-----------------------------------------+-----------------------------+---------------+
800 | Method | Checks that | New in |
801 +=========================================+=============================+===============+
802 | :meth:`assertEqual(a, b) | ``a == b`` | |
803 | <TestCase.assertEqual>` | | |
804 +-----------------------------------------+-----------------------------+---------------+
805 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
806 | <TestCase.assertNotEqual>` | | |
807 +-----------------------------------------+-----------------------------+---------------+
808 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
809 | <TestCase.assertTrue>` | | |
810 +-----------------------------------------+-----------------------------+---------------+
811 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
812 | <TestCase.assertFalse>` | | |
813 +-----------------------------------------+-----------------------------+---------------+
814 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
815 | <TestCase.assertIs>` | | |
816 +-----------------------------------------+-----------------------------+---------------+
817 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
818 | <TestCase.assertIsNot>` | | |
819 +-----------------------------------------+-----------------------------+---------------+
820 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
821 | <TestCase.assertIsNone>` | | |
822 +-----------------------------------------+-----------------------------+---------------+
823 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
824 | <TestCase.assertIsNotNone>` | | |
825 +-----------------------------------------+-----------------------------+---------------+
826 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
827 | <TestCase.assertIn>` | | |
828 +-----------------------------------------+-----------------------------+---------------+
829 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
830 | <TestCase.assertNotIn>` | | |
831 +-----------------------------------------+-----------------------------+---------------+
832 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
833 | <TestCase.assertIsInstance>` | | |
834 +-----------------------------------------+-----------------------------+---------------+
835 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
836 | <TestCase.assertNotIsInstance>` | | |
837 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000838
Ezio Melottib4dc2502011-05-06 15:01:41 +0300839 All the assert methods accept a *msg* argument that, if specified, is used
840 as the error message on failure (see also :data:`longMessage`).
841 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
842 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
843 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000844
Michael Foorde180d392011-01-28 19:51:48 +0000845 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000846
Michael Foorde180d392011-01-28 19:51:48 +0000847 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000848 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000849
Michael Foorde180d392011-01-28 19:51:48 +0000850 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000851 list, tuple, dict, set, frozenset or str or any type that a subclass
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200852 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Michael Foord02834952010-02-08 23:10:39 +0000853 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000854 error message (see also the :ref:`list of type-specific methods
855 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000856
Raymond Hettinger35a88362009-04-09 00:08:24 +0000857 .. versionchanged:: 3.1
Ezio Melotti9ecb6be2012-01-16 08:28:54 +0200858 Added the automatic calling of type-specific equality function.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000859
Michael Foord28a817e2010-02-09 00:03:57 +0000860 .. versionchanged:: 3.2
861 :meth:`assertMultiLineEqual` added as the default type equality
862 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000863
Benjamin Peterson52baa292009-03-24 00:56:30 +0000864
Michael Foorde180d392011-01-28 19:51:48 +0000865 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000866
Michael Foorde180d392011-01-28 19:51:48 +0000867 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000868 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000869
Ezio Melotti4370b302010-11-03 20:39:14 +0000870 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000871 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000872
Ezio Melotti4841fd62010-11-05 15:43:40 +0000873 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000874
Ezio Melotti4841fd62010-11-05 15:43:40 +0000875 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
876 is True`` (use ``assertIs(expr, True)`` for the latter). This method
877 should also be avoided when more specific methods are available (e.g.
878 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
879 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000880
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000881
Michael Foorde180d392011-01-28 19:51:48 +0000882 .. method:: assertIs(first, second, msg=None)
883 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000884
Michael Foorde180d392011-01-28 19:51:48 +0000885 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000886 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000887
Raymond Hettinger35a88362009-04-09 00:08:24 +0000888 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000889
890
Ezio Melotti4370b302010-11-03 20:39:14 +0000891 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000892 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000893
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300894 Test that *expr* is (or is not) ``None``.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000895
Ezio Melotti4370b302010-11-03 20:39:14 +0000896 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000897
898
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000899 .. method:: assertIn(first, second, msg=None)
900 assertNotIn(first, second, msg=None)
901
Ezio Melotti4841fd62010-11-05 15:43:40 +0000902 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000903
Raymond Hettinger35a88362009-04-09 00:08:24 +0000904 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000905
906
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000907 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000908 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000909
Ezio Melotti9794a262010-11-04 14:52:13 +0000910 Test that *obj* is (or is not) an instance of *cls* (which can be a
911 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti80a61e82011-12-19 07:04:48 +0200912 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000913
Ezio Melotti4370b302010-11-03 20:39:14 +0000914 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000915
916
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000917
Ezio Melottif418db22016-01-12 11:03:31 +0200918 It is also possible to check the production of exceptions, warnings, and
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200919 log messages using the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000920
Ezio Melotti4370b302010-11-03 20:39:14 +0000921 +---------------------------------------------------------+--------------------------------------+------------+
922 | Method | Checks that | New in |
923 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200924 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000925 | <TestCase.assertRaises>` | | |
926 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300927 | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
928 | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000929 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200930 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000931 | <TestCase.assertWarns>` | | |
932 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti560a7782013-09-13 22:17:40 +0300933 | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
934 | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000935 +---------------------------------------------------------+--------------------------------------+------------+
Georg Brandled007d52013-11-24 16:09:26 +0100936 | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 |
937 | <TestCase.assertLogs>` | with minimum *level* | |
Antoine Pitrou7c89ae22013-09-15 02:01:39 +0200938 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000939
Georg Brandl7f01a132009-09-16 15:58:14 +0000940 .. method:: assertRaises(exception, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300941 assertRaises(exception, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000942
943 Test that an exception is raised when *callable* is called with any
944 positional or keyword arguments that are also passed to
945 :meth:`assertRaises`. The test passes if *exception* is raised, is an
946 error if another exception is raised, or fails if no exception is raised.
947 To catch any of a group of exceptions, a tuple containing the exception
948 classes may be passed as *exception*.
949
Ezio Melottib4dc2502011-05-06 15:01:41 +0300950 If only the *exception* and possibly the *msg* arguments are given,
951 return a context manager so that the code under test can be written
952 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000953
Michael Foord41531f22010-02-05 21:13:40 +0000954 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000955 do_something()
956
Ezio Melottib4dc2502011-05-06 15:01:41 +0300957 When used as a context manager, :meth:`assertRaises` accepts the
958 additional keyword argument *msg*.
959
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000960 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000961 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000962 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000963
Georg Brandl8a1caa22010-07-29 16:01:11 +0000964 with self.assertRaises(SomeException) as cm:
965 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000966
Georg Brandl8a1caa22010-07-29 16:01:11 +0000967 the_exception = cm.exception
968 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000969
Ezio Melotti49008232010-02-08 21:57:48 +0000970 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000971 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000972
Ezio Melotti49008232010-02-08 21:57:48 +0000973 .. versionchanged:: 3.2
974 Added the :attr:`exception` attribute.
975
Ezio Melottib4dc2502011-05-06 15:01:41 +0300976 .. versionchanged:: 3.3
977 Added the *msg* keyword argument when used as a context manager.
978
Benjamin Peterson52baa292009-03-24 00:56:30 +0000979
Ezio Melottied3a7d22010-12-01 02:32:32 +0000980 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300981 assertRaisesRegex(exception, regex, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000982
Ezio Melottied3a7d22010-12-01 02:32:32 +0000983 Like :meth:`assertRaises` but also tests that *regex* matches
984 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000985 a regular expression object or a string containing a regular expression
986 suitable for use by :func:`re.search`. Examples::
987
Terry Jan Reedyc4565a92013-06-29 13:15:43 -0400988 self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
Ezio Melottied3a7d22010-12-01 02:32:32 +0000989 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000990
991 or::
992
Ezio Melottied3a7d22010-12-01 02:32:32 +0000993 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000994 int('XYZ')
995
Georg Brandl419e3de2010-12-01 15:44:25 +0000996 .. versionadded:: 3.1
997 under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +0300998
Ezio Melottied3a7d22010-12-01 02:32:32 +0000999 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001000 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001001
Ezio Melottib4dc2502011-05-06 15:01:41 +03001002 .. versionchanged:: 3.3
1003 Added the *msg* keyword argument when used as a context manager.
1004
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001005
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001006 .. method:: assertWarns(warning, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001007 assertWarns(warning, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001008
1009 Test that a warning is triggered when *callable* is called with any
1010 positional or keyword arguments that are also passed to
1011 :meth:`assertWarns`. The test passes if *warning* is triggered and
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001012 fails if it isn't. Any exception is an error.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001013 To catch any of a group of warnings, a tuple containing the warning
1014 classes may be passed as *warnings*.
1015
Ezio Melottib4dc2502011-05-06 15:01:41 +03001016 If only the *warning* and possibly the *msg* arguments are given,
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001017 return a context manager so that the code under test can be written
Ezio Melottib4dc2502011-05-06 15:01:41 +03001018 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001019
1020 with self.assertWarns(SomeWarning):
1021 do_something()
1022
Terry Jan Reedy9eda66d2013-07-27 16:15:29 -04001023 When used as a context manager, :meth:`assertWarns` accepts the
Ezio Melottib4dc2502011-05-06 15:01:41 +03001024 additional keyword argument *msg*.
1025
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001026 The context manager will store the caught warning object in its
1027 :attr:`warning` attribute, and the source line which triggered the
1028 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1029 This can be useful if the intention is to perform additional checks
Terry Jan Reedy778cba72013-07-30 22:31:06 -04001030 on the warning caught::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001031
1032 with self.assertWarns(SomeWarning) as cm:
1033 do_something()
1034
1035 self.assertIn('myfile.py', cm.filename)
1036 self.assertEqual(320, cm.lineno)
1037
1038 This method works regardless of the warning filters in place when it
1039 is called.
1040
1041 .. versionadded:: 3.2
1042
Ezio Melottib4dc2502011-05-06 15:01:41 +03001043 .. versionchanged:: 3.3
1044 Added the *msg* keyword argument when used as a context manager.
1045
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001046
Ezio Melottied3a7d22010-12-01 02:32:32 +00001047 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001048 assertWarnsRegex(warning, regex, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001049
Ezio Melottied3a7d22010-12-01 02:32:32 +00001050 Like :meth:`assertWarns` but also tests that *regex* matches on the
1051 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001052 object or a string containing a regular expression suitable for use
1053 by :func:`re.search`. Example::
1054
Ezio Melottied3a7d22010-12-01 02:32:32 +00001055 self.assertWarnsRegex(DeprecationWarning,
1056 r'legacy_function\(\) is deprecated',
1057 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001058
1059 or::
1060
Ezio Melottied3a7d22010-12-01 02:32:32 +00001061 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001062 frobnicate('/etc/passwd')
1063
1064 .. versionadded:: 3.2
1065
Ezio Melottib4dc2502011-05-06 15:01:41 +03001066 .. versionchanged:: 3.3
1067 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001068
Antoine Pitrou0715b9f2013-09-14 19:45:47 +02001069 .. method:: assertLogs(logger=None, level=None)
1070
1071 A context manager to test that at least one message is logged on
1072 the *logger* or one of its children, with at least the given
1073 *level*.
1074
1075 If given, *logger* should be a :class:`logging.Logger` object or a
1076 :class:`str` giving the name of a logger. The default is the root
1077 logger, which will catch all messages.
1078
1079 If given, *level* should be either a numeric logging level or
1080 its string equivalent (for example either ``"ERROR"`` or
1081 :attr:`logging.ERROR`). The default is :attr:`logging.INFO`.
1082
1083 The test passes if at least one message emitted inside the ``with``
1084 block matches the *logger* and *level* conditions, otherwise it fails.
1085
1086 The object returned by the context manager is a recording helper
1087 which keeps tracks of the matching log messages. It has two
1088 attributes:
1089
1090 .. attribute:: records
1091
1092 A list of :class:`logging.LogRecord` objects of the matching
1093 log messages.
1094
1095 .. attribute:: output
1096
1097 A list of :class:`str` objects with the formatted output of
1098 matching messages.
1099
1100 Example::
1101
1102 with self.assertLogs('foo', level='INFO') as cm:
1103 logging.getLogger('foo').info('first message')
1104 logging.getLogger('foo.bar').error('second message')
1105 self.assertEqual(cm.output, ['INFO:foo:first message',
1106 'ERROR:foo.bar:second message'])
1107
1108 .. versionadded:: 3.4
1109
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001110
Ezio Melotti4370b302010-11-03 20:39:14 +00001111 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001112
Ezio Melotti4370b302010-11-03 20:39:14 +00001113 +---------------------------------------+--------------------------------+--------------+
1114 | Method | Checks that | New in |
1115 +=======================================+================================+==============+
1116 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1117 | <TestCase.assertAlmostEqual>` | | |
1118 +---------------------------------------+--------------------------------+--------------+
1119 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1120 | <TestCase.assertNotAlmostEqual>` | | |
1121 +---------------------------------------+--------------------------------+--------------+
1122 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1123 | <TestCase.assertGreater>` | | |
1124 +---------------------------------------+--------------------------------+--------------+
1125 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1126 | <TestCase.assertGreaterEqual>` | | |
1127 +---------------------------------------+--------------------------------+--------------+
1128 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1129 | <TestCase.assertLess>` | | |
1130 +---------------------------------------+--------------------------------+--------------+
1131 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1132 | <TestCase.assertLessEqual>` | | |
1133 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001134 | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001135 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001136 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti560a7782013-09-13 22:17:40 +03001137 | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 |
Ezio Melottied3a7d22010-12-01 02:32:32 +00001138 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001139 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001140 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001141 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001142 | | regardless of their order | |
1143 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001144
1145
Michael Foorde180d392011-01-28 19:51:48 +00001146 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1147 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001148
Michael Foorde180d392011-01-28 19:51:48 +00001149 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001150 equal by computing the difference, rounding to the given number of
1151 decimal *places* (default 7), and comparing to zero. Note that these
1152 methods round the values to the given number of *decimal places* (i.e.
1153 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001154
Ezio Melotti4370b302010-11-03 20:39:14 +00001155 If *delta* is supplied instead of *places* then the difference
Ezio Melottid51914c2013-08-11 13:04:50 +03001156 between *first* and *second* must be less or equal to (or greater than) *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001157
Ezio Melotti4370b302010-11-03 20:39:14 +00001158 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001159
Ezio Melotti4370b302010-11-03 20:39:14 +00001160 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001161 :meth:`assertAlmostEqual` automatically considers almost equal objects
1162 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1163 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001164
Ezio Melotti4370b302010-11-03 20:39:14 +00001165
Michael Foorde180d392011-01-28 19:51:48 +00001166 .. method:: assertGreater(first, second, msg=None)
1167 assertGreaterEqual(first, second, msg=None)
1168 assertLess(first, second, msg=None)
1169 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001170
Michael Foorde180d392011-01-28 19:51:48 +00001171 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001172 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001173
1174 >>> self.assertGreaterEqual(3, 4)
1175 AssertionError: "3" unexpectedly not greater than or equal to "4"
1176
1177 .. versionadded:: 3.1
1178
1179
Ezio Melottied3a7d22010-12-01 02:32:32 +00001180 .. method:: assertRegex(text, regex, msg=None)
1181 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001182
Ezio Melottied3a7d22010-12-01 02:32:32 +00001183 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001184 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001185 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001186 may be a regular expression object or a string containing a regular
1187 expression suitable for use by :func:`re.search`.
1188
Georg Brandl419e3de2010-12-01 15:44:25 +00001189 .. versionadded:: 3.1
1190 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001191 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001192 The method ``assertRegexpMatches()`` has been renamed to
1193 :meth:`.assertRegex`.
1194 .. versionadded:: 3.2
1195 :meth:`.assertNotRegex`.
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001196 .. versionadded:: 3.5
1197 The name ``assertNotRegexpMatches`` is a deprecated alias
1198 for :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001199
1200
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001201 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001202
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001203 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001204 regardless of their order. When they don't, an error message listing the
1205 differences between the sequences will be generated.
1206
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001207 Duplicate elements are *not* ignored when comparing *first* and
1208 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001209 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001210 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001211 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001212
Ezio Melotti4370b302010-11-03 20:39:14 +00001213 .. versionadded:: 3.2
1214
Ezio Melotti4370b302010-11-03 20:39:14 +00001215
Ezio Melotti22170ed2010-11-20 09:57:27 +00001216 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001217
Ezio Melotti22170ed2010-11-20 09:57:27 +00001218 The :meth:`assertEqual` method dispatches the equality check for objects of
1219 the same type to different type-specific methods. These methods are already
1220 implemented for most of the built-in types, but it's also possible to
1221 register new methods using :meth:`addTypeEqualityFunc`:
1222
1223 .. method:: addTypeEqualityFunc(typeobj, function)
1224
1225 Registers a type-specific method called by :meth:`assertEqual` to check
1226 if two objects of exactly the same *typeobj* (not subclasses) compare
1227 equal. *function* must take two positional arguments and a third msg=None
1228 keyword argument just as :meth:`assertEqual` does. It must raise
1229 :data:`self.failureException(msg) <failureException>` when inequality
1230 between the first two parameters is detected -- possibly providing useful
1231 information and explaining the inequalities in details in the error
1232 message.
1233
1234 .. versionadded:: 3.1
1235
1236 The list of type-specific methods automatically used by
1237 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1238 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001239
1240 +-----------------------------------------+-----------------------------+--------------+
1241 | Method | Used to compare | New in |
1242 +=========================================+=============================+==============+
1243 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1244 | <TestCase.assertMultiLineEqual>` | | |
1245 +-----------------------------------------+-----------------------------+--------------+
1246 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1247 | <TestCase.assertSequenceEqual>` | | |
1248 +-----------------------------------------+-----------------------------+--------------+
1249 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1250 | <TestCase.assertListEqual>` | | |
1251 +-----------------------------------------+-----------------------------+--------------+
1252 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1253 | <TestCase.assertTupleEqual>` | | |
1254 +-----------------------------------------+-----------------------------+--------------+
1255 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1256 | <TestCase.assertSetEqual>` | | |
1257 +-----------------------------------------+-----------------------------+--------------+
1258 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1259 | <TestCase.assertDictEqual>` | | |
1260 +-----------------------------------------+-----------------------------+--------------+
1261
1262
1263
Michael Foorde180d392011-01-28 19:51:48 +00001264 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001265
Michael Foorde180d392011-01-28 19:51:48 +00001266 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001267 When not equal a diff of the two strings highlighting the differences
1268 will be included in the error message. This method is used by default
1269 when comparing strings with :meth:`assertEqual`.
1270
Ezio Melotti4370b302010-11-03 20:39:14 +00001271 .. versionadded:: 3.1
1272
1273
Michael Foorde180d392011-01-28 19:51:48 +00001274 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001275
1276 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001277 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001278 be raised. If the sequences are different an error message is
1279 constructed that shows the difference between the two.
1280
Ezio Melotti22170ed2010-11-20 09:57:27 +00001281 This method is not called directly by :meth:`assertEqual`, but
1282 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001283 :meth:`assertTupleEqual`.
1284
1285 .. versionadded:: 3.1
1286
1287
Michael Foorde180d392011-01-28 19:51:48 +00001288 .. method:: assertListEqual(first, second, msg=None)
1289 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001290
Ezio Melotti49ccd512012-08-29 17:50:42 +03001291 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melotti4370b302010-11-03 20:39:14 +00001292 constructed that shows only the differences between the two. An error
1293 is also raised if either of the parameters are of the wrong type.
1294 These methods are used by default when comparing lists or tuples with
1295 :meth:`assertEqual`.
1296
Ezio Melotti4370b302010-11-03 20:39:14 +00001297 .. versionadded:: 3.1
1298
1299
Michael Foorde180d392011-01-28 19:51:48 +00001300 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001301
1302 Tests that two sets are equal. If not, an error message is constructed
1303 that lists the differences between the sets. This method is used by
1304 default when comparing sets or frozensets with :meth:`assertEqual`.
1305
Michael Foorde180d392011-01-28 19:51:48 +00001306 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001307 method.
1308
Ezio Melotti4370b302010-11-03 20:39:14 +00001309 .. versionadded:: 3.1
1310
1311
Michael Foorde180d392011-01-28 19:51:48 +00001312 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001313
1314 Test that two dictionaries are equal. If not, an error message is
1315 constructed that shows the differences in the dictionaries. This
1316 method will be used by default to compare dictionaries in
1317 calls to :meth:`assertEqual`.
1318
Ezio Melotti4370b302010-11-03 20:39:14 +00001319 .. versionadded:: 3.1
1320
1321
1322
Ezio Melotti22170ed2010-11-20 09:57:27 +00001323 .. _other-methods-and-attrs:
1324
Ezio Melotti4370b302010-11-03 20:39:14 +00001325 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001326
Benjamin Peterson52baa292009-03-24 00:56:30 +00001327
Georg Brandl7f01a132009-09-16 15:58:14 +00001328 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001329
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001330 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001331 the error message.
1332
1333
1334 .. attribute:: failureException
1335
1336 This class attribute gives the exception raised by the test method. If a
1337 test framework needs to use a specialized exception, possibly to carry
1338 additional information, it must subclass this exception in order to "play
1339 fair" with the framework. The initial value of this attribute is
1340 :exc:`AssertionError`.
1341
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001342
1343 .. attribute:: longMessage
1344
Guido van Rossum4a452352016-10-13 14:23:01 -07001345 This class attribute determines what happens when a custom failure message
1346 is passed as the msg argument to an assertXYY call that fails.
1347 ``True`` is the default value. In this case, the custom message is appended
1348 to the end of the standard failure message.
1349 When set to ``False``, the custom message replaces the standard message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001350
Guido van Rossum4a452352016-10-13 14:23:01 -07001351 The class setting can be overridden in individual test methods by assigning
1352 an instance attribute, self.longMessage, to ``True`` or ``False`` before
1353 calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001354
Guido van Rossum4a452352016-10-13 14:23:01 -07001355 The class setting gets reset before each test call.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001356
Raymond Hettinger35a88362009-04-09 00:08:24 +00001357 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001358
1359
Michael Foord98b3e762010-06-05 21:59:55 +00001360 .. attribute:: maxDiff
1361
1362 This attribute controls the maximum length of diffs output by assert
1363 methods that report diffs on failure. It defaults to 80*8 characters.
1364 Assert methods affected by this attribute are
1365 :meth:`assertSequenceEqual` (including all the sequence comparison
1366 methods that delegate to it), :meth:`assertDictEqual` and
1367 :meth:`assertMultiLineEqual`.
1368
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001369 Setting ``maxDiff`` to ``None`` means that there is no maximum length of
Michael Foord98b3e762010-06-05 21:59:55 +00001370 diffs.
1371
1372 .. versionadded:: 3.2
1373
1374
Benjamin Peterson52baa292009-03-24 00:56:30 +00001375 Testing frameworks can use the following methods to collect information on
1376 the test:
1377
1378
1379 .. method:: countTestCases()
1380
1381 Return the number of tests represented by this test object. For
1382 :class:`TestCase` instances, this will always be ``1``.
1383
1384
1385 .. method:: defaultTestResult()
1386
1387 Return an instance of the test result class that should be used for this
1388 test case class (if no other result instance is provided to the
1389 :meth:`run` method).
1390
1391 For :class:`TestCase` instances, this will always be an instance of
1392 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1393 as necessary.
1394
1395
1396 .. method:: id()
1397
1398 Return a string identifying the specific test case. This is usually the
1399 full name of the test method, including the module and class name.
1400
1401
1402 .. method:: shortDescription()
1403
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001404 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001405 has been provided. The default implementation of this method
1406 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001407 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001408
Georg Brandl419e3de2010-12-01 15:44:25 +00001409 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001410 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001411 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001412 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001413 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001414
Georg Brandl116aa622007-08-15 14:28:22 +00001415
Georg Brandl7f01a132009-09-16 15:58:14 +00001416 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001417
1418 Add a function to be called after :meth:`tearDown` to cleanup resources
1419 used during the test. Functions will be called in reverse order to the
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +03001420 order they are added (:abbr:`LIFO (last-in, first-out)`). They
1421 are called with any arguments and keyword arguments passed into
1422 :meth:`addCleanup` when they are added.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001423
1424 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1425 then any cleanup functions added will still be called.
1426
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001427 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001428
1429
1430 .. method:: doCleanups()
1431
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001432 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001433 after :meth:`setUp` if :meth:`setUp` raises an exception.
1434
1435 It is responsible for calling all the cleanup functions added by
1436 :meth:`addCleanup`. If you need cleanup functions to be called
1437 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1438 yourself.
1439
1440 :meth:`doCleanups` pops methods off the stack of cleanup
1441 functions one at a time, so it can be called at any time.
1442
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001443 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001444
1445
Georg Brandl7f01a132009-09-16 15:58:14 +00001446.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001447
1448 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001449 allows the test runner to drive the test, but does not provide the methods
1450 which test code can use to check and report errors. This is used to create
1451 test cases using legacy test code, allowing it to be integrated into a
1452 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001453
1454
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001455.. _deprecated-aliases:
1456
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001457Deprecated aliases
1458##################
1459
1460For historical reasons, some of the :class:`TestCase` methods had one or more
1461aliases that are now deprecated. The following table lists the correct names
1462along with their deprecated aliases:
1463
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001464 ============================== ====================== =======================
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001465 Method Name Deprecated alias Deprecated alias
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001466 ============================== ====================== =======================
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001467 :meth:`.assertEqual` failUnlessEqual assertEquals
1468 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1469 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001470 :meth:`.assertFalse` failIf
1471 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001472 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1473 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001474 :meth:`.assertRegex` assertRegexpMatches
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001475 :meth:`.assertNotRegex` assertNotRegexpMatches
Ezio Melottied3a7d22010-12-01 02:32:32 +00001476 :meth:`.assertRaisesRegex` assertRaisesRegexp
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001477 ============================== ====================== =======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001478
Ezio Melotti361467e2011-04-03 17:37:58 +03001479 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001480 the fail* aliases listed in the second column.
1481 .. deprecated:: 3.2
1482 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001483 .. deprecated:: 3.2
1484 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
Jim Fasarakis-Hilliard74921ed2017-06-09 23:27:20 +03001485 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`.
1486 .. deprecated:: 3.5
1487 the ``assertNotRegexpMatches`` name in favor of :meth:`.assertNotRegex`.
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001488
Benjamin Peterson52baa292009-03-24 00:56:30 +00001489.. _testsuite-objects:
1490
Benjamin Peterson52baa292009-03-24 00:56:30 +00001491Grouping tests
1492~~~~~~~~~~~~~~
1493
Georg Brandl7f01a132009-09-16 15:58:14 +00001494.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001495
Martin Panter37f183d2017-01-18 12:06:38 +00001496 This class represents an aggregation of individual test cases and test suites.
Georg Brandl116aa622007-08-15 14:28:22 +00001497 The class presents the interface needed by the test runner to allow it to be run
1498 as any other test case. Running a :class:`TestSuite` instance is the same as
1499 iterating over the suite, running each test individually.
1500
1501 If *tests* is given, it must be an iterable of individual test cases or other
1502 test suites that will be used to build the suite initially. Additional methods
1503 are provided to add test cases and suites to the collection later on.
1504
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001505 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1506 they do not actually implement a test. Instead, they are used to aggregate
1507 tests into groups of tests that should be run together. Some additional
1508 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001509
1510
1511 .. method:: TestSuite.addTest(test)
1512
1513 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1514
1515
1516 .. method:: TestSuite.addTests(tests)
1517
1518 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1519 instances to this test suite.
1520
Benjamin Petersond2397752009-06-27 23:45:02 +00001521 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1522 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001523
1524 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1525
1526
1527 .. method:: run(result)
1528
1529 Run the tests associated with this suite, collecting the result into the
1530 test result object passed as *result*. Note that unlike
1531 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1532 be passed in.
1533
1534
1535 .. method:: debug()
1536
1537 Run the tests associated with this suite without collecting the
1538 result. This allows exceptions raised by the test to be propagated to the
1539 caller and can be used to support running tests under a debugger.
1540
1541
1542 .. method:: countTestCases()
1543
1544 Return the number of tests represented by this test object, including all
1545 individual tests and sub-suites.
1546
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001547
1548 .. method:: __iter__()
1549
1550 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1551 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
Andrew Svetloveb973682013-08-28 21:28:38 +03001552 that this method may be called several times on a single suite (for
1553 example when counting tests or comparing for equality) so the tests
1554 returned by repeated iterations before :meth:`TestSuite.run` must be the
1555 same for each call iteration. After :meth:`TestSuite.run`, callers should
1556 not rely on the tests returned by this method unless the caller uses a
1557 subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
1558 test references.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001559
Georg Brandl853947a2010-01-31 18:53:23 +00001560 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001561 In earlier versions the :class:`TestSuite` accessed tests directly rather
1562 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1563 for providing tests.
1564
Andrew Svetloveb973682013-08-28 21:28:38 +03001565 .. versionchanged:: 3.4
1566 In earlier versions the :class:`TestSuite` held references to each
1567 :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
1568 that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
1569
Benjamin Peterson52baa292009-03-24 00:56:30 +00001570 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1571 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1572
1573
Benjamin Peterson52baa292009-03-24 00:56:30 +00001574Loading and running tests
1575~~~~~~~~~~~~~~~~~~~~~~~~~
1576
Georg Brandl116aa622007-08-15 14:28:22 +00001577.. class:: TestLoader()
1578
Benjamin Peterson52baa292009-03-24 00:56:30 +00001579 The :class:`TestLoader` class is used to create test suites from classes and
1580 modules. Normally, there is no need to create an instance of this class; the
1581 :mod:`unittest` module provides an instance that can be shared as
Ezio Melottib8e336b2012-04-29 10:52:18 +03001582 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1583 allows customization of some configurable properties.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001584
Robert Collinsf920c212014-10-20 13:24:05 +13001585 :class:`TestLoader` objects have the following attributes:
1586
1587
1588 .. attribute:: errors
1589
1590 A list of the non-fatal errors encountered while loading tests. Not reset
1591 by the loader at any point. Fatal errors are signalled by the relevant
1592 a method raising an exception to the caller. Non-fatal errors are also
1593 indicated by a synthetic test that will raise the original error when
1594 run.
1595
1596 .. versionadded:: 3.5
1597
1598
Benjamin Peterson52baa292009-03-24 00:56:30 +00001599 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001600
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001601
Benjamin Peterson52baa292009-03-24 00:56:30 +00001602 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001603
Martin Panter37f183d2017-01-18 12:06:38 +00001604 Return a suite of all test cases contained in the :class:`TestCase`\ -derived
Benjamin Peterson52baa292009-03-24 00:56:30 +00001605 :class:`testCaseClass`.
1606
Robert Collinse02f6c22015-07-23 06:37:26 +12001607 A test case instance is created for each method named by
1608 :meth:`getTestCaseNames`. By default these are the method names
1609 beginning with ``test``. If :meth:`getTestCaseNames` returns no
1610 methods, but the :meth:`runTest` method is implemented, a single test
1611 case is created for that method instead.
1612
Benjamin Peterson52baa292009-03-24 00:56:30 +00001613
Barry Warsawd78742a2014-09-08 14:21:37 -04001614 .. method:: loadTestsFromModule(module, pattern=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001615
Martin Panter37f183d2017-01-18 12:06:38 +00001616 Return a suite of all test cases contained in the given module. This
Benjamin Peterson52baa292009-03-24 00:56:30 +00001617 method searches *module* for classes derived from :class:`TestCase` and
1618 creates an instance of the class for each test method defined for the
1619 class.
1620
Georg Brandle720c0a2009-04-27 16:20:50 +00001621 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001622
1623 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1624 convenient in sharing fixtures and helper functions, defining test
1625 methods on base classes that are not intended to be instantiated
1626 directly does not play well with this method. Doing so, however, can
1627 be useful when the fixtures are different and defined in subclasses.
1628
Benjamin Petersond2397752009-06-27 23:45:02 +00001629 If a module provides a ``load_tests`` function it will be called to
1630 load the tests. This allows modules to customize test loading.
Barry Warsawd78742a2014-09-08 14:21:37 -04001631 This is the `load_tests protocol`_. The *pattern* argument is passed as
1632 the third argument to ``load_tests``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001633
Georg Brandl853947a2010-01-31 18:53:23 +00001634 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001635 Support for ``load_tests`` added.
1636
Barry Warsawd78742a2014-09-08 14:21:37 -04001637 .. versionchanged:: 3.5
1638 The undocumented and unofficial *use_load_tests* default argument is
1639 deprecated and ignored, although it is still accepted for backward
1640 compatibility. The method also now accepts a keyword-only argument
1641 *pattern* which is passed to ``load_tests`` as the third argument.
1642
Benjamin Peterson52baa292009-03-24 00:56:30 +00001643
Georg Brandl7f01a132009-09-16 15:58:14 +00001644 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001645
Martin Panter37f183d2017-01-18 12:06:38 +00001646 Return a suite of all test cases given a string specifier.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001647
1648 The specifier *name* is a "dotted name" that may resolve either to a
1649 module, a test case class, a test method within a test case class, a
1650 :class:`TestSuite` instance, or a callable object which returns a
1651 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1652 applied in the order listed here; that is, a method on a possible test
1653 case class will be picked up as "a test method within a test case class",
1654 rather than "a callable object".
1655
1656 For example, if you have a module :mod:`SampleTests` containing a
1657 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1658 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001659 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1660 return a suite which will run all three test methods. Using the specifier
1661 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1662 suite which will run only the :meth:`test_two` test method. The specifier
1663 can refer to modules and packages which have not been imported; they will
1664 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001665
1666 The method optionally resolves *name* relative to the given *module*.
1667
Martin Panter536d70e2017-01-14 08:23:08 +00001668 .. versionchanged:: 3.5
1669 If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing
1670 *name* then a synthetic test that raises that error when run will be
1671 returned. These errors are included in the errors accumulated by
1672 self.errors.
Robert Collins659dd622014-10-30 08:27:27 +13001673
Benjamin Peterson52baa292009-03-24 00:56:30 +00001674
Georg Brandl7f01a132009-09-16 15:58:14 +00001675 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001676
1677 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1678 than a single name. The return value is a test suite which supports all
1679 the tests defined for each name.
1680
1681
1682 .. method:: getTestCaseNames(testCaseClass)
1683
1684 Return a sorted sequence of method names found within *testCaseClass*;
1685 this should be a subclass of :class:`TestCase`.
1686
Benjamin Petersond2397752009-06-27 23:45:02 +00001687
1688 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1689
Larry Hastings3732ed22014-03-15 21:13:56 -07001690 Find all the test modules by recursing into subdirectories from the
1691 specified start directory, and return a TestSuite object containing them.
1692 Only test files that match *pattern* will be loaded. (Using shell style
1693 pattern matching.) Only module names that are importable (i.e. are valid
1694 Python identifiers) will be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001695
1696 All test modules must be importable from the top level of the project. If
1697 the start directory is not the top level directory then the top level
1698 directory must be specified separately.
1699
Barry Warsawd78742a2014-09-08 14:21:37 -04001700 If importing a module fails, for example due to a syntax error, then
1701 this will be recorded as a single error and discovery will continue. If
1702 the import failure is due to :exc:`SkipTest` being raised, it will be
1703 recorded as a skip instead of an error.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001704
Barry Warsawd78742a2014-09-08 14:21:37 -04001705 If a package (a directory containing a file named :file:`__init__.py`) is
1706 found, the package will be checked for a ``load_tests`` function. If this
Robert Collinsbf2bda32014-11-05 03:09:01 +13001707 exists then it will be called
1708 ``package.load_tests(loader, tests, pattern)``. Test discovery takes care
1709 to ensure that a package is only checked for tests once during an
1710 invocation, even if the load_tests function itself calls
1711 ``loader.discover``.
Benjamin Petersond2397752009-06-27 23:45:02 +00001712
Barry Warsawd78742a2014-09-08 14:21:37 -04001713 If ``load_tests`` exists then discovery does *not* recurse into the
1714 package, ``load_tests`` is responsible for loading all tests in the
1715 package.
Benjamin Petersond2397752009-06-27 23:45:02 +00001716
1717 The pattern is deliberately not stored as a loader attribute so that
1718 packages can continue discovery themselves. *top_level_dir* is stored so
1719 ``load_tests`` does not need to pass this argument in to
1720 ``loader.discover()``.
1721
Benjamin Petersonb48af542010-04-11 20:43:16 +00001722 *start_dir* can be a dotted module name as well as a directory.
1723
Georg Brandl853947a2010-01-31 18:53:23 +00001724 .. versionadded:: 3.2
1725
Ezio Melottieae2b382013-03-01 14:47:50 +02001726 .. versionchanged:: 3.4
Ezio Melotti67ddcca2013-03-27 20:13:59 +02001727 Modules that raise :exc:`SkipTest` on import are recorded as skips,
Larry Hastings3732ed22014-03-15 21:13:56 -07001728 not errors.
1729 Discovery works for :term:`namespace packages <namespace package>`.
1730 Paths are sorted before being imported so that execution order is
1731 the same even if the underlying file system's ordering is not
1732 dependent on file name.
Michael Foord80cbc9e2013-03-18 17:50:12 -07001733
Barry Warsawd78742a2014-09-08 14:21:37 -04001734 .. versionchanged:: 3.5
1735 Found packages are now checked for ``load_tests`` regardless of
1736 whether their path matches *pattern*, because it is impossible for
1737 a package name to match the default pattern.
1738
Benjamin Petersond2397752009-06-27 23:45:02 +00001739
Benjamin Peterson52baa292009-03-24 00:56:30 +00001740 The following attributes of a :class:`TestLoader` can be configured either by
1741 subclassing or assignment on an instance:
1742
1743
1744 .. attribute:: testMethodPrefix
1745
1746 String giving the prefix of method names which will be interpreted as test
1747 methods. The default value is ``'test'``.
1748
1749 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1750 methods.
1751
1752
1753 .. attribute:: sortTestMethodsUsing
1754
1755 Function to be used to compare method names when sorting them in
1756 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1757
1758
1759 .. attribute:: suiteClass
1760
1761 Callable object that constructs a test suite from a list of tests. No
1762 methods on the resulting object are needed. The default value is the
1763 :class:`TestSuite` class.
1764
1765 This affects all the :meth:`loadTestsFrom\*` methods.
1766
Jonas Haag5b48dc62017-11-25 16:23:52 +01001767 .. attribute:: testNamePatterns
1768
1769 List of Unix shell-style wildcard test name patterns that test methods
1770 have to match to be included in test suites (see ``-v`` option).
1771
1772 If this attribute is not ``None`` (the default), all test methods to be
1773 included in test suites must match one of the patterns in this list.
1774 Note that matches are always performed using :meth:`fnmatch.fnmatchcase`,
1775 so unlike patterns passed to the ``-v`` option, simple substring patterns
1776 will have to be converted using ``*`` wildcards.
1777
1778 This affects all the :meth:`loadTestsFrom\*` methods.
1779
1780 .. versionadded:: 3.7
1781
Benjamin Peterson52baa292009-03-24 00:56:30 +00001782
Benjamin Peterson52baa292009-03-24 00:56:30 +00001783.. class:: TestResult
1784
1785 This class is used to compile information about which tests have succeeded
1786 and which have failed.
1787
1788 A :class:`TestResult` object stores the results of a set of tests. The
1789 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1790 properly recorded; test authors do not need to worry about recording the
1791 outcome of tests.
1792
1793 Testing frameworks built on top of :mod:`unittest` may want access to the
1794 :class:`TestResult` object generated by running a set of tests for reporting
1795 purposes; a :class:`TestResult` instance is returned by the
1796 :meth:`TestRunner.run` method for this purpose.
1797
1798 :class:`TestResult` instances have the following attributes that will be of
1799 interest when inspecting the results of running a set of tests:
1800
1801
1802 .. attribute:: errors
1803
1804 A list containing 2-tuples of :class:`TestCase` instances and strings
1805 holding formatted tracebacks. Each tuple represents a test which raised an
1806 unexpected exception.
1807
Benjamin Peterson52baa292009-03-24 00:56:30 +00001808 .. attribute:: failures
1809
1810 A list containing 2-tuples of :class:`TestCase` instances and strings
1811 holding formatted tracebacks. Each tuple represents a test where a failure
Ezio Melottie2202362013-09-07 15:19:30 +03001812 was explicitly signalled using the :meth:`TestCase.assert\*` methods.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001813
Benjamin Peterson52baa292009-03-24 00:56:30 +00001814 .. attribute:: skipped
1815
1816 A list containing 2-tuples of :class:`TestCase` instances and strings
1817 holding the reason for skipping the test.
1818
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001819 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001820
1821 .. attribute:: expectedFailures
1822
Georg Brandl6faee4e2010-09-21 14:48:28 +00001823 A list containing 2-tuples of :class:`TestCase` instances and strings
1824 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001825 of the test case.
1826
1827 .. attribute:: unexpectedSuccesses
1828
1829 A list containing :class:`TestCase` instances that were marked as expected
1830 failures, but succeeded.
1831
1832 .. attribute:: shouldStop
1833
1834 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1835
Benjamin Peterson52baa292009-03-24 00:56:30 +00001836 .. attribute:: testsRun
1837
1838 The total number of tests run so far.
1839
Georg Brandl12037202010-12-02 22:35:25 +00001840 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001841
1842 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1843 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1844 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1845 fails or errors. Any output is also attached to the failure / error message.
1846
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001847 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001848
Benjamin Petersonb48af542010-04-11 20:43:16 +00001849 .. attribute:: failfast
1850
1851 If set to true :meth:`stop` will be called on the first failure or error,
1852 halting the test run.
1853
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001854 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001855
Robert Collinsf0c819a2015-03-06 13:46:35 +13001856 .. attribute:: tb_locals
1857
1858 If set to true then local variables will be shown in tracebacks.
1859
1860 .. versionadded:: 3.5
Benjamin Petersonb48af542010-04-11 20:43:16 +00001861
Benjamin Peterson52baa292009-03-24 00:56:30 +00001862 .. method:: wasSuccessful()
1863
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001864 Return ``True`` if all tests run so far have passed, otherwise returns
1865 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001866
Gregory P. Smith5a6d4bf2014-01-20 01:11:18 -08001867 .. versionchanged:: 3.4
1868 Returns ``False`` if there were any :attr:`unexpectedSuccesses`
1869 from tests marked with the :func:`expectedFailure` decorator.
1870
Benjamin Peterson52baa292009-03-24 00:56:30 +00001871 .. method:: stop()
1872
1873 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001874 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001875 :class:`TestRunner` objects should respect this flag and return without
1876 running any additional tests.
1877
1878 For example, this feature is used by the :class:`TextTestRunner` class to
1879 stop the test framework when the user signals an interrupt from the
1880 keyboard. Interactive tools which provide :class:`TestRunner`
1881 implementations can use this in a similar manner.
1882
1883 The following methods of the :class:`TestResult` class are used to maintain
1884 the internal data structures, and may be extended in subclasses to support
1885 additional reporting requirements. This is particularly useful in building
1886 tools which support interactive reporting while tests are being run.
1887
1888
1889 .. method:: startTest(test)
1890
1891 Called when the test case *test* is about to be run.
1892
Benjamin Peterson52baa292009-03-24 00:56:30 +00001893 .. method:: stopTest(test)
1894
1895 Called after the test case *test* has been executed, regardless of the
1896 outcome.
1897
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001898 .. method:: startTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001899
1900 Called once before any tests are executed.
1901
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001902 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001903
1904
Terry Jan Reedyf98021c2014-04-11 14:11:11 -04001905 .. method:: stopTestRun()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001906
Ezio Melotti176d6c42010-01-27 20:58:07 +00001907 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001908
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001909 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001910
1911
Benjamin Peterson52baa292009-03-24 00:56:30 +00001912 .. method:: addError(test, err)
1913
Ezio Melottie64a91a2013-09-07 15:23:36 +03001914 Called when the test case *test* raises an unexpected exception. *err* is a
Benjamin Peterson52baa292009-03-24 00:56:30 +00001915 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1916 traceback)``.
1917
1918 The default implementation appends a tuple ``(test, formatted_err)`` to
1919 the instance's :attr:`errors` attribute, where *formatted_err* is a
1920 formatted traceback derived from *err*.
1921
1922
1923 .. method:: addFailure(test, err)
1924
Benjamin Petersond2397752009-06-27 23:45:02 +00001925 Called when the test case *test* signals a failure. *err* is a tuple of
1926 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001927
1928 The default implementation appends a tuple ``(test, formatted_err)`` to
1929 the instance's :attr:`failures` attribute, where *formatted_err* is a
1930 formatted traceback derived from *err*.
1931
1932
1933 .. method:: addSuccess(test)
1934
1935 Called when the test case *test* succeeds.
1936
1937 The default implementation does nothing.
1938
1939
1940 .. method:: addSkip(test, reason)
1941
1942 Called when the test case *test* is skipped. *reason* is the reason the
1943 test gave for skipping.
1944
1945 The default implementation appends a tuple ``(test, reason)`` to the
1946 instance's :attr:`skipped` attribute.
1947
1948
1949 .. method:: addExpectedFailure(test, err)
1950
1951 Called when the test case *test* fails, but was marked with the
1952 :func:`expectedFailure` decorator.
1953
1954 The default implementation appends a tuple ``(test, formatted_err)`` to
1955 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1956 is a formatted traceback derived from *err*.
1957
1958
1959 .. method:: addUnexpectedSuccess(test)
1960
1961 Called when the test case *test* was marked with the
1962 :func:`expectedFailure` decorator, but succeeded.
1963
1964 The default implementation appends the test to the instance's
1965 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001966
Georg Brandl67b21b72010-08-17 15:07:14 +00001967
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001968 .. method:: addSubTest(test, subtest, outcome)
1969
1970 Called when a subtest finishes. *test* is the test case
1971 corresponding to the test method. *subtest* is a custom
1972 :class:`TestCase` instance describing the subtest.
1973
1974 If *outcome* is :const:`None`, the subtest succeeded. Otherwise,
1975 it failed with an exception where *outcome* is a tuple of the form
1976 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1977
1978 The default implementation does nothing when the outcome is a
1979 success, and records subtest failures as normal failures.
1980
1981 .. versionadded:: 3.4
1982
1983
Michael Foord34c94622010-02-10 15:51:42 +00001984.. class:: TextTestResult(stream, descriptions, verbosity)
1985
Georg Brandl67b21b72010-08-17 15:07:14 +00001986 A concrete implementation of :class:`TestResult` used by the
1987 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001988
Georg Brandl67b21b72010-08-17 15:07:14 +00001989 .. versionadded:: 3.2
1990 This class was previously named ``_TextTestResult``. The old name still
1991 exists as an alias but is deprecated.
1992
Georg Brandl116aa622007-08-15 14:28:22 +00001993
1994.. data:: defaultTestLoader
1995
1996 Instance of the :class:`TestLoader` class intended to be shared. If no
1997 customization of the :class:`TestLoader` is needed, this instance can be used
1998 instead of repeatedly creating new instances.
1999
2000
Ezio Melotti9c939bc2013-05-07 09:46:30 +03002001.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \
Robert Collinsf0c819a2015-03-06 13:46:35 +13002002 buffer=False, resultclass=None, warnings=None, *, tb_locals=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002003
Michael Foordd218e952011-01-03 12:55:11 +00002004 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02002005 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00002006 has a few configurable parameters, but is essentially very simple. Graphical
Robert Collinsf0c819a2015-03-06 13:46:35 +13002007 applications which run test suites should provide alternate implementations. Such
2008 implementations should accept ``**kwargs`` as the interface to construct runners
2009 changes when features are added to unittest.
Georg Brandl116aa622007-08-15 14:28:22 +00002010
Ezio Melotti60901872010-12-01 00:56:10 +00002011 By default this runner shows :exc:`DeprecationWarning`,
Senthil Kumaran409ea5d2014-02-08 14:28:03 -08002012 :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and
Larry Hastingsad88d7a2014-02-10 04:26:10 -08002013 :exc:`ImportWarning` even if they are :ref:`ignored by default
2014 <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest
2015 methods <deprecated-aliases>` are also special-cased and, when the warning
2016 filters are ``'default'`` or ``'always'``, they will appear only once
2017 per-module, in order to avoid too many warning messages. This behavior can
Martin Panterb8c5f542016-10-30 04:20:23 +00002018 be overridden using Python's :option:`!-Wd` or :option:`!-Wa` options
2019 (see :ref:`Warning control <using-on-warnings>`) and leaving
Larry Hastingsad88d7a2014-02-10 04:26:10 -08002020 *warnings* to ``None``.
Ezio Melotti60901872010-12-01 00:56:10 +00002021
Michael Foordd218e952011-01-03 12:55:11 +00002022 .. versionchanged:: 3.2
2023 Added the ``warnings`` argument.
2024
2025 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02002026 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00002027 than import time.
2028
Robert Collinsf0c819a2015-03-06 13:46:35 +13002029 .. versionchanged:: 3.5
2030 Added the tb_locals parameter.
2031
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002032 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00002033
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002034 This method returns the instance of ``TestResult`` used by :meth:`run`.
2035 It is not intended to be called directly, but can be overridden in
2036 subclasses to provide a custom ``TestResult``.
2037
Michael Foord34c94622010-02-10 15:51:42 +00002038 ``_makeResult()`` instantiates the class or callable passed in the
2039 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00002040 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00002041 The result class is instantiated with the following arguments::
2042
2043 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002044
Michael Foord4d1639f2013-12-29 23:38:55 +00002045 .. method:: run(test)
2046
2047 This method is the main public interface to the `TextTestRunner`. This
2048 method takes a :class:`TestSuite` or :class:`TestCase` instance. A
2049 :class:`TestResult` is created by calling
2050 :func:`_makeResult` and the test(s) are run and the
2051 results printed to stdout.
2052
Ezio Melotti60901872010-12-01 00:56:10 +00002053
Georg Brandl419e3de2010-12-01 15:44:25 +00002054.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02002055 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00002056 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002057
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002058 A command-line program that loads a set of tests from *module* and runs them;
2059 this is primarily for making test modules conveniently executable.
2060 The simplest use for this function is to include the following line at the
2061 end of a test script::
Georg Brandl116aa622007-08-15 14:28:22 +00002062
2063 if __name__ == '__main__':
2064 unittest.main()
2065
Benjamin Petersond2397752009-06-27 23:45:02 +00002066 You can run tests with more detailed information by passing in the verbosity
2067 argument::
2068
2069 if __name__ == '__main__':
2070 unittest.main(verbosity=2)
2071
R David Murray6e731b02014-01-02 13:43:02 -05002072 The *defaultTest* argument is either the name of a single test or an
2073 iterable of test names to run if no test names are specified via *argv*. If
2074 not specified or ``None`` and no test names are provided via *argv*, all
2075 tests found in *module* are run.
R David Murray12e930f2014-01-02 13:37:26 -05002076
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002077 The *argv* argument can be a list of options passed to the program, with the
2078 first element being the program name. If not specified or ``None``,
2079 the values of :data:`sys.argv` are used.
2080
Georg Brandl116aa622007-08-15 14:28:22 +00002081 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002082 created instance of it. By default ``main`` calls :func:`sys.exit` with
2083 an exit code indicating success or failure of the tests run.
2084
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002085 The *testLoader* argument has to be a :class:`TestLoader` instance,
2086 and defaults to :data:`defaultTestLoader`.
2087
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002088 ``main`` supports being used from the interactive interpreter by passing in the
2089 argument ``exit=False``. This displays the result on standard output without
2090 calling :func:`sys.exit`::
2091
2092 >>> from unittest import main
2093 >>> main(module='test_module', exit=False)
2094
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002095 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00002096 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002097
Zachary Waref0a71cf2016-08-30 00:16:13 -05002098 The *warnings* argument specifies the :ref:`warning filter <warning-filter>`
Ezio Melotti60901872010-12-01 00:56:10 +00002099 that should be used while running the tests. If it's not specified, it will
Martin Panterb8c5f542016-10-30 04:20:23 +00002100 remain ``None`` if a :option:`!-W` option is passed to :program:`python`
2101 (see :ref:`Warning control <using-on-warnings>`),
Ezio Melotti60901872010-12-01 00:56:10 +00002102 otherwise it will be set to ``'default'``.
2103
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002104 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
2105 This stores the result of the tests run as the ``result`` attribute.
2106
Éric Araujo971dc012010-12-16 03:13:05 +00002107 .. versionchanged:: 3.1
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002108 The *exit* parameter was added.
Éric Araujo971dc012010-12-16 03:13:05 +00002109
Georg Brandl853947a2010-01-31 18:53:23 +00002110 .. versionchanged:: 3.2
Ezio Melotti3d6d7a52012-04-30 19:10:28 +03002111 The *verbosity*, *failfast*, *catchbreak*, *buffer*
2112 and *warnings* parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00002113
Chris Jerdonekccbc26a2013-02-23 15:44:46 -08002114 .. versionchanged:: 3.4
2115 The *defaultTest* parameter was changed to also accept an iterable of
2116 test names.
2117
Benjamin Petersond2397752009-06-27 23:45:02 +00002118
2119load_tests Protocol
2120###################
2121
Georg Brandl853947a2010-01-31 18:53:23 +00002122.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002123
Benjamin Petersond2397752009-06-27 23:45:02 +00002124Modules or packages can customize how tests are loaded from them during normal
2125test runs or test discovery by implementing a function called ``load_tests``.
2126
2127If a test module defines ``load_tests`` it will be called by
2128:meth:`TestLoader.loadTestsFromModule` with the following arguments::
2129
Barry Warsawd78742a2014-09-08 14:21:37 -04002130 load_tests(loader, standard_tests, pattern)
2131
2132where *pattern* is passed straight through from ``loadTestsFromModule``. It
2133defaults to ``None``.
Benjamin Petersond2397752009-06-27 23:45:02 +00002134
2135It should return a :class:`TestSuite`.
2136
2137*loader* is the instance of :class:`TestLoader` doing the loading.
2138*standard_tests* are the tests that would be loaded by default from the
2139module. It is common for test modules to only want to add or remove tests
2140from the standard set of tests.
2141The third argument is used when loading packages as part of test discovery.
2142
2143A typical ``load_tests`` function that loads tests from a specific set of
2144:class:`TestCase` classes may look like::
2145
2146 test_cases = (TestCase1, TestCase2, TestCase3)
2147
2148 def load_tests(loader, tests, pattern):
2149 suite = TestSuite()
2150 for test_class in test_cases:
2151 tests = loader.loadTestsFromTestCase(test_class)
2152 suite.addTests(tests)
2153 return suite
2154
Barry Warsawd78742a2014-09-08 14:21:37 -04002155If discovery is started in a directory containing a package, either from the
2156command line or by calling :meth:`TestLoader.discover`, then the package
2157:file:`__init__.py` will be checked for ``load_tests``. If that function does
2158not exist, discovery will recurse into the package as though it were just
2159another directory. Otherwise, discovery of the package's tests will be left up
2160to ``load_tests`` which is called with the following arguments::
Benjamin Petersond2397752009-06-27 23:45:02 +00002161
2162 load_tests(loader, standard_tests, pattern)
2163
2164This should return a :class:`TestSuite` representing all the tests
2165from the package. (``standard_tests`` will only contain tests
2166collected from :file:`__init__.py`.)
2167
2168Because the pattern is passed into ``load_tests`` the package is free to
2169continue (and potentially modify) test discovery. A 'do nothing'
2170``load_tests`` function for a test package would look like::
2171
2172 def load_tests(loader, standard_tests, pattern):
2173 # top level directory cached on loader instance
2174 this_dir = os.path.dirname(__file__)
2175 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2176 standard_tests.addTests(package_tests)
2177 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002178
Barry Warsawd78742a2014-09-08 14:21:37 -04002179.. versionchanged:: 3.5
2180 Discovery no longer checks package names for matching *pattern* due to the
2181 impossibility of package names matching the default pattern.
2182
2183
Benjamin Petersonb48af542010-04-11 20:43:16 +00002184
2185Class and Module Fixtures
2186-------------------------
2187
2188Class and module level fixtures are implemented in :class:`TestSuite`. When
2189the test suite encounters a test from a new class then :meth:`tearDownClass`
2190from the previous class (if there is one) is called, followed by
2191:meth:`setUpClass` from the new class.
2192
2193Similarly if a test is from a different module from the previous test then
2194``tearDownModule`` from the previous module is run, followed by
2195``setUpModule`` from the new module.
2196
2197After all the tests have run the final ``tearDownClass`` and
2198``tearDownModule`` are run.
2199
2200Note that shared fixtures do not play well with [potential] features like test
2201parallelization and they break test isolation. They should be used with care.
2202
2203The default ordering of tests created by the unittest test loaders is to group
2204all tests from the same modules and classes together. This will lead to
2205``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2206module. If you randomize the order, so that tests from different modules and
2207classes are adjacent to each other, then these shared fixture functions may be
2208called multiple times in a single test run.
2209
2210Shared fixtures are not intended to work with suites with non-standard
2211ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2212support shared fixtures.
2213
2214If there are any exceptions raised during one of the shared fixture functions
2215the test is reported as an error. Because there is no corresponding test
2216instance an ``_ErrorHolder`` object (that has the same interface as a
2217:class:`TestCase`) is created to represent the error. If you are just using
2218the standard unittest test runner then this detail doesn't matter, but if you
2219are a framework author it may be relevant.
2220
2221
2222setUpClass and tearDownClass
2223~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2224
2225These must be implemented as class methods::
2226
2227 import unittest
2228
2229 class Test(unittest.TestCase):
2230 @classmethod
2231 def setUpClass(cls):
2232 cls._connection = createExpensiveConnectionObject()
2233
2234 @classmethod
2235 def tearDownClass(cls):
2236 cls._connection.destroy()
2237
2238If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2239then you must call up to them yourself. The implementations in
2240:class:`TestCase` are empty.
2241
2242If an exception is raised during a ``setUpClass`` then the tests in the class
2243are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002244have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002245:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002246instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002247
2248
2249setUpModule and tearDownModule
2250~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2251
2252These should be implemented as functions::
2253
2254 def setUpModule():
2255 createConnection()
2256
2257 def tearDownModule():
2258 closeConnection()
2259
2260If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002261module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti265281a2013-03-27 20:11:55 +02002262:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord98b3e762010-06-05 21:59:55 +00002263instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002264
2265
2266Signal Handling
2267---------------
2268
Georg Brandl419e3de2010-12-01 15:44:25 +00002269.. versionadded:: 3.2
2270
Éric Araujo8acb67c2010-11-26 23:31:07 +00002271The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002272along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2273more friendly handling of control-C during a test run. With catch break
2274behavior enabled control-C will allow the currently running test to complete,
2275and the test run will then end and report all the results so far. A second
2276control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002277
Michael Foordde4ceab2010-04-25 19:53:49 +00002278The control-c handling signal handler attempts to remain compatible with code or
2279tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2280handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2281i.e. it has been replaced by the system under test and delegated to, then it
2282calls the default handler. This will normally be the expected behavior by code
2283that replaces an installed handler and delegates to it. For individual tests
2284that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2285decorator can be used.
2286
2287There are a few utility functions for framework authors to enable control-c
2288handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002289
2290.. function:: installHandler()
2291
2292 Install the control-c handler. When a :const:`signal.SIGINT` is received
2293 (usually in response to the user pressing control-c) all registered results
2294 have :meth:`~TestResult.stop` called.
2295
Michael Foord469b1f02010-04-26 23:41:26 +00002296
Benjamin Petersonb48af542010-04-11 20:43:16 +00002297.. function:: registerResult(result)
2298
2299 Register a :class:`TestResult` object for control-c handling. Registering a
2300 result stores a weak reference to it, so it doesn't prevent the result from
2301 being garbage collected.
2302
Michael Foordde4ceab2010-04-25 19:53:49 +00002303 Registering a :class:`TestResult` object has no side-effects if control-c
2304 handling is not enabled, so test frameworks can unconditionally register
2305 all results they create independently of whether or not handling is enabled.
2306
Michael Foord469b1f02010-04-26 23:41:26 +00002307
Benjamin Petersonb48af542010-04-11 20:43:16 +00002308.. function:: removeResult(result)
2309
2310 Remove a registered result. Once a result has been removed then
2311 :meth:`~TestResult.stop` will no longer be called on that result object in
2312 response to a control-c.
2313
Michael Foord469b1f02010-04-26 23:41:26 +00002314
Michael Foordde4ceab2010-04-25 19:53:49 +00002315.. function:: removeHandler(function=None)
2316
2317 When called without arguments this function removes the control-c handler
2318 if it has been installed. This function can also be used as a test decorator
2319 to temporarily remove the handler whilst the test is being executed::
2320
2321 @unittest.removeHandler
2322 def test_signal_handling(self):
2323 ...