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