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