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