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