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