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