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