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