Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`unittest` --- Unit testing framework |
| 2 | ========================================== |
| 3 | |
| 4 | .. module:: unittest |
| 5 | :synopsis: Unit testing framework for Python. |
| 6 | .. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com> |
| 7 | .. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com> |
| 8 | .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> |
| 9 | .. sectionauthor:: Raymond Hettinger <python@rcn.com> |
| 10 | |
Ezio Melotti | 22170ed | 2010-11-20 09:57:27 +0000 | [diff] [blame] | 11 | (If you are already familiar with the basic concepts of testing, you might want |
| 12 | to skip to :ref:`the list of assert methods <assert-methods>`.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 13 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 14 | The :mod:`unittest` unit testing framework was originally inspired by JUnit |
| 15 | and has a similar flavor as major unit testing frameworks in other |
| 16 | languages. It supports test automation, sharing of setup and shutdown code |
| 17 | for tests, aggregation of tests into collections, and independence of the |
| 18 | tests from the reporting framework. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 19 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 20 | To achieve this, :mod:`unittest` supports some important concepts in an |
| 21 | object-oriented way: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 22 | |
| 23 | test fixture |
| 24 | A :dfn:`test fixture` represents the preparation needed to perform one or more |
| 25 | tests, and any associate cleanup actions. This may involve, for example, |
| 26 | creating temporary or proxy databases, directories, or starting a server |
| 27 | process. |
| 28 | |
| 29 | test case |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 30 | A :dfn:`test case` is the individual unit of testing. It checks for a specific |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 31 | response to a particular set of inputs. :mod:`unittest` provides a base class, |
| 32 | :class:`TestCase`, which may be used to create new test cases. |
| 33 | |
| 34 | test suite |
| 35 | A :dfn:`test suite` is a collection of test cases, test suites, or both. It is |
| 36 | used to aggregate tests that should be executed together. |
| 37 | |
| 38 | test runner |
| 39 | A :dfn:`test runner` is a component which orchestrates the execution of tests |
| 40 | and provides the outcome to the user. The runner may use a graphical interface, |
| 41 | a textual interface, or return a special value to indicate the results of |
| 42 | executing the tests. |
| 43 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 44 | |
| 45 | .. seealso:: |
| 46 | |
| 47 | Module :mod:`doctest` |
| 48 | Another test-support module with a very different flavor. |
| 49 | |
R David Murray | a1005ed | 2015-07-04 15:44:14 -0400 | [diff] [blame] | 50 | `Simple Smalltalk Testing: With Patterns <https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm>`_ |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 51 | Kent Beck's original paper on testing frameworks using the pattern shared |
| 52 | by :mod:`unittest`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 53 | |
Berker Peksag | a1a1409 | 2014-12-28 18:48:33 +0200 | [diff] [blame] | 54 | `Nose <https://nose.readthedocs.org/en/latest/>`_ and `py.test <http://pytest.org>`_ |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 55 | Third-party unittest frameworks with a lighter-weight syntax for writing |
| 56 | tests. For example, ``assert func(10) == 42``. |
Raymond Hettinger | 6b232cd | 2009-03-24 00:22:53 +0000 | [diff] [blame] | 57 | |
Georg Brandl | e73778c | 2014-10-29 08:36:35 +0100 | [diff] [blame] | 58 | `The Python Testing Tools Taxonomy <https://wiki.python.org/moin/PythonTestingToolsTaxonomy>`_ |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 59 | An extensive list of Python testing tools including functional testing |
| 60 | frameworks and mock object libraries. |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 61 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 62 | `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_ |
| 63 | A special-interest-group for discussion of testing, and testing tools, |
| 64 | in Python. |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 65 | |
Michael Foord | 90efac7 | 2011-01-03 15:39:49 +0000 | [diff] [blame] | 66 | The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is |
| 67 | a GUI tool for test discovery and execution. This is intended largely for ease of use |
Senthil Kumaran | 847c33c | 2012-10-27 11:04:55 -0700 | [diff] [blame] | 68 | for those new to unit testing. For production environments it is |
| 69 | recommended that tests be driven by a continuous integration system such as |
Georg Brandl | 525d355 | 2014-10-29 10:26:56 +0100 | [diff] [blame] | 70 | `Buildbot <http://buildbot.net/>`_, `Jenkins <http://jenkins-ci.org/>`_ |
Senthil Kumaran | 847c33c | 2012-10-27 11:04:55 -0700 | [diff] [blame] | 71 | or `Hudson <http://hudson-ci.org/>`_. |
Michael Foord | 90efac7 | 2011-01-03 15:39:49 +0000 | [diff] [blame] | 72 | |
| 73 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 74 | .. _unittest-minimal-example: |
| 75 | |
| 76 | Basic example |
| 77 | ------------- |
| 78 | |
| 79 | The :mod:`unittest` module provides a rich set of tools for constructing and |
| 80 | running tests. This section demonstrates that a small subset of the tools |
| 81 | suffice to meet the needs of most users. |
| 82 | |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 83 | Here is a short script to test three string methods:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 84 | |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 85 | import unittest |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 86 | |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 87 | class TestStringMethods(unittest.TestCase): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 88 | |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 89 | def test_upper(self): |
| 90 | self.assertEqual('foo'.upper(), 'FOO') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 91 | |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 92 | def test_isupper(self): |
| 93 | self.assertTrue('FOO'.isupper()) |
| 94 | self.assertFalse('Foo'.isupper()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 95 | |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 96 | def test_split(self): |
| 97 | s = 'hello world' |
| 98 | self.assertEqual(s.split(), ['hello', 'world']) |
| 99 | # check that s.split fails when the separator is not a string |
| 100 | with self.assertRaises(TypeError): |
| 101 | s.split(2) |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 102 | |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 103 | if __name__ == '__main__': |
| 104 | unittest.main() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 105 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 106 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 107 | A testcase is created by subclassing :class:`unittest.TestCase`. The three |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 108 | individual tests are defined with methods whose names start with the letters |
| 109 | ``test``. This naming convention informs the test runner about which methods |
| 110 | represent tests. |
| 111 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 112 | The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 113 | expected result; :meth:`~TestCase.assertTrue` or :meth:`~TestCase.assertFalse` |
| 114 | to verify a condition; or :meth:`~TestCase.assertRaises` to verify that a |
| 115 | specific exception gets raised. These methods are used instead of the |
| 116 | :keyword:`assert` statement so the test runner can accumulate all test results |
| 117 | and produce a report. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 118 | |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 119 | The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you |
| 120 | to define instructions that will be executed before and after each test method. |
| 121 | They are covered in more details in the section :ref:`organizing-tests`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 122 | |
| 123 | The final block shows a simple way to run the tests. :func:`unittest.main` |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 124 | provides a command-line interface to the test script. When run from the command |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 125 | line, the above script produces an output that looks like this:: |
| 126 | |
| 127 | ... |
| 128 | ---------------------------------------------------------------------- |
| 129 | Ran 3 tests in 0.000s |
| 130 | |
| 131 | OK |
| 132 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 133 | Passing the ``-v`` option to your test script will instruct :func:`unittest.main` |
| 134 | to enable a higher level of verbosity, and produce the following output:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 135 | |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 136 | test_isupper (__main__.TestStringMethods) ... ok |
| 137 | test_split (__main__.TestStringMethods) ... ok |
| 138 | test_upper (__main__.TestStringMethods) ... ok |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 139 | |
| 140 | ---------------------------------------------------------------------- |
Ezio Melotti | 2e3998f | 2015-03-24 12:42:41 +0200 | [diff] [blame] | 141 | Ran 3 tests in 0.001s |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 142 | |
| 143 | OK |
| 144 | |
| 145 | The above examples show the most commonly used :mod:`unittest` features which |
| 146 | are sufficient to meet many everyday testing needs. The remainder of the |
| 147 | documentation explores the full feature set from first principles. |
| 148 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 149 | |
| 150 | .. _unittest-command-line-interface: |
| 151 | |
Éric Araujo | 76338ec | 2010-11-26 23:46:18 +0000 | [diff] [blame] | 152 | Command-Line Interface |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 153 | ---------------------- |
| 154 | |
| 155 | The unittest module can be used from the command line to run tests from |
| 156 | modules, classes or even individual test methods:: |
| 157 | |
| 158 | python -m unittest test_module1 test_module2 |
| 159 | python -m unittest test_module.TestClass |
| 160 | python -m unittest test_module.TestClass.test_method |
| 161 | |
| 162 | You can pass in a list with any combination of module names, and fully |
| 163 | qualified class or method names. |
| 164 | |
Michael Foord | 37d120a | 2010-12-04 01:11:21 +0000 | [diff] [blame] | 165 | Test modules can be specified by file path as well:: |
| 166 | |
| 167 | python -m unittest tests/test_something.py |
| 168 | |
| 169 | This allows you to use the shell filename completion to specify the test module. |
| 170 | The file specified must still be importable as a module. The path is converted |
| 171 | to a module name by removing the '.py' and converting path separators into '.'. |
| 172 | If you want to execute a test file that isn't importable as a module you should |
| 173 | execute the file directly instead. |
| 174 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 175 | You can run tests with more detail (higher verbosity) by passing in the -v flag:: |
| 176 | |
| 177 | python -m unittest -v test_module |
| 178 | |
Michael Foord | 086f308 | 2010-11-21 21:28:01 +0000 | [diff] [blame] | 179 | When executed without arguments :ref:`unittest-test-discovery` is started:: |
| 180 | |
| 181 | python -m unittest |
| 182 | |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 183 | For a list of all the command-line options:: |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 184 | |
| 185 | python -m unittest -h |
| 186 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 187 | .. versionchanged:: 3.2 |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 188 | In earlier versions it was only possible to run individual test methods and |
| 189 | not modules or classes. |
| 190 | |
| 191 | |
Éric Araujo | 76338ec | 2010-11-26 23:46:18 +0000 | [diff] [blame] | 192 | Command-line options |
| 193 | ~~~~~~~~~~~~~~~~~~~~ |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 194 | |
Éric Araujo | d3309df | 2010-11-21 03:09:17 +0000 | [diff] [blame] | 195 | :program:`unittest` supports these command-line options: |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 196 | |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 197 | .. program:: unittest |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 198 | |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 199 | .. cmdoption:: -b, --buffer |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 200 | |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 201 | The standard output and standard error streams are buffered during the test |
| 202 | run. Output during a passing test is discarded. Output is echoed normally |
| 203 | on test fail or error and is added to the failure messages. |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 204 | |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 205 | .. cmdoption:: -c, --catch |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 206 | |
Serhiy Storchaka | 0424eaf | 2015-09-12 17:45:25 +0300 | [diff] [blame] | 207 | :kbd:`Control-C` during the test run waits for the current test to end and then |
| 208 | reports all the results so far. A second :kbd:`Control-C` raises the normal |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 209 | :exc:`KeyboardInterrupt` exception. |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 210 | |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 211 | See `Signal Handling`_ for the functions that provide this functionality. |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 212 | |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 213 | .. cmdoption:: -f, --failfast |
| 214 | |
| 215 | Stop the test run on the first error or failure. |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 216 | |
Ezio Melotti | 7afd3f5 | 2010-04-20 09:32:54 +0000 | [diff] [blame] | 217 | .. versionadded:: 3.2 |
Éric Araujo | d6c5f74 | 2010-12-16 00:07:01 +0000 | [diff] [blame] | 218 | The command-line options ``-b``, ``-c`` and ``-f`` were added. |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 219 | |
| 220 | The command line can also be used for test discovery, for running all of the |
| 221 | tests in a project or just a subset. |
| 222 | |
| 223 | |
| 224 | .. _unittest-test-discovery: |
| 225 | |
| 226 | Test Discovery |
| 227 | -------------- |
| 228 | |
Ezio Melotti | 7afd3f5 | 2010-04-20 09:32:54 +0000 | [diff] [blame] | 229 | .. versionadded:: 3.2 |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 230 | |
Ezio Melotti | 3d99584 | 2011-03-08 16:17:35 +0200 | [diff] [blame] | 231 | Unittest supports simple test discovery. In order to be compatible with test |
| 232 | discovery, all of the test files must be :ref:`modules <tut-modules>` or |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 233 | :ref:`packages <tut-packages>` (including :term:`namespace packages |
| 234 | <namespace package>`) importable from the top-level directory of |
| 235 | the project (this means that their filenames must be valid :ref:`identifiers |
| 236 | <identifiers>`). |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 237 | |
| 238 | Test discovery is implemented in :meth:`TestLoader.discover`, but can also be |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 239 | used from the command line. The basic command-line usage is:: |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 240 | |
| 241 | cd project_directory |
| 242 | python -m unittest discover |
| 243 | |
Michael Foord | 086f308 | 2010-11-21 21:28:01 +0000 | [diff] [blame] | 244 | .. note:: |
| 245 | |
| 246 | As a shortcut, ``python -m unittest`` is the equivalent of |
| 247 | ``python -m unittest discover``. If you want to pass arguments to test |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 248 | discovery the ``discover`` sub-command must be used explicitly. |
Michael Foord | 086f308 | 2010-11-21 21:28:01 +0000 | [diff] [blame] | 249 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 250 | The ``discover`` sub-command has the following options: |
| 251 | |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 252 | .. program:: unittest discover |
| 253 | |
| 254 | .. cmdoption:: -v, --verbose |
| 255 | |
| 256 | Verbose output |
| 257 | |
Chris Jerdonek | d69ad55 | 2013-02-21 18:54:43 -0800 | [diff] [blame] | 258 | .. cmdoption:: -s, --start-directory directory |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 259 | |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 260 | Directory to start discovery (``.`` default) |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 261 | |
Chris Jerdonek | d69ad55 | 2013-02-21 18:54:43 -0800 | [diff] [blame] | 262 | .. cmdoption:: -p, --pattern pattern |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 263 | |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 264 | Pattern to match test files (``test*.py`` default) |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 265 | |
Chris Jerdonek | d69ad55 | 2013-02-21 18:54:43 -0800 | [diff] [blame] | 266 | .. cmdoption:: -t, --top-level-directory directory |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 267 | |
| 268 | Top level directory of project (defaults to start directory) |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 269 | |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 270 | The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in |
| 271 | as positional arguments in that order. The following two command lines |
| 272 | are equivalent:: |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 273 | |
Robert Collins | a2b0055 | 2015-08-24 12:14:28 +1200 | [diff] [blame] | 274 | python -m unittest discover -s project_directory -p "*_test.py" |
| 275 | python -m unittest discover project_directory "*_test.py" |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 276 | |
Michael Foord | 16f3e90 | 2010-05-08 15:13:42 +0000 | [diff] [blame] | 277 | As well as being a path it is possible to pass a package name, for example |
| 278 | ``myproject.subpackage.test``, as the start directory. The package name you |
| 279 | supply will then be imported and its location on the filesystem will be used |
| 280 | as the start directory. |
| 281 | |
| 282 | .. caution:: |
| 283 | |
Senthil Kumaran | 916bd38 | 2010-10-15 12:55:19 +0000 | [diff] [blame] | 284 | Test discovery loads tests by importing them. Once test discovery has found |
| 285 | all the test files from the start directory you specify it turns the paths |
| 286 | into package names to import. For example :file:`foo/bar/baz.py` will be |
Michael Foord | 16f3e90 | 2010-05-08 15:13:42 +0000 | [diff] [blame] | 287 | imported as ``foo.bar.baz``. |
| 288 | |
| 289 | If you have a package installed globally and attempt test discovery on |
| 290 | a different copy of the package then the import *could* happen from the |
| 291 | wrong place. If this happens test discovery will warn you and exit. |
| 292 | |
| 293 | If you supply the start directory as a package name rather than a |
| 294 | path to a directory then discover assumes that whichever location it |
| 295 | imports from is the location you intended, so you will not get the |
| 296 | warning. |
| 297 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 298 | Test modules and packages can customize test loading and discovery by through |
| 299 | the `load_tests protocol`_. |
| 300 | |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 301 | .. versionchanged:: 3.4 |
| 302 | Test discovery supports :term:`namespace packages <namespace package>`. |
| 303 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 304 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 305 | .. _organizing-tests: |
| 306 | |
| 307 | Organizing test code |
| 308 | -------------------- |
| 309 | |
| 310 | The basic building blocks of unit testing are :dfn:`test cases` --- single |
| 311 | scenarios that must be set up and checked for correctness. In :mod:`unittest`, |
Raymond Hettinger | 833ad0e | 2011-02-06 21:00:38 +0000 | [diff] [blame] | 312 | test cases are represented by :class:`unittest.TestCase` instances. |
| 313 | To make your own test cases you must write subclasses of |
| 314 | :class:`TestCase` or use :class:`FunctionTestCase`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 315 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 316 | The testing code of a :class:`TestCase` instance should be entirely self |
| 317 | contained, such that it can be run either in isolation or in arbitrary |
| 318 | combination with any number of other test cases. |
| 319 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 320 | The simplest :class:`TestCase` subclass will simply implement a test method |
| 321 | (i.e. a method whose name starts with ``test``) in order to perform specific |
| 322 | testing code:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 323 | |
| 324 | import unittest |
| 325 | |
| 326 | class DefaultWidgetSizeTestCase(unittest.TestCase): |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 327 | def test_default_widget_size(self): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 328 | widget = Widget('The widget') |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 329 | self.assertEqual(widget.size(), (50, 50)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 330 | |
Sandro Tosi | 41b2404 | 2012-01-21 10:59:37 +0100 | [diff] [blame] | 331 | Note that in order to test something, we use one of the :meth:`assert\*` |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 332 | methods provided by the :class:`TestCase` base class. If the test fails, an |
| 333 | exception will be raised, and :mod:`unittest` will identify the test case as a |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 334 | :dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 335 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 336 | Tests can be numerous, and their set-up can be repetitive. Luckily, we |
| 337 | can factor out set-up code by implementing a method called |
| 338 | :meth:`~TestCase.setUp`, which the testing framework will automatically |
| 339 | call for every single test we run:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 340 | |
| 341 | import unittest |
| 342 | |
| 343 | class SimpleWidgetTestCase(unittest.TestCase): |
| 344 | def setUp(self): |
| 345 | self.widget = Widget('The widget') |
| 346 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 347 | def test_default_widget_size(self): |
Ezio Melotti | 2d6c39b | 2010-02-04 20:27:41 +0000 | [diff] [blame] | 348 | self.assertEqual(self.widget.size(), (50,50), |
| 349 | 'incorrect default size') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 350 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 351 | def test_widget_resize(self): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 352 | self.widget.resize(100,150) |
Ezio Melotti | 2d6c39b | 2010-02-04 20:27:41 +0000 | [diff] [blame] | 353 | self.assertEqual(self.widget.size(), (100,150), |
| 354 | 'wrong size after resize') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 355 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 356 | .. note:: |
| 357 | The order in which the various tests will be run is determined |
| 358 | by sorting the test method names with respect to the built-in |
| 359 | ordering for strings. |
| 360 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 361 | If the :meth:`~TestCase.setUp` method raises an exception while the test is |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 362 | running, the framework will consider the test to have suffered an error, and |
| 363 | the test method will not be executed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 364 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 365 | Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 366 | after the test method has been run:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 367 | |
| 368 | import unittest |
| 369 | |
| 370 | class SimpleWidgetTestCase(unittest.TestCase): |
| 371 | def setUp(self): |
| 372 | self.widget = Widget('The widget') |
| 373 | |
| 374 | def tearDown(self): |
| 375 | self.widget.dispose() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 376 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 377 | If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be |
| 378 | run whether the test method succeeded or not. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 379 | |
| 380 | Such a working environment for the testing code is called a :dfn:`fixture`. |
| 381 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 382 | Test case instances are grouped together according to the features they test. |
| 383 | :mod:`unittest` provides a mechanism for this: the :dfn:`test suite`, |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 384 | represented by :mod:`unittest`'s :class:`TestSuite` class. In most cases, |
| 385 | calling :func:`unittest.main` will do the right thing and collect all the |
| 386 | module's test cases for you, and then execute them. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 387 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 388 | However, should you want to customize the building of your test suite, |
| 389 | you can do it yourself:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 390 | |
| 391 | def suite(): |
| 392 | suite = unittest.TestSuite() |
Ezio Melotti | d59e44a | 2010-02-28 03:46:13 +0000 | [diff] [blame] | 393 | suite.addTest(WidgetTestCase('test_default_size')) |
| 394 | suite.addTest(WidgetTestCase('test_resize')) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 395 | return suite |
| 396 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 397 | You can place the definitions of test cases and test suites in the same modules |
| 398 | as the code they are to test (such as :file:`widget.py`), but there are several |
| 399 | advantages to placing the test code in a separate module, such as |
| 400 | :file:`test_widget.py`: |
| 401 | |
| 402 | * The test module can be run standalone from the command line. |
| 403 | |
| 404 | * The test code can more easily be separated from shipped code. |
| 405 | |
| 406 | * There is less temptation to change test code to fit the code it tests without |
| 407 | a good reason. |
| 408 | |
| 409 | * Test code should be modified much less frequently than the code it tests. |
| 410 | |
| 411 | * Tested code can be refactored more easily. |
| 412 | |
| 413 | * Tests for modules written in C must be in separate modules anyway, so why not |
| 414 | be consistent? |
| 415 | |
| 416 | * If the testing strategy changes, there is no need to change the source code. |
| 417 | |
| 418 | |
| 419 | .. _legacy-unit-tests: |
| 420 | |
| 421 | Re-using old test code |
| 422 | ---------------------- |
| 423 | |
| 424 | Some users will find that they have existing test code that they would like to |
| 425 | run from :mod:`unittest`, without converting every old test function to a |
| 426 | :class:`TestCase` subclass. |
| 427 | |
| 428 | For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class. |
| 429 | This subclass of :class:`TestCase` can be used to wrap an existing test |
| 430 | function. Set-up and tear-down functions can also be provided. |
| 431 | |
| 432 | Given the following test function:: |
| 433 | |
| 434 | def testSomething(): |
| 435 | something = makeSomething() |
| 436 | assert something.name is not None |
| 437 | # ... |
| 438 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 439 | one can create an equivalent test case instance as follows, with optional |
| 440 | set-up and tear-down methods:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 441 | |
| 442 | testcase = unittest.FunctionTestCase(testSomething, |
| 443 | setUp=makeSomethingDB, |
| 444 | tearDown=deleteSomethingDB) |
| 445 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 446 | .. note:: |
| 447 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 448 | Even though :class:`FunctionTestCase` can be used to quickly convert an |
| 449 | existing test base over to a :mod:`unittest`\ -based system, this approach is |
| 450 | not recommended. Taking the time to set up proper :class:`TestCase` |
| 451 | subclasses will make future test refactorings infinitely easier. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 452 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 453 | In some cases, the existing tests may have been written using the :mod:`doctest` |
| 454 | module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can |
| 455 | automatically build :class:`unittest.TestSuite` instances from the existing |
| 456 | :mod:`doctest`\ -based tests. |
| 457 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 458 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 459 | .. _unittest-skipping: |
| 460 | |
| 461 | Skipping tests and expected failures |
| 462 | ------------------------------------ |
| 463 | |
Michael Foord | f5c851a | 2010-02-05 21:48:03 +0000 | [diff] [blame] | 464 | .. versionadded:: 3.1 |
| 465 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 466 | Unittest supports skipping individual test methods and even whole classes of |
Serhiy Storchaka | d65c949 | 2015-11-02 14:10:23 +0200 | [diff] [blame] | 467 | tests. In addition, it supports marking a test as an "expected failure," a test |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 468 | that is broken and will fail, but shouldn't be counted as a failure on a |
| 469 | :class:`TestResult`. |
| 470 | |
| 471 | Skipping a test is simply a matter of using the :func:`skip` :term:`decorator` |
| 472 | or one of its conditional variants. |
| 473 | |
Ezio Melotti | fed69ba | 2013-03-01 21:26:04 +0200 | [diff] [blame] | 474 | Basic skipping looks like this:: |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 475 | |
| 476 | class MyTestCase(unittest.TestCase): |
| 477 | |
| 478 | @unittest.skip("demonstrating skipping") |
| 479 | def test_nothing(self): |
| 480 | self.fail("shouldn't happen") |
| 481 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 482 | @unittest.skipIf(mylib.__version__ < (1, 3), |
| 483 | "not supported in this library version") |
Benjamin Peterson | ded31c4 | 2009-03-30 15:04:16 +0000 | [diff] [blame] | 484 | def test_format(self): |
| 485 | # Tests that work for only a certain version of the library. |
| 486 | pass |
| 487 | |
| 488 | @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") |
| 489 | def test_windows_support(self): |
| 490 | # windows specific testing code |
| 491 | pass |
| 492 | |
Ezio Melotti | fed69ba | 2013-03-01 21:26:04 +0200 | [diff] [blame] | 493 | This is the output of running the example above in verbose mode:: |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 494 | |
Benjamin Peterson | ded31c4 | 2009-03-30 15:04:16 +0000 | [diff] [blame] | 495 | test_format (__main__.MyTestCase) ... skipped 'not supported in this library version' |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 496 | test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping' |
Benjamin Peterson | ded31c4 | 2009-03-30 15:04:16 +0000 | [diff] [blame] | 497 | test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows' |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 498 | |
| 499 | ---------------------------------------------------------------------- |
Benjamin Peterson | ded31c4 | 2009-03-30 15:04:16 +0000 | [diff] [blame] | 500 | Ran 3 tests in 0.005s |
| 501 | |
| 502 | OK (skipped=3) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 503 | |
Ezio Melotti | fed69ba | 2013-03-01 21:26:04 +0200 | [diff] [blame] | 504 | Classes can be skipped just like methods:: |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 505 | |
Sandro Tosi | 317075d | 2012-03-31 18:34:59 +0200 | [diff] [blame] | 506 | @unittest.skip("showing class skipping") |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 507 | class MySkippedTestCase(unittest.TestCase): |
| 508 | def test_not_run(self): |
| 509 | pass |
| 510 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 511 | :meth:`TestCase.setUp` can also skip the test. This is useful when a resource |
| 512 | that needs to be set up is not available. |
| 513 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 514 | Expected failures use the :func:`expectedFailure` decorator. :: |
| 515 | |
| 516 | class ExpectedFailureTestCase(unittest.TestCase): |
| 517 | @unittest.expectedFailure |
| 518 | def test_fail(self): |
| 519 | self.assertEqual(1, 0, "broken") |
| 520 | |
| 521 | It's easy to roll your own skipping decorators by making a decorator that calls |
| 522 | :func:`skip` on the test when it wants it to be skipped. This decorator skips |
Ezio Melotti | fed69ba | 2013-03-01 21:26:04 +0200 | [diff] [blame] | 523 | the test unless the passed object has a certain attribute:: |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 524 | |
| 525 | def skipUnlessHasattr(obj, attr): |
| 526 | if hasattr(obj, attr): |
| 527 | return lambda func: func |
Ezio Melotti | 265281a | 2013-03-27 20:11:55 +0200 | [diff] [blame] | 528 | return unittest.skip("{!r} doesn't have {!r}".format(obj, attr)) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 529 | |
| 530 | The following decorators implement test skipping and expected failures: |
| 531 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 532 | .. decorator:: skip(reason) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 533 | |
| 534 | Unconditionally skip the decorated test. *reason* should describe why the |
| 535 | test is being skipped. |
| 536 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 537 | .. decorator:: skipIf(condition, reason) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 538 | |
| 539 | Skip the decorated test if *condition* is true. |
| 540 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 541 | .. decorator:: skipUnless(condition, reason) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 542 | |
Georg Brandl | 6faee4e | 2010-09-21 14:48:28 +0000 | [diff] [blame] | 543 | Skip the decorated test unless *condition* is true. |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 544 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 545 | .. decorator:: expectedFailure |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 546 | |
| 547 | Mark the test as an expected failure. If the test fails when run, the test |
| 548 | is not counted as a failure. |
| 549 | |
Ezio Melotti | 265281a | 2013-03-27 20:11:55 +0200 | [diff] [blame] | 550 | .. exception:: SkipTest(reason) |
| 551 | |
| 552 | This exception is raised to skip a test. |
| 553 | |
| 554 | Usually you can use :meth:`TestCase.skipTest` or one of the skipping |
| 555 | decorators instead of raising this directly. |
| 556 | |
R David Murray | 42fa110 | 2014-01-03 13:03:36 -0500 | [diff] [blame] | 557 | Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them. |
| 558 | Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run. |
| 559 | Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run. |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 560 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 561 | |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 562 | .. _subtests: |
| 563 | |
| 564 | Distinguishing test iterations using subtests |
| 565 | --------------------------------------------- |
| 566 | |
| 567 | .. versionadded:: 3.4 |
| 568 | |
| 569 | When some of your tests differ only by a some very small differences, for |
| 570 | instance some parameters, unittest allows you to distinguish them inside |
| 571 | the body of a test method using the :meth:`~TestCase.subTest` context manager. |
| 572 | |
| 573 | For example, the following test:: |
| 574 | |
| 575 | class NumbersTest(unittest.TestCase): |
| 576 | |
| 577 | def test_even(self): |
| 578 | """ |
| 579 | Test that numbers between 0 and 5 are all even. |
| 580 | """ |
| 581 | for i in range(0, 6): |
| 582 | with self.subTest(i=i): |
| 583 | self.assertEqual(i % 2, 0) |
| 584 | |
| 585 | will produce the following output:: |
| 586 | |
| 587 | ====================================================================== |
| 588 | FAIL: test_even (__main__.NumbersTest) (i=1) |
| 589 | ---------------------------------------------------------------------- |
| 590 | Traceback (most recent call last): |
| 591 | File "subtests.py", line 32, in test_even |
| 592 | self.assertEqual(i % 2, 0) |
| 593 | AssertionError: 1 != 0 |
| 594 | |
| 595 | ====================================================================== |
| 596 | FAIL: test_even (__main__.NumbersTest) (i=3) |
| 597 | ---------------------------------------------------------------------- |
| 598 | Traceback (most recent call last): |
| 599 | File "subtests.py", line 32, in test_even |
| 600 | self.assertEqual(i % 2, 0) |
| 601 | AssertionError: 1 != 0 |
| 602 | |
| 603 | ====================================================================== |
| 604 | FAIL: test_even (__main__.NumbersTest) (i=5) |
| 605 | ---------------------------------------------------------------------- |
| 606 | Traceback (most recent call last): |
| 607 | File "subtests.py", line 32, in test_even |
| 608 | self.assertEqual(i % 2, 0) |
| 609 | AssertionError: 1 != 0 |
| 610 | |
| 611 | Without using a subtest, execution would stop after the first failure, |
| 612 | and the error would be less easy to diagnose because the value of ``i`` |
| 613 | wouldn't be displayed:: |
| 614 | |
| 615 | ====================================================================== |
| 616 | FAIL: test_even (__main__.NumbersTest) |
| 617 | ---------------------------------------------------------------------- |
| 618 | Traceback (most recent call last): |
| 619 | File "subtests.py", line 32, in test_even |
| 620 | self.assertEqual(i % 2, 0) |
| 621 | AssertionError: 1 != 0 |
| 622 | |
| 623 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 624 | .. _unittest-contents: |
| 625 | |
| 626 | Classes and functions |
| 627 | --------------------- |
| 628 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 629 | This section describes in depth the API of :mod:`unittest`. |
| 630 | |
| 631 | |
| 632 | .. _testcase-objects: |
| 633 | |
| 634 | Test cases |
| 635 | ~~~~~~~~~~ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 636 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 637 | .. class:: TestCase(methodName='runTest') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 638 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 639 | Instances of the :class:`TestCase` class represent the logical test units |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 640 | in the :mod:`unittest` universe. This class is intended to be used as a base |
| 641 | class, with specific tests being implemented by concrete subclasses. This class |
| 642 | implements the interface needed by the test runner to allow it to drive the |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 643 | tests, and methods that the test code can use to check for and report various |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 644 | kinds of failure. |
| 645 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 646 | Each instance of :class:`TestCase` will run a single base method: the method |
Robert Collins | e02f6c2 | 2015-07-23 06:37:26 +1200 | [diff] [blame] | 647 | named *methodName*. |
| 648 | In most uses of :class:`TestCase`, you will neither change |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 649 | the *methodName* nor reimplement the default ``runTest()`` method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 650 | |
Michael Foord | 1341bb0 | 2011-03-14 19:01:46 -0400 | [diff] [blame] | 651 | .. versionchanged:: 3.2 |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 652 | :class:`TestCase` can be instantiated successfully without providing a |
| 653 | *methodName*. This makes it easier to experiment with :class:`TestCase` |
| 654 | from the interactive interpreter. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 655 | |
| 656 | :class:`TestCase` instances provide three groups of methods: one group used |
| 657 | to run the test, another used by the test implementation to check conditions |
| 658 | and report failures, and some inquiry methods allowing information about the |
| 659 | test itself to be gathered. |
| 660 | |
| 661 | Methods in the first group (running the test) are: |
| 662 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 663 | .. method:: setUp() |
| 664 | |
| 665 | Method called to prepare the test fixture. This is called immediately |
Terry Jan Reedy | 7f84d1e | 2014-04-15 23:44:14 -0400 | [diff] [blame] | 666 | before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`, |
| 667 | any exception raised by this method will be considered an error rather than |
Terry Jan Reedy | 6ac4240 | 2014-04-15 23:38:18 -0400 | [diff] [blame] | 668 | a test failure. The default implementation does nothing. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 669 | |
| 670 | |
| 671 | .. method:: tearDown() |
| 672 | |
| 673 | Method called immediately after the test method has been called and the |
| 674 | result recorded. This is called even if the test method raised an |
| 675 | exception, so the implementation in subclasses may need to be particularly |
Terry Jan Reedy | 7f84d1e | 2014-04-15 23:44:14 -0400 | [diff] [blame] | 676 | careful about checking internal state. Any exception, other than :exc:`AssertionError` |
| 677 | or :exc:`SkipTest`, raised by this method will be considered an error rather than a |
| 678 | test failure. This method will only be called if the :meth:`setUp` succeeds, |
Terry Jan Reedy | 6ac4240 | 2014-04-15 23:38:18 -0400 | [diff] [blame] | 679 | regardless of the outcome of the test method. The default implementation does nothing. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 680 | |
| 681 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 682 | .. method:: setUpClass() |
| 683 | |
| 684 | A class method called before tests in an individual class run. |
| 685 | ``setUpClass`` is called with the class as the only argument |
| 686 | and must be decorated as a :func:`classmethod`:: |
| 687 | |
| 688 | @classmethod |
| 689 | def setUpClass(cls): |
| 690 | ... |
| 691 | |
| 692 | See `Class and Module Fixtures`_ for more details. |
| 693 | |
| 694 | .. versionadded:: 3.2 |
| 695 | |
| 696 | |
| 697 | .. method:: tearDownClass() |
| 698 | |
| 699 | A class method called after tests in an individual class have run. |
| 700 | ``tearDownClass`` is called with the class as the only argument |
| 701 | and must be decorated as a :meth:`classmethod`:: |
| 702 | |
| 703 | @classmethod |
| 704 | def tearDownClass(cls): |
| 705 | ... |
| 706 | |
| 707 | See `Class and Module Fixtures`_ for more details. |
| 708 | |
| 709 | .. versionadded:: 3.2 |
| 710 | |
| 711 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 712 | .. method:: run(result=None) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 713 | |
Antoine Pitrou | 2c5e950 | 2013-01-20 01:29:39 +0100 | [diff] [blame] | 714 | Run the test, collecting the result into the :class:`TestResult` object |
| 715 | passed as *result*. If *result* is omitted or ``None``, a temporary |
| 716 | result object is created (by calling the :meth:`defaultTestResult` |
| 717 | method) and used. The result object is returned to :meth:`run`'s |
| 718 | caller. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 719 | |
| 720 | The same effect may be had by simply calling the :class:`TestCase` |
| 721 | instance. |
| 722 | |
Michael Foord | 1341bb0 | 2011-03-14 19:01:46 -0400 | [diff] [blame] | 723 | .. versionchanged:: 3.3 |
| 724 | Previous versions of ``run`` did not return the result. Neither did |
| 725 | calling an instance. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 726 | |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 727 | .. method:: skipTest(reason) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 728 | |
Stefan Krah | a5bf3f5 | 2010-05-19 16:09:41 +0000 | [diff] [blame] | 729 | Calling this during a test method or :meth:`setUp` skips the current |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 730 | test. See :ref:`unittest-skipping` for more information. |
| 731 | |
Ezio Melotti | 7afd3f5 | 2010-04-20 09:32:54 +0000 | [diff] [blame] | 732 | .. versionadded:: 3.1 |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 733 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 734 | |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 735 | .. method:: subTest(msg=None, **params) |
| 736 | |
| 737 | Return a context manager which executes the enclosed code block as a |
| 738 | subtest. *msg* and *params* are optional, arbitrary values which are |
| 739 | displayed whenever a subtest fails, allowing you to identify them |
| 740 | clearly. |
| 741 | |
| 742 | A test case can contain any number of subtest declarations, and |
| 743 | they can be arbitrarily nested. |
| 744 | |
| 745 | See :ref:`subtests` for more information. |
| 746 | |
| 747 | .. versionadded:: 3.4 |
| 748 | |
| 749 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 750 | .. method:: debug() |
| 751 | |
| 752 | Run the test without collecting the result. This allows exceptions raised |
| 753 | by the test to be propagated to the caller, and can be used to support |
| 754 | running tests under a debugger. |
| 755 | |
Ezio Melotti | 22170ed | 2010-11-20 09:57:27 +0000 | [diff] [blame] | 756 | .. _assert-methods: |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 757 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 758 | The :class:`TestCase` class provides a number of methods to check for and |
| 759 | report failures, such as: |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 760 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 761 | +-----------------------------------------+-----------------------------+---------------+ |
| 762 | | Method | Checks that | New in | |
| 763 | +=========================================+=============================+===============+ |
| 764 | | :meth:`assertEqual(a, b) | ``a == b`` | | |
| 765 | | <TestCase.assertEqual>` | | | |
| 766 | +-----------------------------------------+-----------------------------+---------------+ |
| 767 | | :meth:`assertNotEqual(a, b) | ``a != b`` | | |
| 768 | | <TestCase.assertNotEqual>` | | | |
| 769 | +-----------------------------------------+-----------------------------+---------------+ |
| 770 | | :meth:`assertTrue(x) | ``bool(x) is True`` | | |
| 771 | | <TestCase.assertTrue>` | | | |
| 772 | +-----------------------------------------+-----------------------------+---------------+ |
| 773 | | :meth:`assertFalse(x) | ``bool(x) is False`` | | |
| 774 | | <TestCase.assertFalse>` | | | |
| 775 | +-----------------------------------------+-----------------------------+---------------+ |
| 776 | | :meth:`assertIs(a, b) | ``a is b`` | 3.1 | |
| 777 | | <TestCase.assertIs>` | | | |
| 778 | +-----------------------------------------+-----------------------------+---------------+ |
| 779 | | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 | |
| 780 | | <TestCase.assertIsNot>` | | | |
| 781 | +-----------------------------------------+-----------------------------+---------------+ |
| 782 | | :meth:`assertIsNone(x) | ``x is None`` | 3.1 | |
| 783 | | <TestCase.assertIsNone>` | | | |
| 784 | +-----------------------------------------+-----------------------------+---------------+ |
| 785 | | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 | |
| 786 | | <TestCase.assertIsNotNone>` | | | |
| 787 | +-----------------------------------------+-----------------------------+---------------+ |
| 788 | | :meth:`assertIn(a, b) | ``a in b`` | 3.1 | |
| 789 | | <TestCase.assertIn>` | | | |
| 790 | +-----------------------------------------+-----------------------------+---------------+ |
| 791 | | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 | |
| 792 | | <TestCase.assertNotIn>` | | | |
| 793 | +-----------------------------------------+-----------------------------+---------------+ |
| 794 | | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 | |
| 795 | | <TestCase.assertIsInstance>` | | | |
| 796 | +-----------------------------------------+-----------------------------+---------------+ |
| 797 | | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 | |
| 798 | | <TestCase.assertNotIsInstance>` | | | |
| 799 | +-----------------------------------------+-----------------------------+---------------+ |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 800 | |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 801 | All the assert methods accept a *msg* argument that, if specified, is used |
| 802 | as the error message on failure (see also :data:`longMessage`). |
| 803 | Note that the *msg* keyword argument can be passed to :meth:`assertRaises`, |
| 804 | :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex` |
| 805 | only when they are used as a context manager. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 806 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 807 | .. method:: assertEqual(first, second, msg=None) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 808 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 809 | Test that *first* and *second* are equal. If the values do not |
Ezio Melotti | addc6f5 | 2010-12-18 20:00:04 +0000 | [diff] [blame] | 810 | compare equal, the test will fail. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 811 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 812 | In addition, if *first* and *second* are the exact same type and one of |
Michael Foord | 0283495 | 2010-02-08 23:10:39 +0000 | [diff] [blame] | 813 | list, tuple, dict, set, frozenset or str or any type that a subclass |
Ezio Melotti | 9ecb6be | 2012-01-16 08:28:54 +0200 | [diff] [blame] | 814 | registers with :meth:`addTypeEqualityFunc` the type-specific equality |
Michael Foord | 0283495 | 2010-02-08 23:10:39 +0000 | [diff] [blame] | 815 | function will be called in order to generate a more useful default |
Ezio Melotti | 22170ed | 2010-11-20 09:57:27 +0000 | [diff] [blame] | 816 | error message (see also the :ref:`list of type-specific methods |
| 817 | <type-specific-methods>`). |
Ezio Melotti | 4841fd6 | 2010-11-05 15:43:40 +0000 | [diff] [blame] | 818 | |
Raymond Hettinger | 35a8836 | 2009-04-09 00:08:24 +0000 | [diff] [blame] | 819 | .. versionchanged:: 3.1 |
Ezio Melotti | 9ecb6be | 2012-01-16 08:28:54 +0200 | [diff] [blame] | 820 | Added the automatic calling of type-specific equality function. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 821 | |
Michael Foord | 28a817e | 2010-02-09 00:03:57 +0000 | [diff] [blame] | 822 | .. versionchanged:: 3.2 |
| 823 | :meth:`assertMultiLineEqual` added as the default type equality |
| 824 | function for comparing strings. |
Michael Foord | 0283495 | 2010-02-08 23:10:39 +0000 | [diff] [blame] | 825 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 826 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 827 | .. method:: assertNotEqual(first, second, msg=None) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 828 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 829 | Test that *first* and *second* are not equal. If the values do |
Ezio Melotti | addc6f5 | 2010-12-18 20:00:04 +0000 | [diff] [blame] | 830 | compare equal, the test will fail. |
Benjamin Peterson | 70e32c8 | 2009-03-24 01:00:11 +0000 | [diff] [blame] | 831 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 832 | .. method:: assertTrue(expr, msg=None) |
Ezio Melotti | 4841fd6 | 2010-11-05 15:43:40 +0000 | [diff] [blame] | 833 | assertFalse(expr, msg=None) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 834 | |
Ezio Melotti | 4841fd6 | 2010-11-05 15:43:40 +0000 | [diff] [blame] | 835 | Test that *expr* is true (or false). |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 836 | |
Ezio Melotti | 4841fd6 | 2010-11-05 15:43:40 +0000 | [diff] [blame] | 837 | Note that this is equivalent to ``bool(expr) is True`` and not to ``expr |
| 838 | is True`` (use ``assertIs(expr, True)`` for the latter). This method |
| 839 | should also be avoided when more specific methods are available (e.g. |
| 840 | ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they |
| 841 | provide a better error message in case of failure. |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 842 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 843 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 844 | .. method:: assertIs(first, second, msg=None) |
| 845 | assertIsNot(first, second, msg=None) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 846 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 847 | Test that *first* and *second* evaluate (or don't evaluate) to the |
Ezio Melotti | addc6f5 | 2010-12-18 20:00:04 +0000 | [diff] [blame] | 848 | same object. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 849 | |
Raymond Hettinger | 35a8836 | 2009-04-09 00:08:24 +0000 | [diff] [blame] | 850 | .. versionadded:: 3.1 |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 851 | |
| 852 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 853 | .. method:: assertIsNone(expr, msg=None) |
Ezio Melotti | 9794a26 | 2010-11-04 14:52:13 +0000 | [diff] [blame] | 854 | assertIsNotNone(expr, msg=None) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 855 | |
Ezio Melotti | 9794a26 | 2010-11-04 14:52:13 +0000 | [diff] [blame] | 856 | Test that *expr* is (or is not) None. |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 857 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 858 | .. versionadded:: 3.1 |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 859 | |
| 860 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 861 | .. method:: assertIn(first, second, msg=None) |
| 862 | assertNotIn(first, second, msg=None) |
| 863 | |
Ezio Melotti | 4841fd6 | 2010-11-05 15:43:40 +0000 | [diff] [blame] | 864 | Test that *first* is (or is not) in *second*. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 865 | |
Raymond Hettinger | 35a8836 | 2009-04-09 00:08:24 +0000 | [diff] [blame] | 866 | .. versionadded:: 3.1 |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 867 | |
| 868 | |
Ezio Melotti | 9c02c2f | 2010-11-03 20:45:31 +0000 | [diff] [blame] | 869 | .. method:: assertIsInstance(obj, cls, msg=None) |
Ezio Melotti | 9794a26 | 2010-11-04 14:52:13 +0000 | [diff] [blame] | 870 | assertNotIsInstance(obj, cls, msg=None) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 871 | |
Ezio Melotti | 9794a26 | 2010-11-04 14:52:13 +0000 | [diff] [blame] | 872 | Test that *obj* is (or is not) an instance of *cls* (which can be a |
| 873 | class or a tuple of classes, as supported by :func:`isinstance`). |
Ezio Melotti | 80a61e8 | 2011-12-19 07:04:48 +0200 | [diff] [blame] | 874 | To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 875 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 876 | .. versionadded:: 3.2 |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 877 | |
| 878 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 879 | |
Antoine Pitrou | 7c89ae2 | 2013-09-15 02:01:39 +0200 | [diff] [blame] | 880 | It is also possible to check the production of exceptions, warnings and |
| 881 | log messages using the following methods: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 882 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 883 | +---------------------------------------------------------+--------------------------------------+------------+ |
| 884 | | Method | Checks that | New in | |
| 885 | +=========================================================+======================================+============+ |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 886 | | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 887 | | <TestCase.assertRaises>` | | | |
| 888 | +---------------------------------------------------------+--------------------------------------+------------+ |
Ezio Melotti | 560a778 | 2013-09-13 22:17:40 +0300 | [diff] [blame] | 889 | | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 | |
| 890 | | <TestCase.assertRaisesRegex>` | and the message matches regex *r* | | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 891 | +---------------------------------------------------------+--------------------------------------+------------+ |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 892 | | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 893 | | <TestCase.assertWarns>` | | | |
| 894 | +---------------------------------------------------------+--------------------------------------+------------+ |
Ezio Melotti | 560a778 | 2013-09-13 22:17:40 +0300 | [diff] [blame] | 895 | | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 | |
| 896 | | <TestCase.assertWarnsRegex>` | and the message matches regex *r* | | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 897 | +---------------------------------------------------------+--------------------------------------+------------+ |
Georg Brandl | ed007d5 | 2013-11-24 16:09:26 +0100 | [diff] [blame] | 898 | | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 | |
| 899 | | <TestCase.assertLogs>` | with minimum *level* | | |
Antoine Pitrou | 7c89ae2 | 2013-09-15 02:01:39 +0200 | [diff] [blame] | 900 | +---------------------------------------------------------+--------------------------------------+------------+ |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 901 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 902 | .. method:: assertRaises(exception, callable, *args, **kwds) |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 903 | assertRaises(exception, msg=None) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 904 | |
| 905 | Test that an exception is raised when *callable* is called with any |
| 906 | positional or keyword arguments that are also passed to |
| 907 | :meth:`assertRaises`. The test passes if *exception* is raised, is an |
| 908 | error if another exception is raised, or fails if no exception is raised. |
| 909 | To catch any of a group of exceptions, a tuple containing the exception |
| 910 | classes may be passed as *exception*. |
| 911 | |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 912 | If only the *exception* and possibly the *msg* arguments are given, |
| 913 | return a context manager so that the code under test can be written |
| 914 | inline rather than as a function:: |
Benjamin Peterson | ded31c4 | 2009-03-30 15:04:16 +0000 | [diff] [blame] | 915 | |
Michael Foord | 41531f2 | 2010-02-05 21:13:40 +0000 | [diff] [blame] | 916 | with self.assertRaises(SomeException): |
Benjamin Peterson | ded31c4 | 2009-03-30 15:04:16 +0000 | [diff] [blame] | 917 | do_something() |
| 918 | |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 919 | When used as a context manager, :meth:`assertRaises` accepts the |
| 920 | additional keyword argument *msg*. |
| 921 | |
Kristján Valur Jónsson | 92a653a | 2009-11-13 16:10:13 +0000 | [diff] [blame] | 922 | The context manager will store the caught exception object in its |
Ezio Melotti | 4900823 | 2010-02-08 21:57:48 +0000 | [diff] [blame] | 923 | :attr:`exception` attribute. This can be useful if the intention |
Michael Foord | 41531f2 | 2010-02-05 21:13:40 +0000 | [diff] [blame] | 924 | is to perform additional checks on the exception raised:: |
Kristján Valur Jónsson | 92a653a | 2009-11-13 16:10:13 +0000 | [diff] [blame] | 925 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 926 | with self.assertRaises(SomeException) as cm: |
| 927 | do_something() |
Michael Foord | 41531f2 | 2010-02-05 21:13:40 +0000 | [diff] [blame] | 928 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 929 | the_exception = cm.exception |
| 930 | self.assertEqual(the_exception.error_code, 3) |
Michael Foord | 41531f2 | 2010-02-05 21:13:40 +0000 | [diff] [blame] | 931 | |
Ezio Melotti | 4900823 | 2010-02-08 21:57:48 +0000 | [diff] [blame] | 932 | .. versionchanged:: 3.1 |
Benjamin Peterson | ded31c4 | 2009-03-30 15:04:16 +0000 | [diff] [blame] | 933 | Added the ability to use :meth:`assertRaises` as a context manager. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 934 | |
Ezio Melotti | 4900823 | 2010-02-08 21:57:48 +0000 | [diff] [blame] | 935 | .. versionchanged:: 3.2 |
| 936 | Added the :attr:`exception` attribute. |
| 937 | |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 938 | .. versionchanged:: 3.3 |
| 939 | Added the *msg* keyword argument when used as a context manager. |
| 940 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 941 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 942 | .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds) |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 943 | assertRaisesRegex(exception, regex, msg=None) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 944 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 945 | Like :meth:`assertRaises` but also tests that *regex* matches |
| 946 | on the string representation of the raised exception. *regex* may be |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 947 | a regular expression object or a string containing a regular expression |
| 948 | suitable for use by :func:`re.search`. Examples:: |
| 949 | |
Terry Jan Reedy | c4565a9 | 2013-06-29 13:15:43 -0400 | [diff] [blame] | 950 | self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$", |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 951 | int, 'XYZ') |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 952 | |
| 953 | or:: |
| 954 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 955 | with self.assertRaisesRegex(ValueError, 'literal'): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 956 | int('XYZ') |
| 957 | |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 958 | .. versionadded:: 3.1 |
| 959 | under the name ``assertRaisesRegexp``. |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 960 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 961 | .. versionchanged:: 3.2 |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 962 | Renamed to :meth:`assertRaisesRegex`. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 963 | |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 964 | .. versionchanged:: 3.3 |
| 965 | Added the *msg* keyword argument when used as a context manager. |
| 966 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 967 | |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 968 | .. method:: assertWarns(warning, callable, *args, **kwds) |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 969 | assertWarns(warning, msg=None) |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 970 | |
| 971 | Test that a warning is triggered when *callable* is called with any |
| 972 | positional or keyword arguments that are also passed to |
| 973 | :meth:`assertWarns`. The test passes if *warning* is triggered and |
Terry Jan Reedy | 778cba7 | 2013-07-30 22:31:06 -0400 | [diff] [blame] | 974 | fails if it isn't. Any exception is an error. |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 975 | To catch any of a group of warnings, a tuple containing the warning |
| 976 | classes may be passed as *warnings*. |
| 977 | |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 978 | If only the *warning* and possibly the *msg* arguments are given, |
Terry Jan Reedy | 778cba7 | 2013-07-30 22:31:06 -0400 | [diff] [blame] | 979 | return a context manager so that the code under test can be written |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 980 | inline rather than as a function:: |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 981 | |
| 982 | with self.assertWarns(SomeWarning): |
| 983 | do_something() |
| 984 | |
Terry Jan Reedy | 9eda66d | 2013-07-27 16:15:29 -0400 | [diff] [blame] | 985 | When used as a context manager, :meth:`assertWarns` accepts the |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 986 | additional keyword argument *msg*. |
| 987 | |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 988 | The context manager will store the caught warning object in its |
| 989 | :attr:`warning` attribute, and the source line which triggered the |
| 990 | warnings in the :attr:`filename` and :attr:`lineno` attributes. |
| 991 | This can be useful if the intention is to perform additional checks |
Terry Jan Reedy | 778cba7 | 2013-07-30 22:31:06 -0400 | [diff] [blame] | 992 | on the warning caught:: |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 993 | |
| 994 | with self.assertWarns(SomeWarning) as cm: |
| 995 | do_something() |
| 996 | |
| 997 | self.assertIn('myfile.py', cm.filename) |
| 998 | self.assertEqual(320, cm.lineno) |
| 999 | |
| 1000 | This method works regardless of the warning filters in place when it |
| 1001 | is called. |
| 1002 | |
| 1003 | .. versionadded:: 3.2 |
| 1004 | |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 1005 | .. versionchanged:: 3.3 |
| 1006 | Added the *msg* keyword argument when used as a context manager. |
| 1007 | |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 1008 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1009 | .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds) |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 1010 | assertWarnsRegex(warning, regex, msg=None) |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 1011 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1012 | Like :meth:`assertWarns` but also tests that *regex* matches on the |
| 1013 | message of the triggered warning. *regex* may be a regular expression |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 1014 | object or a string containing a regular expression suitable for use |
| 1015 | by :func:`re.search`. Example:: |
| 1016 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1017 | self.assertWarnsRegex(DeprecationWarning, |
| 1018 | r'legacy_function\(\) is deprecated', |
| 1019 | legacy_function, 'XYZ') |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 1020 | |
| 1021 | or:: |
| 1022 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1023 | with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'): |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 1024 | frobnicate('/etc/passwd') |
| 1025 | |
| 1026 | .. versionadded:: 3.2 |
| 1027 | |
Ezio Melotti | b4dc250 | 2011-05-06 15:01:41 +0300 | [diff] [blame] | 1028 | .. versionchanged:: 3.3 |
| 1029 | Added the *msg* keyword argument when used as a context manager. |
Antoine Pitrou | 4bc12ef | 2010-09-06 19:25:46 +0000 | [diff] [blame] | 1030 | |
Antoine Pitrou | 0715b9f | 2013-09-14 19:45:47 +0200 | [diff] [blame] | 1031 | .. method:: assertLogs(logger=None, level=None) |
| 1032 | |
| 1033 | A context manager to test that at least one message is logged on |
| 1034 | the *logger* or one of its children, with at least the given |
| 1035 | *level*. |
| 1036 | |
| 1037 | If given, *logger* should be a :class:`logging.Logger` object or a |
| 1038 | :class:`str` giving the name of a logger. The default is the root |
| 1039 | logger, which will catch all messages. |
| 1040 | |
| 1041 | If given, *level* should be either a numeric logging level or |
| 1042 | its string equivalent (for example either ``"ERROR"`` or |
| 1043 | :attr:`logging.ERROR`). The default is :attr:`logging.INFO`. |
| 1044 | |
| 1045 | The test passes if at least one message emitted inside the ``with`` |
| 1046 | block matches the *logger* and *level* conditions, otherwise it fails. |
| 1047 | |
| 1048 | The object returned by the context manager is a recording helper |
| 1049 | which keeps tracks of the matching log messages. It has two |
| 1050 | attributes: |
| 1051 | |
| 1052 | .. attribute:: records |
| 1053 | |
| 1054 | A list of :class:`logging.LogRecord` objects of the matching |
| 1055 | log messages. |
| 1056 | |
| 1057 | .. attribute:: output |
| 1058 | |
| 1059 | A list of :class:`str` objects with the formatted output of |
| 1060 | matching messages. |
| 1061 | |
| 1062 | Example:: |
| 1063 | |
| 1064 | with self.assertLogs('foo', level='INFO') as cm: |
| 1065 | logging.getLogger('foo').info('first message') |
| 1066 | logging.getLogger('foo.bar').error('second message') |
| 1067 | self.assertEqual(cm.output, ['INFO:foo:first message', |
| 1068 | 'ERROR:foo.bar:second message']) |
| 1069 | |
| 1070 | .. versionadded:: 3.4 |
| 1071 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1072 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1073 | There are also other methods used to perform more specific checks, such as: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1074 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1075 | +---------------------------------------+--------------------------------+--------------+ |
| 1076 | | Method | Checks that | New in | |
| 1077 | +=======================================+================================+==============+ |
| 1078 | | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | | |
| 1079 | | <TestCase.assertAlmostEqual>` | | | |
| 1080 | +---------------------------------------+--------------------------------+--------------+ |
| 1081 | | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | | |
| 1082 | | <TestCase.assertNotAlmostEqual>` | | | |
| 1083 | +---------------------------------------+--------------------------------+--------------+ |
| 1084 | | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 | |
| 1085 | | <TestCase.assertGreater>` | | | |
| 1086 | +---------------------------------------+--------------------------------+--------------+ |
| 1087 | | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 | |
| 1088 | | <TestCase.assertGreaterEqual>` | | | |
| 1089 | +---------------------------------------+--------------------------------+--------------+ |
| 1090 | | :meth:`assertLess(a, b) | ``a < b`` | 3.1 | |
| 1091 | | <TestCase.assertLess>` | | | |
| 1092 | +---------------------------------------+--------------------------------+--------------+ |
| 1093 | | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 | |
| 1094 | | <TestCase.assertLessEqual>` | | | |
| 1095 | +---------------------------------------+--------------------------------+--------------+ |
Ezio Melotti | 560a778 | 2013-09-13 22:17:40 +0300 | [diff] [blame] | 1096 | | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1097 | | <TestCase.assertRegex>` | | | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1098 | +---------------------------------------+--------------------------------+--------------+ |
Ezio Melotti | 560a778 | 2013-09-13 22:17:40 +0300 | [diff] [blame] | 1099 | | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1100 | | <TestCase.assertNotRegex>` | | | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1101 | +---------------------------------------+--------------------------------+--------------+ |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 1102 | | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 | |
Raymond Hettinger | 6e165b3 | 2010-11-27 09:31:37 +0000 | [diff] [blame] | 1103 | | <TestCase.assertCountEqual>` | elements in the same number, | | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1104 | | | regardless of their order | | |
| 1105 | +---------------------------------------+--------------------------------+--------------+ |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1106 | |
| 1107 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1108 | .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None) |
| 1109 | assertNotAlmostEqual(first, second, places=7, msg=None, delta=None) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1110 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1111 | Test that *first* and *second* are approximately (or not approximately) |
Ezio Melotti | 4841fd6 | 2010-11-05 15:43:40 +0000 | [diff] [blame] | 1112 | equal by computing the difference, rounding to the given number of |
| 1113 | decimal *places* (default 7), and comparing to zero. Note that these |
| 1114 | methods round the values to the given number of *decimal places* (i.e. |
| 1115 | like the :func:`round` function) and not *significant digits*. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1116 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1117 | If *delta* is supplied instead of *places* then the difference |
Ezio Melotti | d51914c | 2013-08-11 13:04:50 +0300 | [diff] [blame] | 1118 | between *first* and *second* must be less or equal to (or greater than) *delta*. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1119 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1120 | Supplying both *delta* and *places* raises a ``TypeError``. |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 1121 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1122 | .. versionchanged:: 3.2 |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 1123 | :meth:`assertAlmostEqual` automatically considers almost equal objects |
| 1124 | that compare equal. :meth:`assertNotAlmostEqual` automatically fails |
| 1125 | if the objects compare equal. Added the *delta* keyword argument. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1126 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1127 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1128 | .. method:: assertGreater(first, second, msg=None) |
| 1129 | assertGreaterEqual(first, second, msg=None) |
| 1130 | assertLess(first, second, msg=None) |
| 1131 | assertLessEqual(first, second, msg=None) |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1132 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1133 | Test that *first* is respectively >, >=, < or <= than *second* depending |
Ezio Melotti | 4841fd6 | 2010-11-05 15:43:40 +0000 | [diff] [blame] | 1134 | on the method name. If not, the test will fail:: |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1135 | |
| 1136 | >>> self.assertGreaterEqual(3, 4) |
| 1137 | AssertionError: "3" unexpectedly not greater than or equal to "4" |
| 1138 | |
| 1139 | .. versionadded:: 3.1 |
| 1140 | |
| 1141 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1142 | .. method:: assertRegex(text, regex, msg=None) |
| 1143 | assertNotRegex(text, regex, msg=None) |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1144 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1145 | Test that a *regex* search matches (or does not match) *text*. In case |
Ezio Melotti | 4841fd6 | 2010-11-05 15:43:40 +0000 | [diff] [blame] | 1146 | of failure, the error message will include the pattern and the *text* (or |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1147 | the pattern and the part of *text* that unexpectedly matched). *regex* |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1148 | may be a regular expression object or a string containing a regular |
| 1149 | expression suitable for use by :func:`re.search`. |
| 1150 | |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 1151 | .. versionadded:: 3.1 |
| 1152 | under the name ``assertRegexpMatches``. |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1153 | .. versionchanged:: 3.2 |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 1154 | The method ``assertRegexpMatches()`` has been renamed to |
| 1155 | :meth:`.assertRegex`. |
| 1156 | .. versionadded:: 3.2 |
| 1157 | :meth:`.assertNotRegex`. |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1158 | |
| 1159 | |
Raymond Hettinger | 57bd00a | 2010-12-24 21:51:48 +0000 | [diff] [blame] | 1160 | .. method:: assertCountEqual(first, second, msg=None) |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1161 | |
Raymond Hettinger | 57bd00a | 2010-12-24 21:51:48 +0000 | [diff] [blame] | 1162 | Test that sequence *first* contains the same elements as *second*, |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1163 | regardless of their order. When they don't, an error message listing the |
| 1164 | differences between the sequences will be generated. |
| 1165 | |
Raymond Hettinger | 57bd00a | 2010-12-24 21:51:48 +0000 | [diff] [blame] | 1166 | Duplicate elements are *not* ignored when comparing *first* and |
| 1167 | *second*. It verifies whether each element has the same count in both |
Raymond Hettinger | 6e165b3 | 2010-11-27 09:31:37 +0000 | [diff] [blame] | 1168 | sequences. Equivalent to: |
Raymond Hettinger | 57bd00a | 2010-12-24 21:51:48 +0000 | [diff] [blame] | 1169 | ``assertEqual(Counter(list(first)), Counter(list(second)))`` |
Raymond Hettinger | 6e165b3 | 2010-11-27 09:31:37 +0000 | [diff] [blame] | 1170 | but works with sequences of unhashable objects as well. |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1171 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1172 | .. versionadded:: 3.2 |
| 1173 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1174 | |
Ezio Melotti | 22170ed | 2010-11-20 09:57:27 +0000 | [diff] [blame] | 1175 | .. _type-specific-methods: |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1176 | |
Ezio Melotti | 22170ed | 2010-11-20 09:57:27 +0000 | [diff] [blame] | 1177 | The :meth:`assertEqual` method dispatches the equality check for objects of |
| 1178 | the same type to different type-specific methods. These methods are already |
| 1179 | implemented for most of the built-in types, but it's also possible to |
| 1180 | register new methods using :meth:`addTypeEqualityFunc`: |
| 1181 | |
| 1182 | .. method:: addTypeEqualityFunc(typeobj, function) |
| 1183 | |
| 1184 | Registers a type-specific method called by :meth:`assertEqual` to check |
| 1185 | if two objects of exactly the same *typeobj* (not subclasses) compare |
| 1186 | equal. *function* must take two positional arguments and a third msg=None |
| 1187 | keyword argument just as :meth:`assertEqual` does. It must raise |
| 1188 | :data:`self.failureException(msg) <failureException>` when inequality |
| 1189 | between the first two parameters is detected -- possibly providing useful |
| 1190 | information and explaining the inequalities in details in the error |
| 1191 | message. |
| 1192 | |
| 1193 | .. versionadded:: 3.1 |
| 1194 | |
| 1195 | The list of type-specific methods automatically used by |
| 1196 | :meth:`~TestCase.assertEqual` are summarized in the following table. Note |
| 1197 | that it's usually not necessary to invoke these methods directly. |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1198 | |
| 1199 | +-----------------------------------------+-----------------------------+--------------+ |
| 1200 | | Method | Used to compare | New in | |
| 1201 | +=========================================+=============================+==============+ |
| 1202 | | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 | |
| 1203 | | <TestCase.assertMultiLineEqual>` | | | |
| 1204 | +-----------------------------------------+-----------------------------+--------------+ |
| 1205 | | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 | |
| 1206 | | <TestCase.assertSequenceEqual>` | | | |
| 1207 | +-----------------------------------------+-----------------------------+--------------+ |
| 1208 | | :meth:`assertListEqual(a, b) | lists | 3.1 | |
| 1209 | | <TestCase.assertListEqual>` | | | |
| 1210 | +-----------------------------------------+-----------------------------+--------------+ |
| 1211 | | :meth:`assertTupleEqual(a, b) | tuples | 3.1 | |
| 1212 | | <TestCase.assertTupleEqual>` | | | |
| 1213 | +-----------------------------------------+-----------------------------+--------------+ |
| 1214 | | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 | |
| 1215 | | <TestCase.assertSetEqual>` | | | |
| 1216 | +-----------------------------------------+-----------------------------+--------------+ |
| 1217 | | :meth:`assertDictEqual(a, b) | dicts | 3.1 | |
| 1218 | | <TestCase.assertDictEqual>` | | | |
| 1219 | +-----------------------------------------+-----------------------------+--------------+ |
| 1220 | |
| 1221 | |
| 1222 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1223 | .. method:: assertMultiLineEqual(first, second, msg=None) |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1224 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1225 | Test that the multiline string *first* is equal to the string *second*. |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1226 | When not equal a diff of the two strings highlighting the differences |
| 1227 | will be included in the error message. This method is used by default |
| 1228 | when comparing strings with :meth:`assertEqual`. |
| 1229 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1230 | .. versionadded:: 3.1 |
| 1231 | |
| 1232 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1233 | .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None) |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1234 | |
| 1235 | Tests that two sequences are equal. If a *seq_type* is supplied, both |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1236 | *first* and *second* must be instances of *seq_type* or a failure will |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1237 | be raised. If the sequences are different an error message is |
| 1238 | constructed that shows the difference between the two. |
| 1239 | |
Ezio Melotti | 22170ed | 2010-11-20 09:57:27 +0000 | [diff] [blame] | 1240 | This method is not called directly by :meth:`assertEqual`, but |
| 1241 | it's used to implement :meth:`assertListEqual` and |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1242 | :meth:`assertTupleEqual`. |
| 1243 | |
| 1244 | .. versionadded:: 3.1 |
| 1245 | |
| 1246 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1247 | .. method:: assertListEqual(first, second, msg=None) |
| 1248 | assertTupleEqual(first, second, msg=None) |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1249 | |
Ezio Melotti | 49ccd51 | 2012-08-29 17:50:42 +0300 | [diff] [blame] | 1250 | Tests that two lists or tuples are equal. If not, an error message is |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1251 | constructed that shows only the differences between the two. An error |
| 1252 | is also raised if either of the parameters are of the wrong type. |
| 1253 | These methods are used by default when comparing lists or tuples with |
| 1254 | :meth:`assertEqual`. |
| 1255 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1256 | .. versionadded:: 3.1 |
| 1257 | |
| 1258 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1259 | .. method:: assertSetEqual(first, second, msg=None) |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1260 | |
| 1261 | Tests that two sets are equal. If not, an error message is constructed |
| 1262 | that lists the differences between the sets. This method is used by |
| 1263 | default when comparing sets or frozensets with :meth:`assertEqual`. |
| 1264 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1265 | Fails if either of *first* or *second* does not have a :meth:`set.difference` |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1266 | method. |
| 1267 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1268 | .. versionadded:: 3.1 |
| 1269 | |
| 1270 | |
Michael Foord | e180d39 | 2011-01-28 19:51:48 +0000 | [diff] [blame] | 1271 | .. method:: assertDictEqual(first, second, msg=None) |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1272 | |
| 1273 | Test that two dictionaries are equal. If not, an error message is |
| 1274 | constructed that shows the differences in the dictionaries. This |
| 1275 | method will be used by default to compare dictionaries in |
| 1276 | calls to :meth:`assertEqual`. |
| 1277 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1278 | .. versionadded:: 3.1 |
| 1279 | |
| 1280 | |
| 1281 | |
Ezio Melotti | 22170ed | 2010-11-20 09:57:27 +0000 | [diff] [blame] | 1282 | .. _other-methods-and-attrs: |
| 1283 | |
Ezio Melotti | 4370b30 | 2010-11-03 20:39:14 +0000 | [diff] [blame] | 1284 | Finally the :class:`TestCase` provides the following methods and attributes: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1285 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1286 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1287 | .. method:: fail(msg=None) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1288 | |
Ezio Melotti | 75b2a5e | 2010-11-20 10:13:45 +0000 | [diff] [blame] | 1289 | Signals a test failure unconditionally, with *msg* or ``None`` for |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1290 | the error message. |
| 1291 | |
| 1292 | |
| 1293 | .. attribute:: failureException |
| 1294 | |
| 1295 | This class attribute gives the exception raised by the test method. If a |
| 1296 | test framework needs to use a specialized exception, possibly to carry |
| 1297 | additional information, it must subclass this exception in order to "play |
| 1298 | fair" with the framework. The initial value of this attribute is |
| 1299 | :exc:`AssertionError`. |
| 1300 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1301 | |
| 1302 | .. attribute:: longMessage |
| 1303 | |
Ezio Melotti | 75b2a5e | 2010-11-20 10:13:45 +0000 | [diff] [blame] | 1304 | If set to ``True`` then any explicit failure message you pass in to the |
Ezio Melotti | 22170ed | 2010-11-20 09:57:27 +0000 | [diff] [blame] | 1305 | :ref:`assert methods <assert-methods>` will be appended to the end of the |
| 1306 | normal failure message. The normal messages contain useful information |
| 1307 | about the objects involved, for example the message from assertEqual |
| 1308 | shows you the repr of the two unequal objects. Setting this attribute |
Ezio Melotti | 75b2a5e | 2010-11-20 10:13:45 +0000 | [diff] [blame] | 1309 | to ``True`` allows you to have a custom error message in addition to the |
Ezio Melotti | 22170ed | 2010-11-20 09:57:27 +0000 | [diff] [blame] | 1310 | normal one. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1311 | |
Michael Foord | 5074df6 | 2010-12-03 00:53:09 +0000 | [diff] [blame] | 1312 | This attribute defaults to ``True``. If set to False then a custom message |
| 1313 | passed to an assert method will silence the normal message. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1314 | |
| 1315 | The class setting can be overridden in individual tests by assigning an |
Ezio Melotti | 75b2a5e | 2010-11-20 10:13:45 +0000 | [diff] [blame] | 1316 | instance attribute to ``True`` or ``False`` before calling the assert methods. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1317 | |
Raymond Hettinger | 35a8836 | 2009-04-09 00:08:24 +0000 | [diff] [blame] | 1318 | .. versionadded:: 3.1 |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1319 | |
| 1320 | |
Michael Foord | 98b3e76 | 2010-06-05 21:59:55 +0000 | [diff] [blame] | 1321 | .. attribute:: maxDiff |
| 1322 | |
| 1323 | This attribute controls the maximum length of diffs output by assert |
| 1324 | methods that report diffs on failure. It defaults to 80*8 characters. |
| 1325 | Assert methods affected by this attribute are |
| 1326 | :meth:`assertSequenceEqual` (including all the sequence comparison |
| 1327 | methods that delegate to it), :meth:`assertDictEqual` and |
| 1328 | :meth:`assertMultiLineEqual`. |
| 1329 | |
| 1330 | Setting ``maxDiff`` to None means that there is no maximum length of |
| 1331 | diffs. |
| 1332 | |
| 1333 | .. versionadded:: 3.2 |
| 1334 | |
| 1335 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1336 | Testing frameworks can use the following methods to collect information on |
| 1337 | the test: |
| 1338 | |
| 1339 | |
| 1340 | .. method:: countTestCases() |
| 1341 | |
| 1342 | Return the number of tests represented by this test object. For |
| 1343 | :class:`TestCase` instances, this will always be ``1``. |
| 1344 | |
| 1345 | |
| 1346 | .. method:: defaultTestResult() |
| 1347 | |
| 1348 | Return an instance of the test result class that should be used for this |
| 1349 | test case class (if no other result instance is provided to the |
| 1350 | :meth:`run` method). |
| 1351 | |
| 1352 | For :class:`TestCase` instances, this will always be an instance of |
| 1353 | :class:`TestResult`; subclasses of :class:`TestCase` should override this |
| 1354 | as necessary. |
| 1355 | |
| 1356 | |
| 1357 | .. method:: id() |
| 1358 | |
| 1359 | Return a string identifying the specific test case. This is usually the |
| 1360 | full name of the test method, including the module and class name. |
| 1361 | |
| 1362 | |
| 1363 | .. method:: shortDescription() |
| 1364 | |
Ezio Melotti | 75b2a5e | 2010-11-20 10:13:45 +0000 | [diff] [blame] | 1365 | Returns a description of the test, or ``None`` if no description |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1366 | has been provided. The default implementation of this method |
| 1367 | returns the first line of the test method's docstring, if available, |
Ezio Melotti | 75b2a5e | 2010-11-20 10:13:45 +0000 | [diff] [blame] | 1368 | or ``None``. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1369 | |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 1370 | .. versionchanged:: 3.1 |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 1371 | In 3.1 this was changed to add the test name to the short description |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 1372 | even in the presence of a docstring. This caused compatibility issues |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 1373 | with unittest extensions and adding the test name was moved to the |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 1374 | :class:`TextTestResult` in Python 3.2. |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 1375 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1376 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1377 | .. method:: addCleanup(function, *args, **kwargs) |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1378 | |
| 1379 | Add a function to be called after :meth:`tearDown` to cleanup resources |
| 1380 | used during the test. Functions will be called in reverse order to the |
| 1381 | order they are added (LIFO). They are called with any arguments and |
| 1382 | keyword arguments passed into :meth:`addCleanup` when they are |
| 1383 | added. |
| 1384 | |
| 1385 | If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called, |
| 1386 | then any cleanup functions added will still be called. |
| 1387 | |
Ezio Melotti | 2d1e88a | 2011-03-10 12:16:35 +0200 | [diff] [blame] | 1388 | .. versionadded:: 3.1 |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1389 | |
| 1390 | |
| 1391 | .. method:: doCleanups() |
| 1392 | |
Barry Warsaw | 0c9fd63 | 2010-04-12 14:50:57 +0000 | [diff] [blame] | 1393 | This method is called unconditionally after :meth:`tearDown`, or |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1394 | after :meth:`setUp` if :meth:`setUp` raises an exception. |
| 1395 | |
| 1396 | It is responsible for calling all the cleanup functions added by |
| 1397 | :meth:`addCleanup`. If you need cleanup functions to be called |
| 1398 | *prior* to :meth:`tearDown` then you can call :meth:`doCleanups` |
| 1399 | yourself. |
| 1400 | |
| 1401 | :meth:`doCleanups` pops methods off the stack of cleanup |
| 1402 | functions one at a time, so it can be called at any time. |
| 1403 | |
Ezio Melotti | 2d1e88a | 2011-03-10 12:16:35 +0200 | [diff] [blame] | 1404 | .. versionadded:: 3.1 |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1405 | |
| 1406 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1407 | .. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1408 | |
| 1409 | This class implements the portion of the :class:`TestCase` interface which |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1410 | allows the test runner to drive the test, but does not provide the methods |
| 1411 | which test code can use to check and report errors. This is used to create |
| 1412 | test cases using legacy test code, allowing it to be integrated into a |
| 1413 | :mod:`unittest`-based test framework. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1414 | |
| 1415 | |
Ezio Melotti | 2baf1a6 | 2010-11-22 12:56:58 +0000 | [diff] [blame] | 1416 | .. _deprecated-aliases: |
| 1417 | |
Ezio Melotti | 8f2e07b | 2010-11-04 19:09:28 +0000 | [diff] [blame] | 1418 | Deprecated aliases |
| 1419 | ################## |
| 1420 | |
| 1421 | For historical reasons, some of the :class:`TestCase` methods had one or more |
| 1422 | aliases that are now deprecated. The following table lists the correct names |
| 1423 | along with their deprecated aliases: |
| 1424 | |
Ezio Melotti | 2baf1a6 | 2010-11-22 12:56:58 +0000 | [diff] [blame] | 1425 | ============================== ====================== ====================== |
| 1426 | Method Name Deprecated alias Deprecated alias |
| 1427 | ============================== ====================== ====================== |
| 1428 | :meth:`.assertEqual` failUnlessEqual assertEquals |
| 1429 | :meth:`.assertNotEqual` failIfEqual assertNotEquals |
| 1430 | :meth:`.assertTrue` failUnless assert\_ |
Ezio Melotti | 8f2e07b | 2010-11-04 19:09:28 +0000 | [diff] [blame] | 1431 | :meth:`.assertFalse` failIf |
| 1432 | :meth:`.assertRaises` failUnlessRaises |
Ezio Melotti | 2baf1a6 | 2010-11-22 12:56:58 +0000 | [diff] [blame] | 1433 | :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals |
| 1434 | :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1435 | :meth:`.assertRegex` assertRegexpMatches |
| 1436 | :meth:`.assertRaisesRegex` assertRaisesRegexp |
Ezio Melotti | 2baf1a6 | 2010-11-22 12:56:58 +0000 | [diff] [blame] | 1437 | ============================== ====================== ====================== |
Ezio Melotti | 8f2e07b | 2010-11-04 19:09:28 +0000 | [diff] [blame] | 1438 | |
Ezio Melotti | 361467e | 2011-04-03 17:37:58 +0300 | [diff] [blame] | 1439 | .. deprecated:: 3.1 |
Ezio Melotti | 2baf1a6 | 2010-11-22 12:56:58 +0000 | [diff] [blame] | 1440 | the fail* aliases listed in the second column. |
| 1441 | .. deprecated:: 3.2 |
| 1442 | the assert* aliases listed in the third column. |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1443 | .. deprecated:: 3.2 |
| 1444 | ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to |
| 1445 | :meth:`.assertRegex` and :meth:`.assertRaisesRegex` |
Ezio Melotti | 8f2e07b | 2010-11-04 19:09:28 +0000 | [diff] [blame] | 1446 | |
| 1447 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1448 | .. _testsuite-objects: |
| 1449 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1450 | Grouping tests |
| 1451 | ~~~~~~~~~~~~~~ |
| 1452 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1453 | .. class:: TestSuite(tests=()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1454 | |
| 1455 | This class represents an aggregation of individual tests cases and test suites. |
| 1456 | The class presents the interface needed by the test runner to allow it to be run |
| 1457 | as any other test case. Running a :class:`TestSuite` instance is the same as |
| 1458 | iterating over the suite, running each test individually. |
| 1459 | |
| 1460 | If *tests* is given, it must be an iterable of individual test cases or other |
| 1461 | test suites that will be used to build the suite initially. Additional methods |
| 1462 | are provided to add test cases and suites to the collection later on. |
| 1463 | |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame] | 1464 | :class:`TestSuite` objects behave much like :class:`TestCase` objects, except |
| 1465 | they do not actually implement a test. Instead, they are used to aggregate |
| 1466 | tests into groups of tests that should be run together. Some additional |
| 1467 | methods are available to add tests to :class:`TestSuite` instances: |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1468 | |
| 1469 | |
| 1470 | .. method:: TestSuite.addTest(test) |
| 1471 | |
| 1472 | Add a :class:`TestCase` or :class:`TestSuite` to the suite. |
| 1473 | |
| 1474 | |
| 1475 | .. method:: TestSuite.addTests(tests) |
| 1476 | |
| 1477 | Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite` |
| 1478 | instances to this test suite. |
| 1479 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1480 | This is equivalent to iterating over *tests*, calling :meth:`addTest` for |
| 1481 | each element. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1482 | |
| 1483 | :class:`TestSuite` shares the following methods with :class:`TestCase`: |
| 1484 | |
| 1485 | |
| 1486 | .. method:: run(result) |
| 1487 | |
| 1488 | Run the tests associated with this suite, collecting the result into the |
| 1489 | test result object passed as *result*. Note that unlike |
| 1490 | :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to |
| 1491 | be passed in. |
| 1492 | |
| 1493 | |
| 1494 | .. method:: debug() |
| 1495 | |
| 1496 | Run the tests associated with this suite without collecting the |
| 1497 | result. This allows exceptions raised by the test to be propagated to the |
| 1498 | caller and can be used to support running tests under a debugger. |
| 1499 | |
| 1500 | |
| 1501 | .. method:: countTestCases() |
| 1502 | |
| 1503 | Return the number of tests represented by this test object, including all |
| 1504 | individual tests and sub-suites. |
| 1505 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1506 | |
| 1507 | .. method:: __iter__() |
| 1508 | |
| 1509 | Tests grouped by a :class:`TestSuite` are always accessed by iteration. |
| 1510 | Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note |
Andrew Svetlov | eb97368 | 2013-08-28 21:28:38 +0300 | [diff] [blame] | 1511 | that this method may be called several times on a single suite (for |
| 1512 | example when counting tests or comparing for equality) so the tests |
| 1513 | returned by repeated iterations before :meth:`TestSuite.run` must be the |
| 1514 | same for each call iteration. After :meth:`TestSuite.run`, callers should |
| 1515 | not rely on the tests returned by this method unless the caller uses a |
| 1516 | subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve |
| 1517 | test references. |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1518 | |
Georg Brandl | 853947a | 2010-01-31 18:53:23 +0000 | [diff] [blame] | 1519 | .. versionchanged:: 3.2 |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1520 | In earlier versions the :class:`TestSuite` accessed tests directly rather |
| 1521 | than through iteration, so overriding :meth:`__iter__` wasn't sufficient |
| 1522 | for providing tests. |
| 1523 | |
Andrew Svetlov | eb97368 | 2013-08-28 21:28:38 +0300 | [diff] [blame] | 1524 | .. versionchanged:: 3.4 |
| 1525 | In earlier versions the :class:`TestSuite` held references to each |
| 1526 | :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore |
| 1527 | that behavior by overriding :meth:`TestSuite._removeTestAtIndex`. |
| 1528 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1529 | In the typical usage of a :class:`TestSuite` object, the :meth:`run` method |
| 1530 | is invoked by a :class:`TestRunner` rather than by the end-user test harness. |
| 1531 | |
| 1532 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1533 | Loading and running tests |
| 1534 | ~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1535 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1536 | .. class:: TestLoader() |
| 1537 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1538 | The :class:`TestLoader` class is used to create test suites from classes and |
| 1539 | modules. Normally, there is no need to create an instance of this class; the |
| 1540 | :mod:`unittest` module provides an instance that can be shared as |
Ezio Melotti | b8e336b | 2012-04-29 10:52:18 +0300 | [diff] [blame] | 1541 | :data:`unittest.defaultTestLoader`. Using a subclass or instance, however, |
| 1542 | allows customization of some configurable properties. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1543 | |
| 1544 | :class:`TestLoader` objects have the following methods: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1545 | |
Ezio Melotti | 9c02c2f | 2010-11-03 20:45:31 +0000 | [diff] [blame] | 1546 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1547 | .. method:: loadTestsFromTestCase(testCaseClass) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1548 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1549 | Return a suite of all tests cases contained in the :class:`TestCase`\ -derived |
| 1550 | :class:`testCaseClass`. |
| 1551 | |
Robert Collins | e02f6c2 | 2015-07-23 06:37:26 +1200 | [diff] [blame] | 1552 | A test case instance is created for each method named by |
| 1553 | :meth:`getTestCaseNames`. By default these are the method names |
| 1554 | beginning with ``test``. If :meth:`getTestCaseNames` returns no |
| 1555 | methods, but the :meth:`runTest` method is implemented, a single test |
| 1556 | case is created for that method instead. |
| 1557 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1558 | |
| 1559 | .. method:: loadTestsFromModule(module) |
| 1560 | |
| 1561 | Return a suite of all tests cases contained in the given module. This |
| 1562 | method searches *module* for classes derived from :class:`TestCase` and |
| 1563 | creates an instance of the class for each test method defined for the |
| 1564 | class. |
| 1565 | |
Georg Brandl | e720c0a | 2009-04-27 16:20:50 +0000 | [diff] [blame] | 1566 | .. note:: |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1567 | |
| 1568 | While using a hierarchy of :class:`TestCase`\ -derived classes can be |
| 1569 | convenient in sharing fixtures and helper functions, defining test |
| 1570 | methods on base classes that are not intended to be instantiated |
| 1571 | directly does not play well with this method. Doing so, however, can |
| 1572 | be useful when the fixtures are different and defined in subclasses. |
| 1573 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1574 | If a module provides a ``load_tests`` function it will be called to |
| 1575 | load the tests. This allows modules to customize test loading. |
| 1576 | This is the `load_tests protocol`_. |
| 1577 | |
Georg Brandl | 853947a | 2010-01-31 18:53:23 +0000 | [diff] [blame] | 1578 | .. versionchanged:: 3.2 |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1579 | Support for ``load_tests`` added. |
| 1580 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1581 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1582 | .. method:: loadTestsFromName(name, module=None) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1583 | |
| 1584 | Return a suite of all tests cases given a string specifier. |
| 1585 | |
| 1586 | The specifier *name* is a "dotted name" that may resolve either to a |
| 1587 | module, a test case class, a test method within a test case class, a |
| 1588 | :class:`TestSuite` instance, or a callable object which returns a |
| 1589 | :class:`TestCase` or :class:`TestSuite` instance. These checks are |
| 1590 | applied in the order listed here; that is, a method on a possible test |
| 1591 | case class will be picked up as "a test method within a test case class", |
| 1592 | rather than "a callable object". |
| 1593 | |
| 1594 | For example, if you have a module :mod:`SampleTests` containing a |
| 1595 | :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test |
| 1596 | methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1597 | specifier ``'SampleTests.SampleTestCase'`` would cause this method to |
| 1598 | return a suite which will run all three test methods. Using the specifier |
| 1599 | ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test |
| 1600 | suite which will run only the :meth:`test_two` test method. The specifier |
| 1601 | can refer to modules and packages which have not been imported; they will |
| 1602 | be imported as a side-effect. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1603 | |
| 1604 | The method optionally resolves *name* relative to the given *module*. |
| 1605 | |
| 1606 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1607 | .. method:: loadTestsFromNames(names, module=None) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1608 | |
| 1609 | Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather |
| 1610 | than a single name. The return value is a test suite which supports all |
| 1611 | the tests defined for each name. |
| 1612 | |
| 1613 | |
| 1614 | .. method:: getTestCaseNames(testCaseClass) |
| 1615 | |
| 1616 | Return a sorted sequence of method names found within *testCaseClass*; |
| 1617 | this should be a subclass of :class:`TestCase`. |
| 1618 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1619 | |
| 1620 | .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None) |
| 1621 | |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 1622 | Find all the test modules by recursing into subdirectories from the |
| 1623 | specified start directory, and return a TestSuite object containing them. |
| 1624 | Only test files that match *pattern* will be loaded. (Using shell style |
| 1625 | pattern matching.) Only module names that are importable (i.e. are valid |
| 1626 | Python identifiers) will be loaded. |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1627 | |
| 1628 | All test modules must be importable from the top level of the project. If |
| 1629 | the start directory is not the top level directory then the top level |
| 1630 | directory must be specified separately. |
| 1631 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1632 | If importing a module fails, for example due to a syntax error, then this |
Ezio Melotti | eae2b38 | 2013-03-01 14:47:50 +0200 | [diff] [blame] | 1633 | will be recorded as a single error and discovery will continue. If the |
Ezio Melotti | 67ddcca | 2013-03-27 20:13:59 +0200 | [diff] [blame] | 1634 | import failure is due to :exc:`SkipTest` being raised, it will be recorded |
Ezio Melotti | eae2b38 | 2013-03-01 14:47:50 +0200 | [diff] [blame] | 1635 | as a skip instead of an error. |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1636 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1637 | If a test package name (directory with :file:`__init__.py`) matches the |
| 1638 | pattern then the package will be checked for a ``load_tests`` |
| 1639 | function. If this exists then it will be called with *loader*, *tests*, |
| 1640 | *pattern*. |
| 1641 | |
Georg Brandl | 3f1ef9e | 2014-10-02 12:37:50 +0200 | [diff] [blame] | 1642 | If ``load_tests`` exists then discovery does *not* recurse into the package, |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1643 | ``load_tests`` is responsible for loading all tests in the package. |
| 1644 | |
| 1645 | The pattern is deliberately not stored as a loader attribute so that |
| 1646 | packages can continue discovery themselves. *top_level_dir* is stored so |
| 1647 | ``load_tests`` does not need to pass this argument in to |
| 1648 | ``loader.discover()``. |
| 1649 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 1650 | *start_dir* can be a dotted module name as well as a directory. |
| 1651 | |
Georg Brandl | 853947a | 2010-01-31 18:53:23 +0000 | [diff] [blame] | 1652 | .. versionadded:: 3.2 |
| 1653 | |
Ezio Melotti | eae2b38 | 2013-03-01 14:47:50 +0200 | [diff] [blame] | 1654 | .. versionchanged:: 3.4 |
Ezio Melotti | 67ddcca | 2013-03-27 20:13:59 +0200 | [diff] [blame] | 1655 | Modules that raise :exc:`SkipTest` on import are recorded as skips, |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 1656 | not errors. |
| 1657 | Discovery works for :term:`namespace packages <namespace package>`. |
| 1658 | Paths are sorted before being imported so that execution order is |
| 1659 | the same even if the underlying file system's ordering is not |
| 1660 | dependent on file name. |
Michael Foord | 80cbc9e | 2013-03-18 17:50:12 -0700 | [diff] [blame] | 1661 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1662 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1663 | The following attributes of a :class:`TestLoader` can be configured either by |
| 1664 | subclassing or assignment on an instance: |
| 1665 | |
| 1666 | |
| 1667 | .. attribute:: testMethodPrefix |
| 1668 | |
| 1669 | String giving the prefix of method names which will be interpreted as test |
| 1670 | methods. The default value is ``'test'``. |
| 1671 | |
| 1672 | This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` |
| 1673 | methods. |
| 1674 | |
| 1675 | |
| 1676 | .. attribute:: sortTestMethodsUsing |
| 1677 | |
| 1678 | Function to be used to compare method names when sorting them in |
| 1679 | :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. |
| 1680 | |
| 1681 | |
| 1682 | .. attribute:: suiteClass |
| 1683 | |
| 1684 | Callable object that constructs a test suite from a list of tests. No |
| 1685 | methods on the resulting object are needed. The default value is the |
| 1686 | :class:`TestSuite` class. |
| 1687 | |
| 1688 | This affects all the :meth:`loadTestsFrom\*` methods. |
| 1689 | |
| 1690 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1691 | .. class:: TestResult |
| 1692 | |
| 1693 | This class is used to compile information about which tests have succeeded |
| 1694 | and which have failed. |
| 1695 | |
| 1696 | A :class:`TestResult` object stores the results of a set of tests. The |
| 1697 | :class:`TestCase` and :class:`TestSuite` classes ensure that results are |
| 1698 | properly recorded; test authors do not need to worry about recording the |
| 1699 | outcome of tests. |
| 1700 | |
| 1701 | Testing frameworks built on top of :mod:`unittest` may want access to the |
| 1702 | :class:`TestResult` object generated by running a set of tests for reporting |
| 1703 | purposes; a :class:`TestResult` instance is returned by the |
| 1704 | :meth:`TestRunner.run` method for this purpose. |
| 1705 | |
| 1706 | :class:`TestResult` instances have the following attributes that will be of |
| 1707 | interest when inspecting the results of running a set of tests: |
| 1708 | |
| 1709 | |
| 1710 | .. attribute:: errors |
| 1711 | |
| 1712 | A list containing 2-tuples of :class:`TestCase` instances and strings |
| 1713 | holding formatted tracebacks. Each tuple represents a test which raised an |
| 1714 | unexpected exception. |
| 1715 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1716 | .. attribute:: failures |
| 1717 | |
| 1718 | A list containing 2-tuples of :class:`TestCase` instances and strings |
| 1719 | holding formatted tracebacks. Each tuple represents a test where a failure |
Ezio Melotti | e220236 | 2013-09-07 15:19:30 +0300 | [diff] [blame] | 1720 | was explicitly signalled using the :meth:`TestCase.assert\*` methods. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1721 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1722 | .. attribute:: skipped |
| 1723 | |
| 1724 | A list containing 2-tuples of :class:`TestCase` instances and strings |
| 1725 | holding the reason for skipping the test. |
| 1726 | |
Benjamin Peterson | 70e32c8 | 2009-03-24 01:00:11 +0000 | [diff] [blame] | 1727 | .. versionadded:: 3.1 |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1728 | |
| 1729 | .. attribute:: expectedFailures |
| 1730 | |
Georg Brandl | 6faee4e | 2010-09-21 14:48:28 +0000 | [diff] [blame] | 1731 | A list containing 2-tuples of :class:`TestCase` instances and strings |
| 1732 | holding formatted tracebacks. Each tuple represents an expected failure |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1733 | of the test case. |
| 1734 | |
| 1735 | .. attribute:: unexpectedSuccesses |
| 1736 | |
| 1737 | A list containing :class:`TestCase` instances that were marked as expected |
| 1738 | failures, but succeeded. |
| 1739 | |
| 1740 | .. attribute:: shouldStop |
| 1741 | |
| 1742 | Set to ``True`` when the execution of tests should stop by :meth:`stop`. |
| 1743 | |
| 1744 | |
| 1745 | .. attribute:: testsRun |
| 1746 | |
| 1747 | The total number of tests run so far. |
| 1748 | |
| 1749 | |
Georg Brandl | 1203720 | 2010-12-02 22:35:25 +0000 | [diff] [blame] | 1750 | .. attribute:: buffer |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 1751 | |
| 1752 | If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between |
| 1753 | :meth:`startTest` and :meth:`stopTest` being called. Collected output will |
| 1754 | only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test |
| 1755 | fails or errors. Any output is also attached to the failure / error message. |
| 1756 | |
Ezio Melotti | 7afd3f5 | 2010-04-20 09:32:54 +0000 | [diff] [blame] | 1757 | .. versionadded:: 3.2 |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 1758 | |
| 1759 | |
| 1760 | .. attribute:: failfast |
| 1761 | |
| 1762 | If set to true :meth:`stop` will be called on the first failure or error, |
| 1763 | halting the test run. |
| 1764 | |
Ezio Melotti | 7afd3f5 | 2010-04-20 09:32:54 +0000 | [diff] [blame] | 1765 | .. versionadded:: 3.2 |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 1766 | |
| 1767 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1768 | .. method:: wasSuccessful() |
| 1769 | |
Ezio Melotti | 75b2a5e | 2010-11-20 10:13:45 +0000 | [diff] [blame] | 1770 | Return ``True`` if all tests run so far have passed, otherwise returns |
| 1771 | ``False``. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1772 | |
Gregory P. Smith | 5a6d4bf | 2014-01-20 01:11:18 -0800 | [diff] [blame] | 1773 | .. versionchanged:: 3.4 |
| 1774 | Returns ``False`` if there were any :attr:`unexpectedSuccesses` |
| 1775 | from tests marked with the :func:`expectedFailure` decorator. |
| 1776 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1777 | |
| 1778 | .. method:: stop() |
| 1779 | |
| 1780 | This method can be called to signal that the set of tests being run should |
Ezio Melotti | 75b2a5e | 2010-11-20 10:13:45 +0000 | [diff] [blame] | 1781 | be aborted by setting the :attr:`shouldStop` attribute to ``True``. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1782 | :class:`TestRunner` objects should respect this flag and return without |
| 1783 | running any additional tests. |
| 1784 | |
| 1785 | For example, this feature is used by the :class:`TextTestRunner` class to |
| 1786 | stop the test framework when the user signals an interrupt from the |
| 1787 | keyboard. Interactive tools which provide :class:`TestRunner` |
| 1788 | implementations can use this in a similar manner. |
| 1789 | |
| 1790 | The following methods of the :class:`TestResult` class are used to maintain |
| 1791 | the internal data structures, and may be extended in subclasses to support |
| 1792 | additional reporting requirements. This is particularly useful in building |
| 1793 | tools which support interactive reporting while tests are being run. |
| 1794 | |
| 1795 | |
| 1796 | .. method:: startTest(test) |
| 1797 | |
| 1798 | Called when the test case *test* is about to be run. |
| 1799 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1800 | .. method:: stopTest(test) |
| 1801 | |
| 1802 | Called after the test case *test* has been executed, regardless of the |
| 1803 | outcome. |
| 1804 | |
Terry Jan Reedy | f98021c | 2014-04-11 14:11:11 -0400 | [diff] [blame] | 1805 | .. method:: startTestRun() |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1806 | |
| 1807 | Called once before any tests are executed. |
| 1808 | |
Ezio Melotti | 2d1e88a | 2011-03-10 12:16:35 +0200 | [diff] [blame] | 1809 | .. versionadded:: 3.1 |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1810 | |
| 1811 | |
Terry Jan Reedy | f98021c | 2014-04-11 14:11:11 -0400 | [diff] [blame] | 1812 | .. method:: stopTestRun() |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1813 | |
Ezio Melotti | 176d6c4 | 2010-01-27 20:58:07 +0000 | [diff] [blame] | 1814 | Called once after all tests are executed. |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1815 | |
Ezio Melotti | 2d1e88a | 2011-03-10 12:16:35 +0200 | [diff] [blame] | 1816 | .. versionadded:: 3.1 |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1817 | |
| 1818 | |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1819 | .. method:: addError(test, err) |
| 1820 | |
Ezio Melotti | e64a91a | 2013-09-07 15:23:36 +0300 | [diff] [blame] | 1821 | Called when the test case *test* raises an unexpected exception. *err* is a |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1822 | tuple of the form returned by :func:`sys.exc_info`: ``(type, value, |
| 1823 | traceback)``. |
| 1824 | |
| 1825 | The default implementation appends a tuple ``(test, formatted_err)`` to |
| 1826 | the instance's :attr:`errors` attribute, where *formatted_err* is a |
| 1827 | formatted traceback derived from *err*. |
| 1828 | |
| 1829 | |
| 1830 | .. method:: addFailure(test, err) |
| 1831 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1832 | Called when the test case *test* signals a failure. *err* is a tuple of |
| 1833 | the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``. |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 1834 | |
| 1835 | The default implementation appends a tuple ``(test, formatted_err)`` to |
| 1836 | the instance's :attr:`failures` attribute, where *formatted_err* is a |
| 1837 | formatted traceback derived from *err*. |
| 1838 | |
| 1839 | |
| 1840 | .. method:: addSuccess(test) |
| 1841 | |
| 1842 | Called when the test case *test* succeeds. |
| 1843 | |
| 1844 | The default implementation does nothing. |
| 1845 | |
| 1846 | |
| 1847 | .. method:: addSkip(test, reason) |
| 1848 | |
| 1849 | Called when the test case *test* is skipped. *reason* is the reason the |
| 1850 | test gave for skipping. |
| 1851 | |
| 1852 | The default implementation appends a tuple ``(test, reason)`` to the |
| 1853 | instance's :attr:`skipped` attribute. |
| 1854 | |
| 1855 | |
| 1856 | .. method:: addExpectedFailure(test, err) |
| 1857 | |
| 1858 | Called when the test case *test* fails, but was marked with the |
| 1859 | :func:`expectedFailure` decorator. |
| 1860 | |
| 1861 | The default implementation appends a tuple ``(test, formatted_err)`` to |
| 1862 | the instance's :attr:`expectedFailures` attribute, where *formatted_err* |
| 1863 | is a formatted traceback derived from *err*. |
| 1864 | |
| 1865 | |
| 1866 | .. method:: addUnexpectedSuccess(test) |
| 1867 | |
| 1868 | Called when the test case *test* was marked with the |
| 1869 | :func:`expectedFailure` decorator, but succeeded. |
| 1870 | |
| 1871 | The default implementation appends the test to the instance's |
| 1872 | :attr:`unexpectedSuccesses` attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1873 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 1874 | |
Antoine Pitrou | c9b3ef2 | 2013-03-20 20:16:47 +0100 | [diff] [blame] | 1875 | .. method:: addSubTest(test, subtest, outcome) |
| 1876 | |
| 1877 | Called when a subtest finishes. *test* is the test case |
| 1878 | corresponding to the test method. *subtest* is a custom |
| 1879 | :class:`TestCase` instance describing the subtest. |
| 1880 | |
| 1881 | If *outcome* is :const:`None`, the subtest succeeded. Otherwise, |
| 1882 | it failed with an exception where *outcome* is a tuple of the form |
| 1883 | returned by :func:`sys.exc_info`: ``(type, value, traceback)``. |
| 1884 | |
| 1885 | The default implementation does nothing when the outcome is a |
| 1886 | success, and records subtest failures as normal failures. |
| 1887 | |
| 1888 | .. versionadded:: 3.4 |
| 1889 | |
| 1890 | |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 1891 | .. class:: TextTestResult(stream, descriptions, verbosity) |
| 1892 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 1893 | A concrete implementation of :class:`TestResult` used by the |
| 1894 | :class:`TextTestRunner`. |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 1895 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 1896 | .. versionadded:: 3.2 |
| 1897 | This class was previously named ``_TextTestResult``. The old name still |
| 1898 | exists as an alias but is deprecated. |
| 1899 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1900 | |
| 1901 | .. data:: defaultTestLoader |
| 1902 | |
| 1903 | Instance of the :class:`TestLoader` class intended to be shared. If no |
| 1904 | customization of the :class:`TestLoader` is needed, this instance can be used |
| 1905 | instead of repeatedly creating new instances. |
| 1906 | |
| 1907 | |
Ezio Melotti | 9c939bc | 2013-05-07 09:46:30 +0300 | [diff] [blame] | 1908 | .. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \ |
| 1909 | buffer=False, resultclass=None, warnings=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1910 | |
Michael Foord | d218e95 | 2011-01-03 12:55:11 +0000 | [diff] [blame] | 1911 | A basic test runner implementation that outputs results to a stream. If *stream* |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 1912 | is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1913 | has a few configurable parameters, but is essentially very simple. Graphical |
| 1914 | applications which run test suites should provide alternate implementations. |
| 1915 | |
Ezio Melotti | 6090187 | 2010-12-01 00:56:10 +0000 | [diff] [blame] | 1916 | By default this runner shows :exc:`DeprecationWarning`, |
Senthil Kumaran | 409ea5d | 2014-02-08 14:28:03 -0800 | [diff] [blame] | 1917 | :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and |
Larry Hastings | ad88d7a | 2014-02-10 04:26:10 -0800 | [diff] [blame] | 1918 | :exc:`ImportWarning` even if they are :ref:`ignored by default |
| 1919 | <warning-ignored>`. Deprecation warnings caused by :ref:`deprecated unittest |
| 1920 | methods <deprecated-aliases>` are also special-cased and, when the warning |
| 1921 | filters are ``'default'`` or ``'always'``, they will appear only once |
| 1922 | per-module, in order to avoid too many warning messages. This behavior can |
| 1923 | be overridden using the :option:`-Wd` or :option:`-Wa` options and leaving |
| 1924 | *warnings* to ``None``. |
Ezio Melotti | 6090187 | 2010-12-01 00:56:10 +0000 | [diff] [blame] | 1925 | |
Michael Foord | d218e95 | 2011-01-03 12:55:11 +0000 | [diff] [blame] | 1926 | .. versionchanged:: 3.2 |
| 1927 | Added the ``warnings`` argument. |
| 1928 | |
| 1929 | .. versionchanged:: 3.2 |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 1930 | The default stream is set to :data:`sys.stderr` at instantiation time rather |
Michael Foord | d218e95 | 2011-01-03 12:55:11 +0000 | [diff] [blame] | 1931 | than import time. |
| 1932 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1933 | .. method:: _makeResult() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1934 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1935 | This method returns the instance of ``TestResult`` used by :meth:`run`. |
| 1936 | It is not intended to be called directly, but can be overridden in |
| 1937 | subclasses to provide a custom ``TestResult``. |
| 1938 | |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 1939 | ``_makeResult()`` instantiates the class or callable passed in the |
| 1940 | ``TextTestRunner`` constructor as the ``resultclass`` argument. It |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 1941 | defaults to :class:`TextTestResult` if no ``resultclass`` is provided. |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 1942 | The result class is instantiated with the following arguments:: |
| 1943 | |
| 1944 | stream, descriptions, verbosity |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1945 | |
Michael Foord | 4d1639f | 2013-12-29 23:38:55 +0000 | [diff] [blame] | 1946 | .. method:: run(test) |
| 1947 | |
| 1948 | This method is the main public interface to the `TextTestRunner`. This |
| 1949 | method takes a :class:`TestSuite` or :class:`TestCase` instance. A |
| 1950 | :class:`TestResult` is created by calling |
| 1951 | :func:`_makeResult` and the test(s) are run and the |
| 1952 | results printed to stdout. |
| 1953 | |
Ezio Melotti | 6090187 | 2010-12-01 00:56:10 +0000 | [diff] [blame] | 1954 | |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 1955 | .. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \ |
Ezio Melotti | 40dcb1d | 2011-03-10 13:46:50 +0200 | [diff] [blame] | 1956 | testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \ |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 1957 | failfast=None, catchbreak=None, buffer=None, warnings=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1958 | |
Ezio Melotti | 3d6d7a5 | 2012-04-30 19:10:28 +0300 | [diff] [blame] | 1959 | A command-line program that loads a set of tests from *module* and runs them; |
| 1960 | this is primarily for making test modules conveniently executable. |
| 1961 | The simplest use for this function is to include the following line at the |
| 1962 | end of a test script:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1963 | |
| 1964 | if __name__ == '__main__': |
| 1965 | unittest.main() |
| 1966 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 1967 | You can run tests with more detailed information by passing in the verbosity |
| 1968 | argument:: |
| 1969 | |
| 1970 | if __name__ == '__main__': |
| 1971 | unittest.main(verbosity=2) |
| 1972 | |
R David Murray | 6e731b0 | 2014-01-02 13:43:02 -0500 | [diff] [blame] | 1973 | The *defaultTest* argument is either the name of a single test or an |
| 1974 | iterable of test names to run if no test names are specified via *argv*. If |
| 1975 | not specified or ``None`` and no test names are provided via *argv*, all |
| 1976 | tests found in *module* are run. |
R David Murray | 12e930f | 2014-01-02 13:37:26 -0500 | [diff] [blame] | 1977 | |
Ezio Melotti | 3d6d7a5 | 2012-04-30 19:10:28 +0300 | [diff] [blame] | 1978 | The *argv* argument can be a list of options passed to the program, with the |
| 1979 | first element being the program name. If not specified or ``None``, |
| 1980 | the values of :data:`sys.argv` are used. |
| 1981 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1982 | The *testRunner* argument can either be a test runner class or an already |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1983 | created instance of it. By default ``main`` calls :func:`sys.exit` with |
| 1984 | an exit code indicating success or failure of the tests run. |
| 1985 | |
Ezio Melotti | 3d6d7a5 | 2012-04-30 19:10:28 +0300 | [diff] [blame] | 1986 | The *testLoader* argument has to be a :class:`TestLoader` instance, |
| 1987 | and defaults to :data:`defaultTestLoader`. |
| 1988 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1989 | ``main`` supports being used from the interactive interpreter by passing in the |
| 1990 | argument ``exit=False``. This displays the result on standard output without |
| 1991 | calling :func:`sys.exit`:: |
| 1992 | |
| 1993 | >>> from unittest import main |
| 1994 | >>> main(module='test_module', exit=False) |
| 1995 | |
Ezio Melotti | 3d6d7a5 | 2012-04-30 19:10:28 +0300 | [diff] [blame] | 1996 | The *failfast*, *catchbreak* and *buffer* parameters have the same |
Éric Araujo | 76338ec | 2010-11-26 23:46:18 +0000 | [diff] [blame] | 1997 | effect as the same-name `command-line options`_. |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 1998 | |
Ezio Melotti | 6090187 | 2010-12-01 00:56:10 +0000 | [diff] [blame] | 1999 | The *warning* argument specifies the :ref:`warning filter <warning-filter>` |
| 2000 | that should be used while running the tests. If it's not specified, it will |
| 2001 | remain ``None`` if a :option:`-W` option is passed to :program:`python`, |
| 2002 | otherwise it will be set to ``'default'``. |
| 2003 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2004 | Calling ``main`` actually returns an instance of the ``TestProgram`` class. |
| 2005 | This stores the result of the tests run as the ``result`` attribute. |
| 2006 | |
Éric Araujo | 971dc01 | 2010-12-16 03:13:05 +0000 | [diff] [blame] | 2007 | .. versionchanged:: 3.1 |
Ezio Melotti | 3d6d7a5 | 2012-04-30 19:10:28 +0300 | [diff] [blame] | 2008 | The *exit* parameter was added. |
Éric Araujo | 971dc01 | 2010-12-16 03:13:05 +0000 | [diff] [blame] | 2009 | |
Georg Brandl | 853947a | 2010-01-31 18:53:23 +0000 | [diff] [blame] | 2010 | .. versionchanged:: 3.2 |
Ezio Melotti | 3d6d7a5 | 2012-04-30 19:10:28 +0300 | [diff] [blame] | 2011 | The *verbosity*, *failfast*, *catchbreak*, *buffer* |
| 2012 | and *warnings* parameters were added. |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 2013 | |
Chris Jerdonek | ccbc26a | 2013-02-23 15:44:46 -0800 | [diff] [blame] | 2014 | .. versionchanged:: 3.4 |
| 2015 | The *defaultTest* parameter was changed to also accept an iterable of |
| 2016 | test names. |
| 2017 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 2018 | |
| 2019 | load_tests Protocol |
| 2020 | ################### |
| 2021 | |
Georg Brandl | 853947a | 2010-01-31 18:53:23 +0000 | [diff] [blame] | 2022 | .. versionadded:: 3.2 |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 2023 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 2024 | Modules or packages can customize how tests are loaded from them during normal |
| 2025 | test runs or test discovery by implementing a function called ``load_tests``. |
| 2026 | |
| 2027 | If a test module defines ``load_tests`` it will be called by |
| 2028 | :meth:`TestLoader.loadTestsFromModule` with the following arguments:: |
| 2029 | |
| 2030 | load_tests(loader, standard_tests, None) |
| 2031 | |
| 2032 | It should return a :class:`TestSuite`. |
| 2033 | |
| 2034 | *loader* is the instance of :class:`TestLoader` doing the loading. |
| 2035 | *standard_tests* are the tests that would be loaded by default from the |
| 2036 | module. It is common for test modules to only want to add or remove tests |
| 2037 | from the standard set of tests. |
| 2038 | The third argument is used when loading packages as part of test discovery. |
| 2039 | |
| 2040 | A typical ``load_tests`` function that loads tests from a specific set of |
| 2041 | :class:`TestCase` classes may look like:: |
| 2042 | |
| 2043 | test_cases = (TestCase1, TestCase2, TestCase3) |
| 2044 | |
| 2045 | def load_tests(loader, tests, pattern): |
| 2046 | suite = TestSuite() |
| 2047 | for test_class in test_cases: |
| 2048 | tests = loader.loadTestsFromTestCase(test_class) |
| 2049 | suite.addTests(tests) |
| 2050 | return suite |
| 2051 | |
| 2052 | If discovery is started, either from the command line or by calling |
| 2053 | :meth:`TestLoader.discover`, with a pattern that matches a package |
| 2054 | name then the package :file:`__init__.py` will be checked for ``load_tests``. |
| 2055 | |
| 2056 | .. note:: |
| 2057 | |
Ezio Melotti | 4d6cb0f | 2013-02-28 08:28:11 +0200 | [diff] [blame] | 2058 | The default pattern is ``'test*.py'``. This matches all Python files |
| 2059 | that start with ``'test'`` but *won't* match any test directories. |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 2060 | |
Ezio Melotti | 4d6cb0f | 2013-02-28 08:28:11 +0200 | [diff] [blame] | 2061 | A pattern like ``'test*'`` will match test packages as well as |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 2062 | modules. |
| 2063 | |
| 2064 | If the package :file:`__init__.py` defines ``load_tests`` then it will be |
| 2065 | called and discovery not continued into the package. ``load_tests`` |
| 2066 | is called with the following arguments:: |
| 2067 | |
| 2068 | load_tests(loader, standard_tests, pattern) |
| 2069 | |
| 2070 | This should return a :class:`TestSuite` representing all the tests |
| 2071 | from the package. (``standard_tests`` will only contain tests |
| 2072 | collected from :file:`__init__.py`.) |
| 2073 | |
| 2074 | Because the pattern is passed into ``load_tests`` the package is free to |
| 2075 | continue (and potentially modify) test discovery. A 'do nothing' |
| 2076 | ``load_tests`` function for a test package would look like:: |
| 2077 | |
| 2078 | def load_tests(loader, standard_tests, pattern): |
| 2079 | # top level directory cached on loader instance |
| 2080 | this_dir = os.path.dirname(__file__) |
| 2081 | package_tests = loader.discover(start_dir=this_dir, pattern=pattern) |
| 2082 | standard_tests.addTests(package_tests) |
| 2083 | return standard_tests |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 2084 | |
| 2085 | |
| 2086 | Class and Module Fixtures |
| 2087 | ------------------------- |
| 2088 | |
| 2089 | Class and module level fixtures are implemented in :class:`TestSuite`. When |
| 2090 | the test suite encounters a test from a new class then :meth:`tearDownClass` |
| 2091 | from the previous class (if there is one) is called, followed by |
| 2092 | :meth:`setUpClass` from the new class. |
| 2093 | |
| 2094 | Similarly if a test is from a different module from the previous test then |
| 2095 | ``tearDownModule`` from the previous module is run, followed by |
| 2096 | ``setUpModule`` from the new module. |
| 2097 | |
| 2098 | After all the tests have run the final ``tearDownClass`` and |
| 2099 | ``tearDownModule`` are run. |
| 2100 | |
| 2101 | Note that shared fixtures do not play well with [potential] features like test |
| 2102 | parallelization and they break test isolation. They should be used with care. |
| 2103 | |
| 2104 | The default ordering of tests created by the unittest test loaders is to group |
| 2105 | all tests from the same modules and classes together. This will lead to |
| 2106 | ``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and |
| 2107 | module. If you randomize the order, so that tests from different modules and |
| 2108 | classes are adjacent to each other, then these shared fixture functions may be |
| 2109 | called multiple times in a single test run. |
| 2110 | |
| 2111 | Shared fixtures are not intended to work with suites with non-standard |
| 2112 | ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to |
| 2113 | support shared fixtures. |
| 2114 | |
| 2115 | If there are any exceptions raised during one of the shared fixture functions |
| 2116 | the test is reported as an error. Because there is no corresponding test |
| 2117 | instance an ``_ErrorHolder`` object (that has the same interface as a |
| 2118 | :class:`TestCase`) is created to represent the error. If you are just using |
| 2119 | the standard unittest test runner then this detail doesn't matter, but if you |
| 2120 | are a framework author it may be relevant. |
| 2121 | |
| 2122 | |
| 2123 | setUpClass and tearDownClass |
| 2124 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2125 | |
| 2126 | These must be implemented as class methods:: |
| 2127 | |
| 2128 | import unittest |
| 2129 | |
| 2130 | class Test(unittest.TestCase): |
| 2131 | @classmethod |
| 2132 | def setUpClass(cls): |
| 2133 | cls._connection = createExpensiveConnectionObject() |
| 2134 | |
| 2135 | @classmethod |
| 2136 | def tearDownClass(cls): |
| 2137 | cls._connection.destroy() |
| 2138 | |
| 2139 | If you want the ``setUpClass`` and ``tearDownClass`` on base classes called |
| 2140 | then you must call up to them yourself. The implementations in |
| 2141 | :class:`TestCase` are empty. |
| 2142 | |
| 2143 | If an exception is raised during a ``setUpClass`` then the tests in the class |
| 2144 | are not run and the ``tearDownClass`` is not run. Skipped classes will not |
Michael Foord | 98b3e76 | 2010-06-05 21:59:55 +0000 | [diff] [blame] | 2145 | have ``setUpClass`` or ``tearDownClass`` run. If the exception is a |
Ezio Melotti | 265281a | 2013-03-27 20:11:55 +0200 | [diff] [blame] | 2146 | :exc:`SkipTest` exception then the class will be reported as having been skipped |
Michael Foord | 98b3e76 | 2010-06-05 21:59:55 +0000 | [diff] [blame] | 2147 | instead of as an error. |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 2148 | |
| 2149 | |
| 2150 | setUpModule and tearDownModule |
| 2151 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2152 | |
| 2153 | These should be implemented as functions:: |
| 2154 | |
| 2155 | def setUpModule(): |
| 2156 | createConnection() |
| 2157 | |
| 2158 | def tearDownModule(): |
| 2159 | closeConnection() |
| 2160 | |
| 2161 | If an exception is raised in a ``setUpModule`` then none of the tests in the |
Michael Foord | 98b3e76 | 2010-06-05 21:59:55 +0000 | [diff] [blame] | 2162 | module will be run and the ``tearDownModule`` will not be run. If the exception is a |
Ezio Melotti | 265281a | 2013-03-27 20:11:55 +0200 | [diff] [blame] | 2163 | :exc:`SkipTest` exception then the module will be reported as having been skipped |
Michael Foord | 98b3e76 | 2010-06-05 21:59:55 +0000 | [diff] [blame] | 2164 | instead of as an error. |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 2165 | |
| 2166 | |
| 2167 | Signal Handling |
| 2168 | --------------- |
| 2169 | |
Georg Brandl | 419e3de | 2010-12-01 15:44:25 +0000 | [diff] [blame] | 2170 | .. versionadded:: 3.2 |
| 2171 | |
Éric Araujo | 8acb67c | 2010-11-26 23:31:07 +0000 | [diff] [blame] | 2172 | The :option:`-c/--catch <unittest -c>` command-line option to unittest, |
Éric Araujo | 76338ec | 2010-11-26 23:46:18 +0000 | [diff] [blame] | 2173 | along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide |
| 2174 | more friendly handling of control-C during a test run. With catch break |
| 2175 | behavior enabled control-C will allow the currently running test to complete, |
| 2176 | and the test run will then end and report all the results so far. A second |
| 2177 | control-c will raise a :exc:`KeyboardInterrupt` in the usual way. |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 2178 | |
Michael Foord | de4ceab | 2010-04-25 19:53:49 +0000 | [diff] [blame] | 2179 | The control-c handling signal handler attempts to remain compatible with code or |
| 2180 | tests that install their own :const:`signal.SIGINT` handler. If the ``unittest`` |
| 2181 | handler is called but *isn't* the installed :const:`signal.SIGINT` handler, |
| 2182 | i.e. it has been replaced by the system under test and delegated to, then it |
| 2183 | calls the default handler. This will normally be the expected behavior by code |
| 2184 | that replaces an installed handler and delegates to it. For individual tests |
| 2185 | that need ``unittest`` control-c handling disabled the :func:`removeHandler` |
| 2186 | decorator can be used. |
| 2187 | |
| 2188 | There are a few utility functions for framework authors to enable control-c |
| 2189 | handling functionality within test frameworks. |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 2190 | |
| 2191 | .. function:: installHandler() |
| 2192 | |
| 2193 | Install the control-c handler. When a :const:`signal.SIGINT` is received |
| 2194 | (usually in response to the user pressing control-c) all registered results |
| 2195 | have :meth:`~TestResult.stop` called. |
| 2196 | |
Michael Foord | 469b1f0 | 2010-04-26 23:41:26 +0000 | [diff] [blame] | 2197 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 2198 | .. function:: registerResult(result) |
| 2199 | |
| 2200 | Register a :class:`TestResult` object for control-c handling. Registering a |
| 2201 | result stores a weak reference to it, so it doesn't prevent the result from |
| 2202 | being garbage collected. |
| 2203 | |
Michael Foord | de4ceab | 2010-04-25 19:53:49 +0000 | [diff] [blame] | 2204 | Registering a :class:`TestResult` object has no side-effects if control-c |
| 2205 | handling is not enabled, so test frameworks can unconditionally register |
| 2206 | all results they create independently of whether or not handling is enabled. |
| 2207 | |
Michael Foord | 469b1f0 | 2010-04-26 23:41:26 +0000 | [diff] [blame] | 2208 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 2209 | .. function:: removeResult(result) |
| 2210 | |
| 2211 | Remove a registered result. Once a result has been removed then |
| 2212 | :meth:`~TestResult.stop` will no longer be called on that result object in |
| 2213 | response to a control-c. |
| 2214 | |
Michael Foord | 469b1f0 | 2010-04-26 23:41:26 +0000 | [diff] [blame] | 2215 | |
Michael Foord | de4ceab | 2010-04-25 19:53:49 +0000 | [diff] [blame] | 2216 | .. function:: removeHandler(function=None) |
| 2217 | |
| 2218 | When called without arguments this function removes the control-c handler |
| 2219 | if it has been installed. This function can also be used as a test decorator |
| 2220 | to temporarily remove the handler whilst the test is being executed:: |
| 2221 | |
| 2222 | @unittest.removeHandler |
| 2223 | def test_signal_handling(self): |
| 2224 | ... |