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