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