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