Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 2 | :mod:`unittest` --- Unit testing framework |
| 3 | ========================================== |
| 4 | |
| 5 | .. module:: unittest |
| 6 | :synopsis: Unit testing framework for Python. |
| 7 | .. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com> |
| 8 | .. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com> |
| 9 | .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> |
| 10 | .. sectionauthor:: Raymond Hettinger <python@rcn.com> |
| 11 | |
| 12 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 13 | The Python unit testing framework, sometimes referred to as "PyUnit," is a |
| 14 | Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in |
| 15 | turn, a Java version of Kent's Smalltalk testing framework. Each is the de |
| 16 | facto standard unit testing framework for its respective language. |
| 17 | |
| 18 | :mod:`unittest` supports test automation, sharing of setup and shutdown code for |
| 19 | tests, aggregation of tests into collections, and independence of the tests from |
| 20 | the reporting framework. The :mod:`unittest` module provides classes that make |
| 21 | it easy to support these qualities for a set of tests. |
| 22 | |
| 23 | To achieve this, :mod:`unittest` supports some important concepts: |
| 24 | |
| 25 | test fixture |
| 26 | A :dfn:`test fixture` represents the preparation needed to perform one or more |
| 27 | tests, and any associate cleanup actions. This may involve, for example, |
| 28 | creating temporary or proxy databases, directories, or starting a server |
| 29 | process. |
| 30 | |
| 31 | test case |
| 32 | A :dfn:`test case` is the smallest unit of testing. It checks for a specific |
| 33 | response to a particular set of inputs. :mod:`unittest` provides a base class, |
| 34 | :class:`TestCase`, which may be used to create new test cases. |
| 35 | |
| 36 | test suite |
| 37 | A :dfn:`test suite` is a collection of test cases, test suites, or both. It is |
| 38 | used to aggregate tests that should be executed together. |
| 39 | |
| 40 | test runner |
| 41 | A :dfn:`test runner` is a component which orchestrates the execution of tests |
| 42 | and provides the outcome to the user. The runner may use a graphical interface, |
| 43 | a textual interface, or return a special value to indicate the results of |
| 44 | executing the tests. |
| 45 | |
| 46 | The test case and test fixture concepts are supported through the |
| 47 | :class:`TestCase` and :class:`FunctionTestCase` classes; the former should be |
| 48 | used when creating new tests, and the latter can be used when integrating |
| 49 | existing test code with a :mod:`unittest`\ -driven framework. When building test |
| 50 | fixtures using :class:`TestCase`, the :meth:`setUp` and :meth:`tearDown` methods |
| 51 | can be overridden to provide initialization and cleanup for the fixture. With |
| 52 | :class:`FunctionTestCase`, existing functions can be passed to the constructor |
| 53 | for these purposes. When the test is run, the fixture initialization is run |
| 54 | first; if it succeeds, the cleanup method is run after the test has been |
| 55 | executed, regardless of the outcome of the test. Each instance of the |
| 56 | :class:`TestCase` will only be used to run a single test method, so a new |
| 57 | fixture is created for each test. |
| 58 | |
| 59 | Test suites are implemented by the :class:`TestSuite` class. This class allows |
| 60 | individual tests and test suites to be aggregated; when the suite is executed, |
| 61 | all tests added directly to the suite and in "child" test suites are run. |
| 62 | |
| 63 | A test runner is an object that provides a single method, :meth:`run`, which |
| 64 | accepts a :class:`TestCase` or :class:`TestSuite` object as a parameter, and |
| 65 | returns a result object. The class :class:`TestResult` is provided for use as |
| 66 | the result object. :mod:`unittest` provides the :class:`TextTestRunner` as an |
| 67 | example test runner which reports test results on the standard error stream by |
| 68 | default. Alternate runners can be implemented for other environments (such as |
| 69 | graphical environments) without any need to derive from a specific class. |
| 70 | |
| 71 | |
| 72 | .. seealso:: |
| 73 | |
| 74 | Module :mod:`doctest` |
| 75 | Another test-support module with a very different flavor. |
| 76 | |
| 77 | `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_ |
| 78 | Kent Beck's original paper on testing frameworks using the pattern shared by |
| 79 | :mod:`unittest`. |
| 80 | |
| 81 | |
| 82 | .. _unittest-minimal-example: |
| 83 | |
| 84 | Basic example |
| 85 | ------------- |
| 86 | |
| 87 | The :mod:`unittest` module provides a rich set of tools for constructing and |
| 88 | running tests. This section demonstrates that a small subset of the tools |
| 89 | suffice to meet the needs of most users. |
| 90 | |
| 91 | Here is a short script to test three functions from the :mod:`random` module:: |
| 92 | |
| 93 | import random |
| 94 | import unittest |
| 95 | |
| 96 | class TestSequenceFunctions(unittest.TestCase): |
| 97 | |
| 98 | def setUp(self): |
| 99 | self.seq = range(10) |
| 100 | |
| 101 | def testshuffle(self): |
| 102 | # make sure the shuffled sequence does not lose any elements |
| 103 | random.shuffle(self.seq) |
| 104 | self.seq.sort() |
| 105 | self.assertEqual(self.seq, range(10)) |
| 106 | |
| 107 | def testchoice(self): |
| 108 | element = random.choice(self.seq) |
| 109 | self.assert_(element in self.seq) |
| 110 | |
| 111 | def testsample(self): |
| 112 | self.assertRaises(ValueError, random.sample, self.seq, 20) |
| 113 | for element in random.sample(self.seq, 5): |
| 114 | self.assert_(element in self.seq) |
| 115 | |
| 116 | if __name__ == '__main__': |
| 117 | unittest.main() |
| 118 | |
| 119 | A testcase is created by subclassing :class:`unittest.TestCase`. The three |
| 120 | individual tests are defined with methods whose names start with the letters |
| 121 | ``test``. This naming convention informs the test runner about which methods |
| 122 | represent tests. |
| 123 | |
| 124 | The crux of each test is a call to :meth:`assertEqual` to check for an expected |
| 125 | result; :meth:`assert_` to verify a condition; or :meth:`assertRaises` to verify |
| 126 | that an expected exception gets raised. These methods are used instead of the |
| 127 | :keyword:`assert` statement so the test runner can accumulate all test results |
| 128 | and produce a report. |
| 129 | |
| 130 | When a :meth:`setUp` method is defined, the test runner will run that method |
| 131 | prior to each test. Likewise, if a :meth:`tearDown` method is defined, the test |
| 132 | runner will invoke that method after each test. In the example, :meth:`setUp` |
| 133 | was used to create a fresh sequence for each test. |
| 134 | |
| 135 | The final block shows a simple way to run the tests. :func:`unittest.main` |
| 136 | provides a command line interface to the test script. When run from the command |
| 137 | line, the above script produces an output that looks like this:: |
| 138 | |
| 139 | ... |
| 140 | ---------------------------------------------------------------------- |
| 141 | Ran 3 tests in 0.000s |
| 142 | |
| 143 | OK |
| 144 | |
| 145 | Instead of :func:`unittest.main`, there are other ways to run the tests with a |
| 146 | finer level of control, less terse output, and no requirement to be run from the |
| 147 | command line. For example, the last two lines may be replaced with:: |
| 148 | |
| 149 | suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions) |
| 150 | unittest.TextTestRunner(verbosity=2).run(suite) |
| 151 | |
| 152 | Running the revised script from the interpreter or another script produces the |
| 153 | following output:: |
| 154 | |
| 155 | testchoice (__main__.TestSequenceFunctions) ... ok |
| 156 | testsample (__main__.TestSequenceFunctions) ... ok |
| 157 | testshuffle (__main__.TestSequenceFunctions) ... ok |
| 158 | |
| 159 | ---------------------------------------------------------------------- |
| 160 | Ran 3 tests in 0.110s |
| 161 | |
| 162 | OK |
| 163 | |
| 164 | The above examples show the most commonly used :mod:`unittest` features which |
| 165 | are sufficient to meet many everyday testing needs. The remainder of the |
| 166 | documentation explores the full feature set from first principles. |
| 167 | |
| 168 | |
| 169 | .. _organizing-tests: |
| 170 | |
| 171 | Organizing test code |
| 172 | -------------------- |
| 173 | |
| 174 | The basic building blocks of unit testing are :dfn:`test cases` --- single |
| 175 | scenarios that must be set up and checked for correctness. In :mod:`unittest`, |
| 176 | test cases are represented by instances of :mod:`unittest`'s :class:`TestCase` |
| 177 | class. To make your own test cases you must write subclasses of |
| 178 | :class:`TestCase`, or use :class:`FunctionTestCase`. |
| 179 | |
| 180 | An instance of a :class:`TestCase`\ -derived class is an object that can |
| 181 | completely run a single test method, together with optional set-up and tidy-up |
| 182 | code. |
| 183 | |
| 184 | The testing code of a :class:`TestCase` instance should be entirely self |
| 185 | contained, such that it can be run either in isolation or in arbitrary |
| 186 | combination with any number of other test cases. |
| 187 | |
| 188 | The simplest :class:`TestCase` subclass will simply override the :meth:`runTest` |
| 189 | method in order to perform specific testing code:: |
| 190 | |
| 191 | import unittest |
| 192 | |
| 193 | class DefaultWidgetSizeTestCase(unittest.TestCase): |
| 194 | def runTest(self): |
| 195 | widget = Widget('The widget') |
| 196 | self.assertEqual(widget.size(), (50, 50), 'incorrect default size') |
| 197 | |
| 198 | Note that in order to test something, we use the one of the :meth:`assert\*` or |
| 199 | :meth:`fail\*` methods provided by the :class:`TestCase` base class. If the |
| 200 | test fails, an exception will be raised, and :mod:`unittest` will identify the |
| 201 | test case as a :dfn:`failure`. Any other exceptions will be treated as |
| 202 | :dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are |
| 203 | caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are |
| 204 | caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect |
| 205 | function call. |
| 206 | |
| 207 | The way to run a test case will be described later. For now, note that to |
| 208 | construct an instance of such a test case, we call its constructor without |
| 209 | arguments:: |
| 210 | |
| 211 | testCase = DefaultWidgetSizeTestCase() |
| 212 | |
| 213 | Now, such test cases can be numerous, and their set-up can be repetitive. In |
| 214 | the above case, constructing a :class:`Widget` in each of 100 Widget test case |
| 215 | subclasses would mean unsightly duplication. |
| 216 | |
| 217 | Luckily, we can factor out such set-up code by implementing a method called |
| 218 | :meth:`setUp`, which the testing framework will automatically call for us when |
| 219 | we run the test:: |
| 220 | |
| 221 | import unittest |
| 222 | |
| 223 | class SimpleWidgetTestCase(unittest.TestCase): |
| 224 | def setUp(self): |
| 225 | self.widget = Widget('The widget') |
| 226 | |
| 227 | class DefaultWidgetSizeTestCase(SimpleWidgetTestCase): |
| 228 | def runTest(self): |
| 229 | self.failUnless(self.widget.size() == (50,50), |
| 230 | 'incorrect default size') |
| 231 | |
| 232 | class WidgetResizeTestCase(SimpleWidgetTestCase): |
| 233 | def runTest(self): |
| 234 | self.widget.resize(100,150) |
| 235 | self.failUnless(self.widget.size() == (100,150), |
| 236 | 'wrong size after resize') |
| 237 | |
| 238 | If the :meth:`setUp` method raises an exception while the test is running, the |
| 239 | framework will consider the test to have suffered an error, and the |
| 240 | :meth:`runTest` method will not be executed. |
| 241 | |
| 242 | Similarly, we can provide a :meth:`tearDown` method that tidies up after the |
| 243 | :meth:`runTest` method has been run:: |
| 244 | |
| 245 | import unittest |
| 246 | |
| 247 | class SimpleWidgetTestCase(unittest.TestCase): |
| 248 | def setUp(self): |
| 249 | self.widget = Widget('The widget') |
| 250 | |
| 251 | def tearDown(self): |
| 252 | self.widget.dispose() |
| 253 | self.widget = None |
| 254 | |
| 255 | If :meth:`setUp` succeeded, the :meth:`tearDown` method will be run whether |
| 256 | :meth:`runTest` succeeded or not. |
| 257 | |
| 258 | Such a working environment for the testing code is called a :dfn:`fixture`. |
| 259 | |
| 260 | Often, many small test cases will use the same fixture. In this case, we would |
| 261 | end up subclassing :class:`SimpleWidgetTestCase` into many small one-method |
| 262 | classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 263 | discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler |
| 264 | mechanism:: |
| 265 | |
| 266 | import unittest |
| 267 | |
| 268 | class WidgetTestCase(unittest.TestCase): |
| 269 | def setUp(self): |
| 270 | self.widget = Widget('The widget') |
| 271 | |
| 272 | def tearDown(self): |
| 273 | self.widget.dispose() |
| 274 | self.widget = None |
| 275 | |
| 276 | def testDefaultSize(self): |
| 277 | self.failUnless(self.widget.size() == (50,50), |
| 278 | 'incorrect default size') |
| 279 | |
| 280 | def testResize(self): |
| 281 | self.widget.resize(100,150) |
| 282 | self.failUnless(self.widget.size() == (100,150), |
| 283 | 'wrong size after resize') |
| 284 | |
| 285 | Here we have not provided a :meth:`runTest` method, but have instead provided |
| 286 | two different test methods. Class instances will now each run one of the |
| 287 | :meth:`test\*` methods, with ``self.widget`` created and destroyed separately |
| 288 | for each instance. When creating an instance we must specify the test method it |
| 289 | is to run. We do this by passing the method name in the constructor:: |
| 290 | |
| 291 | defaultSizeTestCase = WidgetTestCase('testDefaultSize') |
| 292 | resizeTestCase = WidgetTestCase('testResize') |
| 293 | |
| 294 | Test case instances are grouped together according to the features they test. |
| 295 | :mod:`unittest` provides a mechanism for this: the :dfn:`test suite`, |
| 296 | represented by :mod:`unittest`'s :class:`TestSuite` class:: |
| 297 | |
| 298 | widgetTestSuite = unittest.TestSuite() |
| 299 | widgetTestSuite.addTest(WidgetTestCase('testDefaultSize')) |
| 300 | widgetTestSuite.addTest(WidgetTestCase('testResize')) |
| 301 | |
| 302 | For the ease of running tests, as we will see later, it is a good idea to |
| 303 | provide in each test module a callable object that returns a pre-built test |
| 304 | suite:: |
| 305 | |
| 306 | def suite(): |
| 307 | suite = unittest.TestSuite() |
| 308 | suite.addTest(WidgetTestCase('testDefaultSize')) |
| 309 | suite.addTest(WidgetTestCase('testResize')) |
| 310 | return suite |
| 311 | |
| 312 | or even:: |
| 313 | |
| 314 | def suite(): |
| 315 | tests = ['testDefaultSize', 'testResize'] |
| 316 | |
| 317 | return unittest.TestSuite(map(WidgetTestCase, tests)) |
| 318 | |
| 319 | Since it is a common pattern to create a :class:`TestCase` subclass with many |
| 320 | similarly named test functions, :mod:`unittest` provides a :class:`TestLoader` |
| 321 | class that can be used to automate the process of creating a test suite and |
| 322 | populating it with individual tests. For example, :: |
| 323 | |
| 324 | suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase) |
| 325 | |
| 326 | will create a test suite that will run ``WidgetTestCase.testDefaultSize()`` and |
| 327 | ``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method |
| 328 | name prefix to identify test methods automatically. |
| 329 | |
| 330 | Note that the order in which the various test cases will be run is determined by |
| 331 | sorting the test function names with the built-in :func:`cmp` function. |
| 332 | |
| 333 | Often it is desirable to group suites of test cases together, so as to run tests |
| 334 | for the whole system at once. This is easy, since :class:`TestSuite` instances |
| 335 | can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be |
| 336 | added to a :class:`TestSuite`:: |
| 337 | |
| 338 | suite1 = module1.TheTestSuite() |
| 339 | suite2 = module2.TheTestSuite() |
| 340 | alltests = unittest.TestSuite([suite1, suite2]) |
| 341 | |
| 342 | You can place the definitions of test cases and test suites in the same modules |
| 343 | as the code they are to test (such as :file:`widget.py`), but there are several |
| 344 | advantages to placing the test code in a separate module, such as |
| 345 | :file:`test_widget.py`: |
| 346 | |
| 347 | * The test module can be run standalone from the command line. |
| 348 | |
| 349 | * The test code can more easily be separated from shipped code. |
| 350 | |
| 351 | * There is less temptation to change test code to fit the code it tests without |
| 352 | a good reason. |
| 353 | |
| 354 | * Test code should be modified much less frequently than the code it tests. |
| 355 | |
| 356 | * Tested code can be refactored more easily. |
| 357 | |
| 358 | * Tests for modules written in C must be in separate modules anyway, so why not |
| 359 | be consistent? |
| 360 | |
| 361 | * If the testing strategy changes, there is no need to change the source code. |
| 362 | |
| 363 | |
| 364 | .. _legacy-unit-tests: |
| 365 | |
| 366 | Re-using old test code |
| 367 | ---------------------- |
| 368 | |
| 369 | Some users will find that they have existing test code that they would like to |
| 370 | run from :mod:`unittest`, without converting every old test function to a |
| 371 | :class:`TestCase` subclass. |
| 372 | |
| 373 | For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class. |
| 374 | This subclass of :class:`TestCase` can be used to wrap an existing test |
| 375 | function. Set-up and tear-down functions can also be provided. |
| 376 | |
| 377 | Given the following test function:: |
| 378 | |
| 379 | def testSomething(): |
| 380 | something = makeSomething() |
| 381 | assert something.name is not None |
| 382 | # ... |
| 383 | |
| 384 | one can create an equivalent test case instance as follows:: |
| 385 | |
| 386 | testcase = unittest.FunctionTestCase(testSomething) |
| 387 | |
| 388 | If there are additional set-up and tear-down methods that should be called as |
| 389 | part of the test case's operation, they can also be provided like so:: |
| 390 | |
| 391 | testcase = unittest.FunctionTestCase(testSomething, |
| 392 | setUp=makeSomethingDB, |
| 393 | tearDown=deleteSomethingDB) |
| 394 | |
| 395 | To make migrating existing test suites easier, :mod:`unittest` supports tests |
| 396 | raising :exc:`AssertionError` to indicate test failure. However, it is |
| 397 | recommended that you use the explicit :meth:`TestCase.fail\*` and |
| 398 | :meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest` |
| 399 | may treat :exc:`AssertionError` differently. |
| 400 | |
| 401 | .. note:: |
| 402 | |
| 403 | Even though :class:`FunctionTestCase` can be used to quickly convert an existing |
| 404 | test base over to a :mod:`unittest`\ -based system, this approach is not |
| 405 | recommended. Taking the time to set up proper :class:`TestCase` subclasses will |
| 406 | make future test refactorings infinitely easier. |
| 407 | |
| 408 | |
| 409 | .. _unittest-contents: |
| 410 | |
| 411 | Classes and functions |
| 412 | --------------------- |
| 413 | |
| 414 | |
| 415 | .. class:: TestCase([methodName]) |
| 416 | |
| 417 | Instances of the :class:`TestCase` class represent the smallest testable units |
| 418 | in the :mod:`unittest` universe. This class is intended to be used as a base |
| 419 | class, with specific tests being implemented by concrete subclasses. This class |
| 420 | implements the interface needed by the test runner to allow it to drive the |
| 421 | test, and methods that the test code can use to check for and report various |
| 422 | kinds of failure. |
| 423 | |
| 424 | Each instance of :class:`TestCase` will run a single test method: the method |
| 425 | named *methodName*. If you remember, we had an earlier example that went |
| 426 | something like this:: |
| 427 | |
| 428 | def suite(): |
| 429 | suite = unittest.TestSuite() |
| 430 | suite.addTest(WidgetTestCase('testDefaultSize')) |
| 431 | suite.addTest(WidgetTestCase('testResize')) |
| 432 | return suite |
| 433 | |
| 434 | Here, we create two instances of :class:`WidgetTestCase`, each of which runs a |
| 435 | single test. |
| 436 | |
| 437 | *methodName* defaults to ``'runTest'``. |
| 438 | |
| 439 | |
| 440 | .. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]]) |
| 441 | |
| 442 | This class implements the portion of the :class:`TestCase` interface which |
| 443 | allows the test runner to drive the test, but does not provide the methods which |
| 444 | test code can use to check and report errors. This is used to create test cases |
| 445 | using legacy test code, allowing it to be integrated into a :mod:`unittest`\ |
| 446 | -based test framework. |
| 447 | |
| 448 | |
| 449 | .. class:: TestSuite([tests]) |
| 450 | |
| 451 | This class represents an aggregation of individual tests cases and test suites. |
| 452 | The class presents the interface needed by the test runner to allow it to be run |
| 453 | as any other test case. Running a :class:`TestSuite` instance is the same as |
| 454 | iterating over the suite, running each test individually. |
| 455 | |
| 456 | If *tests* is given, it must be an iterable of individual test cases or other |
| 457 | test suites that will be used to build the suite initially. Additional methods |
| 458 | are provided to add test cases and suites to the collection later on. |
| 459 | |
| 460 | |
| 461 | .. class:: TestLoader() |
| 462 | |
| 463 | This class is responsible for loading tests according to various criteria and |
| 464 | returning them wrapped in a :class:`TestSuite`. It can load all tests within a |
| 465 | given module or :class:`TestCase` subclass. |
| 466 | |
| 467 | |
| 468 | .. class:: TestResult() |
| 469 | |
| 470 | This class is used to compile information about which tests have succeeded and |
| 471 | which have failed. |
| 472 | |
| 473 | |
| 474 | .. data:: defaultTestLoader |
| 475 | |
| 476 | Instance of the :class:`TestLoader` class intended to be shared. If no |
| 477 | customization of the :class:`TestLoader` is needed, this instance can be used |
| 478 | instead of repeatedly creating new instances. |
| 479 | |
| 480 | |
| 481 | .. class:: TextTestRunner([stream[, descriptions[, verbosity]]]) |
| 482 | |
| 483 | A basic test runner implementation which prints results on standard error. It |
| 484 | has a few configurable parameters, but is essentially very simple. Graphical |
| 485 | applications which run test suites should provide alternate implementations. |
| 486 | |
| 487 | |
| 488 | .. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader]]]]]) |
| 489 | |
| 490 | A command-line program that runs a set of tests; this is primarily for making |
| 491 | test modules conveniently executable. The simplest use for this function is to |
| 492 | include the following line at the end of a test script:: |
| 493 | |
| 494 | if __name__ == '__main__': |
| 495 | unittest.main() |
| 496 | |
| 497 | The *testRunner* argument can either be a test runner class or an already |
| 498 | created instance of it. |
| 499 | |
| 500 | In some cases, the existing tests may have been written using the :mod:`doctest` |
| 501 | module. If so, that module provides a :class:`DocTestSuite` class that can |
| 502 | automatically build :class:`unittest.TestSuite` instances from the existing |
| 503 | :mod:`doctest`\ -based tests. |
| 504 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 505 | |
| 506 | .. _testcase-objects: |
| 507 | |
| 508 | TestCase Objects |
| 509 | ---------------- |
| 510 | |
| 511 | Each :class:`TestCase` instance represents a single test, but each concrete |
| 512 | subclass may be used to define multiple tests --- the concrete class represents |
| 513 | a single test fixture. The fixture is created and cleaned up for each test |
| 514 | case. |
| 515 | |
| 516 | :class:`TestCase` instances provide three groups of methods: one group used to |
| 517 | run the test, another used by the test implementation to check conditions and |
| 518 | report failures, and some inquiry methods allowing information about the test |
| 519 | itself to be gathered. |
| 520 | |
| 521 | Methods in the first group (running the test) are: |
| 522 | |
| 523 | |
| 524 | .. method:: TestCase.setUp() |
| 525 | |
| 526 | Method called to prepare the test fixture. This is called immediately before |
| 527 | calling the test method; any exception raised by this method will be considered |
| 528 | an error rather than a test failure. The default implementation does nothing. |
| 529 | |
| 530 | |
| 531 | .. method:: TestCase.tearDown() |
| 532 | |
| 533 | Method called immediately after the test method has been called and the result |
| 534 | recorded. This is called even if the test method raised an exception, so the |
| 535 | implementation in subclasses may need to be particularly careful about checking |
| 536 | internal state. Any exception raised by this method will be considered an error |
| 537 | rather than a test failure. This method will only be called if the |
| 538 | :meth:`setUp` succeeds, regardless of the outcome of the test method. The |
| 539 | default implementation does nothing. |
| 540 | |
| 541 | |
| 542 | .. method:: TestCase.run([result]) |
| 543 | |
| 544 | Run the test, collecting the result into the test result object passed as |
| 545 | *result*. If *result* is omitted or :const:`None`, a temporary result object is |
| 546 | created (by calling the :meth:`defaultTestCase` method) and used; this result |
| 547 | object is not returned to :meth:`run`'s caller. |
| 548 | |
| 549 | The same effect may be had by simply calling the :class:`TestCase` instance. |
| 550 | |
| 551 | |
| 552 | .. method:: TestCase.debug() |
| 553 | |
| 554 | Run the test without collecting the result. This allows exceptions raised by |
| 555 | the test to be propagated to the caller, and can be used to support running |
| 556 | tests under a debugger. |
| 557 | |
| 558 | The test code can use any of the following methods to check for and report |
| 559 | failures. |
| 560 | |
| 561 | |
| 562 | .. method:: TestCase.assert_(expr[, msg]) |
| 563 | TestCase.failUnless(expr[, msg]) |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 564 | TestCase.assertTrue(expr[, msg]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 565 | |
| 566 | Signal a test failure if *expr* is false; the explanation for the error will be |
| 567 | *msg* if given, otherwise it will be :const:`None`. |
| 568 | |
| 569 | |
| 570 | .. method:: TestCase.assertEqual(first, second[, msg]) |
| 571 | TestCase.failUnlessEqual(first, second[, msg]) |
| 572 | |
| 573 | Test that *first* and *second* are equal. If the values do not compare equal, |
| 574 | the test will fail with the explanation given by *msg*, or :const:`None`. Note |
| 575 | that using :meth:`failUnlessEqual` improves upon doing the comparison as the |
| 576 | first parameter to :meth:`failUnless`: the default value for *msg* can be |
| 577 | computed to include representations of both *first* and *second*. |
| 578 | |
| 579 | |
| 580 | .. method:: TestCase.assertNotEqual(first, second[, msg]) |
| 581 | TestCase.failIfEqual(first, second[, msg]) |
| 582 | |
| 583 | Test that *first* and *second* are not equal. If the values do compare equal, |
| 584 | the test will fail with the explanation given by *msg*, or :const:`None`. Note |
| 585 | that using :meth:`failIfEqual` improves upon doing the comparison as the first |
| 586 | parameter to :meth:`failUnless` is that the default value for *msg* can be |
| 587 | computed to include representations of both *first* and *second*. |
| 588 | |
| 589 | |
| 590 | .. method:: TestCase.assertAlmostEqual(first, second[, places[, msg]]) |
| 591 | TestCase.failUnlessAlmostEqual(first, second[, places[, msg]]) |
| 592 | |
| 593 | Test that *first* and *second* are approximately equal by computing the |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 594 | difference, rounding to the given number of decimal *places* (default 7), |
Benjamin Peterson | 9bc9351 | 2008-09-22 22:10:59 +0000 | [diff] [blame] | 595 | and comparing to zero. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 596 | Note that comparing a given number of decimal places is not the same as |
| 597 | comparing a given number of significant digits. If the values do not compare |
| 598 | equal, the test will fail with the explanation given by *msg*, or :const:`None`. |
| 599 | |
| 600 | |
| 601 | .. method:: TestCase.assertNotAlmostEqual(first, second[, places[, msg]]) |
| 602 | TestCase.failIfAlmostEqual(first, second[, places[, msg]]) |
| 603 | |
| 604 | Test that *first* and *second* are not approximately equal by computing the |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 605 | difference, rounding to the given number of decimal *places* (default 7), |
Benjamin Peterson | 9bc9351 | 2008-09-22 22:10:59 +0000 | [diff] [blame] | 606 | and comparing to zero. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 607 | Note that comparing a given number of decimal places is not the same as |
| 608 | comparing a given number of significant digits. If the values do not compare |
| 609 | equal, the test will fail with the explanation given by *msg*, or :const:`None`. |
| 610 | |
| 611 | |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 612 | .. method:: TestCase.assertRaises(exception[, callable, ...]) |
| 613 | TestCase.failUnlessRaises(exception[, callable, ...]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 614 | |
| 615 | Test that an exception is raised when *callable* is called with any positional |
| 616 | or keyword arguments that are also passed to :meth:`assertRaises`. The test |
| 617 | passes if *exception* is raised, is an error if another exception is raised, or |
| 618 | fails if no exception is raised. To catch any of a group of exceptions, a tuple |
| 619 | containing the exception classes may be passed as *exception*. |
| 620 | |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 621 | If *callable* is omitted or None, returns a context manager so that the code |
| 622 | under test can be written inline rather than as a function:: |
| 623 | |
| 624 | with self.failUnlessRaises(some_error_class): |
| 625 | do_something() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 626 | |
| 627 | .. method:: TestCase.failIf(expr[, msg]) |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 628 | TestCase.assertFalse(expr[, msg]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 629 | |
| 630 | The inverse of the :meth:`failUnless` method is the :meth:`failIf` method. This |
| 631 | signals a test failure if *expr* is true, with *msg* or :const:`None` for the |
| 632 | error message. |
| 633 | |
| 634 | |
| 635 | .. method:: TestCase.fail([msg]) |
| 636 | |
| 637 | Signals a test failure unconditionally, with *msg* or :const:`None` for the |
| 638 | error message. |
| 639 | |
| 640 | |
| 641 | .. attribute:: TestCase.failureException |
| 642 | |
| 643 | This class attribute gives the exception raised by the :meth:`test` method. If |
| 644 | a test framework needs to use a specialized exception, possibly to carry |
| 645 | additional information, it must subclass this exception in order to "play fair" |
| 646 | with the framework. The initial value of this attribute is |
| 647 | :exc:`AssertionError`. |
| 648 | |
| 649 | Testing frameworks can use the following methods to collect information on the |
| 650 | test: |
| 651 | |
| 652 | |
| 653 | .. method:: TestCase.countTestCases() |
| 654 | |
| 655 | Return the number of tests represented by this test object. For |
| 656 | :class:`TestCase` instances, this will always be ``1``. |
| 657 | |
| 658 | |
| 659 | .. method:: TestCase.defaultTestResult() |
| 660 | |
| 661 | Return an instance of the test result class that should be used for this test |
| 662 | case class (if no other result instance is provided to the :meth:`run` method). |
| 663 | |
| 664 | For :class:`TestCase` instances, this will always be an instance of |
| 665 | :class:`TestResult`; subclasses of :class:`TestCase` should override this as |
| 666 | necessary. |
| 667 | |
| 668 | |
| 669 | .. method:: TestCase.id() |
| 670 | |
| 671 | Return a string identifying the specific test case. This is usually the full |
| 672 | name of the test method, including the module and class name. |
| 673 | |
| 674 | |
| 675 | .. method:: TestCase.shortDescription() |
| 676 | |
| 677 | Returns a one-line description of the test, or :const:`None` if no description |
| 678 | has been provided. The default implementation of this method returns the first |
| 679 | line of the test method's docstring, if available, or :const:`None`. |
| 680 | |
| 681 | |
| 682 | .. _testsuite-objects: |
| 683 | |
| 684 | TestSuite Objects |
| 685 | ----------------- |
| 686 | |
| 687 | :class:`TestSuite` objects behave much like :class:`TestCase` objects, except |
| 688 | they do not actually implement a test. Instead, they are used to aggregate |
| 689 | tests into groups of tests that should be run together. Some additional methods |
| 690 | are available to add tests to :class:`TestSuite` instances: |
| 691 | |
| 692 | |
| 693 | .. method:: TestSuite.addTest(test) |
| 694 | |
| 695 | Add a :class:`TestCase` or :class:`TestSuite` to the suite. |
| 696 | |
| 697 | |
| 698 | .. method:: TestSuite.addTests(tests) |
| 699 | |
| 700 | Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite` |
| 701 | instances to this test suite. |
| 702 | |
| 703 | This is equivalent to iterating over *tests*, calling :meth:`addTest` for each |
| 704 | element. |
| 705 | |
| 706 | :class:`TestSuite` shares the following methods with :class:`TestCase`: |
| 707 | |
| 708 | |
| 709 | .. method:: TestSuite.run(result) |
| 710 | |
| 711 | Run the tests associated with this suite, collecting the result into the test |
| 712 | result object passed as *result*. Note that unlike :meth:`TestCase.run`, |
| 713 | :meth:`TestSuite.run` requires the result object to be passed in. |
| 714 | |
| 715 | |
| 716 | .. method:: TestSuite.debug() |
| 717 | |
| 718 | Run the tests associated with this suite without collecting the result. This |
| 719 | allows exceptions raised by the test to be propagated to the caller and can be |
| 720 | used to support running tests under a debugger. |
| 721 | |
| 722 | |
| 723 | .. method:: TestSuite.countTestCases() |
| 724 | |
| 725 | Return the number of tests represented by this test object, including all |
| 726 | individual tests and sub-suites. |
| 727 | |
| 728 | In the typical usage of a :class:`TestSuite` object, the :meth:`run` method is |
| 729 | invoked by a :class:`TestRunner` rather than by the end-user test harness. |
| 730 | |
| 731 | |
| 732 | .. _testresult-objects: |
| 733 | |
| 734 | TestResult Objects |
| 735 | ------------------ |
| 736 | |
| 737 | A :class:`TestResult` object stores the results of a set of tests. The |
| 738 | :class:`TestCase` and :class:`TestSuite` classes ensure that results are |
| 739 | properly recorded; test authors do not need to worry about recording the outcome |
| 740 | of tests. |
| 741 | |
| 742 | Testing frameworks built on top of :mod:`unittest` may want access to the |
| 743 | :class:`TestResult` object generated by running a set of tests for reporting |
| 744 | purposes; a :class:`TestResult` instance is returned by the |
| 745 | :meth:`TestRunner.run` method for this purpose. |
| 746 | |
| 747 | :class:`TestResult` instances have the following attributes that will be of |
| 748 | interest when inspecting the results of running a set of tests: |
| 749 | |
| 750 | |
| 751 | .. attribute:: TestResult.errors |
| 752 | |
| 753 | A list containing 2-tuples of :class:`TestCase` instances and strings holding |
| 754 | formatted tracebacks. Each tuple represents a test which raised an unexpected |
| 755 | exception. |
| 756 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 757 | |
| 758 | .. attribute:: TestResult.failures |
| 759 | |
| 760 | A list containing 2-tuples of :class:`TestCase` instances and strings holding |
| 761 | formatted tracebacks. Each tuple represents a test where a failure was |
| 762 | explicitly signalled using the :meth:`TestCase.fail\*` or |
| 763 | :meth:`TestCase.assert\*` methods. |
| 764 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 765 | |
| 766 | .. attribute:: TestResult.testsRun |
| 767 | |
| 768 | The total number of tests run so far. |
| 769 | |
| 770 | |
| 771 | .. method:: TestResult.wasSuccessful() |
| 772 | |
| 773 | Returns :const:`True` if all tests run so far have passed, otherwise returns |
| 774 | :const:`False`. |
| 775 | |
| 776 | |
| 777 | .. method:: TestResult.stop() |
| 778 | |
| 779 | This method can be called to signal that the set of tests being run should be |
| 780 | aborted by setting the :class:`TestResult`'s ``shouldStop`` attribute to |
| 781 | :const:`True`. :class:`TestRunner` objects should respect this flag and return |
| 782 | without running any additional tests. |
| 783 | |
| 784 | For example, this feature is used by the :class:`TextTestRunner` class to stop |
| 785 | the test framework when the user signals an interrupt from the keyboard. |
| 786 | Interactive tools which provide :class:`TestRunner` implementations can use this |
| 787 | in a similar manner. |
| 788 | |
| 789 | The following methods of the :class:`TestResult` class are used to maintain the |
| 790 | internal data structures, and may be extended in subclasses to support |
| 791 | additional reporting requirements. This is particularly useful in building |
| 792 | tools which support interactive reporting while tests are being run. |
| 793 | |
| 794 | |
| 795 | .. method:: TestResult.startTest(test) |
| 796 | |
| 797 | Called when the test case *test* is about to be run. |
| 798 | |
| 799 | The default implementation simply increments the instance's ``testsRun`` |
| 800 | counter. |
| 801 | |
| 802 | |
| 803 | .. method:: TestResult.stopTest(test) |
| 804 | |
| 805 | Called after the test case *test* has been executed, regardless of the outcome. |
| 806 | |
| 807 | The default implementation does nothing. |
| 808 | |
| 809 | |
| 810 | .. method:: TestResult.addError(test, err) |
| 811 | |
| 812 | Called when the test case *test* raises an unexpected exception *err* is a tuple |
| 813 | of the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``. |
| 814 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 815 | The default implementation appends a tuple ``(test, formatted_err)`` to the |
| 816 | instance's ``errors`` attribute, where *formatted_err* is a formatted |
| 817 | traceback derived from *err*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 818 | |
| 819 | |
| 820 | .. method:: TestResult.addFailure(test, err) |
| 821 | |
| 822 | Called when the test case *test* signals a failure. *err* is a tuple of the form |
| 823 | returned by :func:`sys.exc_info`: ``(type, value, traceback)``. |
| 824 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 825 | The default implementation appends a tuple ``(test, formatted_err)`` to the |
| 826 | instance's ``failures`` attribute, where *formatted_err* is a formatted |
| 827 | traceback derived from *err*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 828 | |
| 829 | |
| 830 | .. method:: TestResult.addSuccess(test) |
| 831 | |
| 832 | Called when the test case *test* succeeds. |
| 833 | |
| 834 | The default implementation does nothing. |
| 835 | |
| 836 | |
| 837 | .. _testloader-objects: |
| 838 | |
| 839 | TestLoader Objects |
| 840 | ------------------ |
| 841 | |
| 842 | The :class:`TestLoader` class is used to create test suites from classes and |
| 843 | modules. Normally, there is no need to create an instance of this class; the |
| 844 | :mod:`unittest` module provides an instance that can be shared as |
| 845 | ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows |
| 846 | customization of some configurable properties. |
| 847 | |
| 848 | :class:`TestLoader` objects have the following methods: |
| 849 | |
| 850 | |
| 851 | .. method:: TestLoader.loadTestsFromTestCase(testCaseClass) |
| 852 | |
| 853 | Return a suite of all tests cases contained in the :class:`TestCase`\ -derived |
| 854 | :class:`testCaseClass`. |
| 855 | |
| 856 | |
| 857 | .. method:: TestLoader.loadTestsFromModule(module) |
| 858 | |
| 859 | Return a suite of all tests cases contained in the given module. This method |
| 860 | searches *module* for classes derived from :class:`TestCase` and creates an |
| 861 | instance of the class for each test method defined for the class. |
| 862 | |
| 863 | .. warning:: |
| 864 | |
| 865 | While using a hierarchy of :class:`TestCase`\ -derived classes can be convenient |
| 866 | in sharing fixtures and helper functions, defining test methods on base classes |
| 867 | that are not intended to be instantiated directly does not play well with this |
| 868 | method. Doing so, however, can be useful when the fixtures are different and |
| 869 | defined in subclasses. |
| 870 | |
| 871 | |
| 872 | .. method:: TestLoader.loadTestsFromName(name[, module]) |
| 873 | |
| 874 | Return a suite of all tests cases given a string specifier. |
| 875 | |
| 876 | The specifier *name* is a "dotted name" that may resolve either to a module, a |
| 877 | test case class, a test method within a test case class, a :class:`TestSuite` |
| 878 | instance, or a callable object which returns a :class:`TestCase` or |
| 879 | :class:`TestSuite` instance. These checks are applied in the order listed here; |
| 880 | that is, a method on a possible test case class will be picked up as "a test |
| 881 | method within a test case class", rather than "a callable object". |
| 882 | |
| 883 | For example, if you have a module :mod:`SampleTests` containing a |
| 884 | :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test |
| 885 | methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the |
| 886 | specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a |
| 887 | suite which will run all three test methods. Using the specifier |
| 888 | ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite |
| 889 | which will run only the :meth:`test_two` test method. The specifier can refer |
| 890 | to modules and packages which have not been imported; they will be imported as a |
| 891 | side-effect. |
| 892 | |
| 893 | The method optionally resolves *name* relative to the given *module*. |
| 894 | |
| 895 | |
| 896 | .. method:: TestLoader.loadTestsFromNames(names[, module]) |
| 897 | |
| 898 | Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather than |
| 899 | a single name. The return value is a test suite which supports all the tests |
| 900 | defined for each name. |
| 901 | |
| 902 | |
| 903 | .. method:: TestLoader.getTestCaseNames(testCaseClass) |
| 904 | |
| 905 | Return a sorted sequence of method names found within *testCaseClass*; this |
| 906 | should be a subclass of :class:`TestCase`. |
| 907 | |
| 908 | The following attributes of a :class:`TestLoader` can be configured either by |
| 909 | subclassing or assignment on an instance: |
| 910 | |
| 911 | |
| 912 | .. attribute:: TestLoader.testMethodPrefix |
| 913 | |
| 914 | String giving the prefix of method names which will be interpreted as test |
| 915 | methods. The default value is ``'test'``. |
| 916 | |
| 917 | This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` |
| 918 | methods. |
| 919 | |
| 920 | |
| 921 | .. attribute:: TestLoader.sortTestMethodsUsing |
| 922 | |
| 923 | Function to be used to compare method names when sorting them in |
| 924 | :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The |
| 925 | default value is the built-in :func:`cmp` function; the attribute can also be |
| 926 | set to :const:`None` to disable the sort. |
| 927 | |
| 928 | |
| 929 | .. attribute:: TestLoader.suiteClass |
| 930 | |
| 931 | Callable object that constructs a test suite from a list of tests. No methods on |
| 932 | the resulting object are needed. The default value is the :class:`TestSuite` |
| 933 | class. |
| 934 | |
| 935 | This affects all the :meth:`loadTestsFrom\*` methods. |
| 936 | |