blob: 5ed75d5a87f7e414f8d24f3ee9283580d9f17eb9 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`unittest` --- Unit testing framework
2==========================================
3
4.. module:: unittest
5 :synopsis: Unit testing framework for Python.
6.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
7.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9.. sectionauthor:: Raymond Hettinger <python@rcn.com>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012The Python unit testing framework, sometimes referred to as "PyUnit," is a
13Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
14turn, a Java version of Kent's Smalltalk testing framework. Each is the de
15facto standard unit testing framework for its respective language.
16
17:mod:`unittest` supports test automation, sharing of setup and shutdown code for
18tests, aggregation of tests into collections, and independence of the tests from
19the reporting framework. The :mod:`unittest` module provides classes that make
20it easy to support these qualities for a set of tests.
21
22To achieve this, :mod:`unittest` supports some important concepts:
23
24test fixture
25 A :dfn:`test fixture` represents the preparation needed to perform one or more
26 tests, and any associate cleanup actions. This may involve, for example,
27 creating temporary or proxy databases, directories, or starting a server
28 process.
29
30test case
31 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
32 response to a particular set of inputs. :mod:`unittest` provides a base class,
33 :class:`TestCase`, which may be used to create new test cases.
34
35test suite
36 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
37 used to aggregate tests that should be executed together.
38
39test runner
40 A :dfn:`test runner` is a component which orchestrates the execution of tests
41 and provides the outcome to the user. The runner may use a graphical interface,
42 a textual interface, or return a special value to indicate the results of
43 executing the tests.
44
45The test case and test fixture concepts are supported through the
46:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
47used when creating new tests, and the latter can be used when integrating
48existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson52baa292009-03-24 00:56:30 +000049fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
50:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
51and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
52can be passed to the constructor for these purposes. When the test is run, the
53fixture initialization is run first; if it succeeds, the cleanup method is run
54after the test has been executed, regardless of the outcome of the test. Each
55instance of the :class:`TestCase` will only be used to run a single test method,
56so a new fixture is created for each test.
Georg Brandl116aa622007-08-15 14:28:22 +000057
58Test suites are implemented by the :class:`TestSuite` class. This class allows
59individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson14a3dd72009-05-25 00:51:58 +000060all tests added directly to the suite and in "child" test suites are run.
Georg Brandl116aa622007-08-15 14:28:22 +000061
Benjamin Peterson52baa292009-03-24 00:56:30 +000062A test runner is an object that provides a single method,
63:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
64object as a parameter, and returns a result object. The class
65:class:`TestResult` is provided for use as the result object. :mod:`unittest`
66provides the :class:`TextTestRunner` as an example test runner which reports
67test results on the standard error stream by default. Alternate runners can be
68implemented for other environments (such as graphical environments) without any
69need to derive from a specific class.
Georg Brandl116aa622007-08-15 14:28:22 +000070
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>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000078 Kent Beck's original paper on testing frameworks using the pattern shared
79 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000080
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000081 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000082 Third-party unittest frameworks with a lighter-weight syntax for writing
83 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000084
85 `python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000086 Tools for creating mock test objects (objects simulating external
87 resources).
88
89
90.. _unittest-command-line-interface:
91
92Command Line Interface
93----------------------
94
95The unittest module can be used from the command line to run tests from
96modules, classes or even individual test methods::
97
98 python -m unittest test_module1 test_module2
99 python -m unittest test_module.TestClass
100 python -m unittest test_module.TestClass.test_method
101
102You can pass in a list with any combination of module names, and fully
103qualified class or method names.
104
105You can run tests with more detail (higher verbosity) by passing in the -v flag::
106
Ezio Melotti176d6c42010-01-27 20:58:07 +0000107 python -m unittest -v test_module
Benjamin Petersond2397752009-06-27 23:45:02 +0000108
109For a list of all the command line options::
110
111 python -m unittest -h
112
Georg Brandl853947a2010-01-31 18:53:23 +0000113.. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +0000114 In earlier versions it was only possible to run individual test methods and
115 not modules or classes.
116
117The command line can also be used for test discovery, for running all of the
118tests in a project or just a subset.
119
120
121.. _unittest-test-discovery:
122
123Test Discovery
124--------------
125
Georg Brandl853947a2010-01-31 18:53:23 +0000126.. versionadded:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +0000127
128unittest supports simple test discovery. For a project's tests to be
129compatible with test discovery they must all be importable from the top level
130directory of the project; i.e. they must all be in Python packages.
131
132Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
133used from the command line. The basic command line usage is::
134
135 cd project_directory
136 python -m unittest discover
137
138The ``discover`` sub-command has the following options:
139
140 -v, --verbose Verbose output
141 -s directory Directory to start discovery ('.' default)
142 -p pattern Pattern to match test files ('test*.py' default)
143 -t directory Top level directory of project (default to
144 start directory)
145
146The -s, -p, & -t options can be passsed in as positional arguments. The
147following two command lines are equivalent::
148
Ezio Melotti176d6c42010-01-27 20:58:07 +0000149 python -m unittest discover -s project_directory -p '*_test.py'
150 python -m unittest discover project_directory '*_test.py'
Benjamin Petersond2397752009-06-27 23:45:02 +0000151
152Test modules and packages can customize test loading and discovery by through
153the `load_tests protocol`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155.. _unittest-minimal-example:
156
157Basic example
158-------------
159
160The :mod:`unittest` module provides a rich set of tools for constructing and
161running tests. This section demonstrates that a small subset of the tools
162suffice to meet the needs of most users.
163
164Here is a short script to test three functions from the :mod:`random` module::
165
166 import random
167 import unittest
168
169 class TestSequenceFunctions(unittest.TestCase):
170
171 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000172 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Benjamin Peterson52baa292009-03-24 00:56:30 +0000174 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000175 # make sure the shuffled sequence does not lose any elements
176 random.shuffle(self.seq)
177 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000178 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +0000179
Benjamin Peterson847a4112010-03-14 15:04:17 +0000180 # should raise an exception for an immutable sequence
181 self.assertRaises(TypeError, random.shuffle, (1,2,3))
182
Benjamin Peterson52baa292009-03-24 00:56:30 +0000183 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000184 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000185 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000186
Benjamin Peterson52baa292009-03-24 00:56:30 +0000187 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000188 with self.assertRaises(ValueError):
189 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000190 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000191 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193 if __name__ == '__main__':
194 unittest.main()
195
Benjamin Peterson52baa292009-03-24 00:56:30 +0000196A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000197individual tests are defined with methods whose names start with the letters
198``test``. This naming convention informs the test runner about which methods
199represent tests.
200
Benjamin Peterson52baa292009-03-24 00:56:30 +0000201The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000202expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000203:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
204These methods are used instead of the :keyword:`assert` statement so the test
205runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Benjamin Peterson52baa292009-03-24 00:56:30 +0000207When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
208method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
209defined, the test runner will invoke that method after each test. In the
210example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
211test.
Georg Brandl116aa622007-08-15 14:28:22 +0000212
213The final block shows a simple way to run the tests. :func:`unittest.main`
214provides a command line interface to the test script. When run from the command
215line, the above script produces an output that looks like this::
216
217 ...
218 ----------------------------------------------------------------------
219 Ran 3 tests in 0.000s
220
221 OK
222
223Instead of :func:`unittest.main`, there are other ways to run the tests with a
224finer level of control, less terse output, and no requirement to be run from the
225command line. For example, the last two lines may be replaced with::
226
227 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
228 unittest.TextTestRunner(verbosity=2).run(suite)
229
230Running the revised script from the interpreter or another script produces the
231following output::
232
Ezio Melottid59e44a2010-02-28 03:46:13 +0000233 test_choice (__main__.TestSequenceFunctions) ... ok
234 test_sample (__main__.TestSequenceFunctions) ... ok
235 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237 ----------------------------------------------------------------------
238 Ran 3 tests in 0.110s
239
240 OK
241
242The above examples show the most commonly used :mod:`unittest` features which
243are sufficient to meet many everyday testing needs. The remainder of the
244documentation explores the full feature set from first principles.
245
Georg Brandl116aa622007-08-15 14:28:22 +0000246.. _organizing-tests:
247
248Organizing test code
249--------------------
250
251The basic building blocks of unit testing are :dfn:`test cases` --- single
252scenarios that must be set up and checked for correctness. In :mod:`unittest`,
253test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
254class. To make your own test cases you must write subclasses of
255:class:`TestCase`, or use :class:`FunctionTestCase`.
256
257An instance of a :class:`TestCase`\ -derived class is an object that can
258completely run a single test method, together with optional set-up and tidy-up
259code.
260
261The testing code of a :class:`TestCase` instance should be entirely self
262contained, such that it can be run either in isolation or in arbitrary
263combination with any number of other test cases.
264
Benjamin Peterson52baa292009-03-24 00:56:30 +0000265The simplest :class:`TestCase` subclass will simply override the
266:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268 import unittest
269
270 class DefaultWidgetSizeTestCase(unittest.TestCase):
271 def runTest(self):
272 widget = Widget('The widget')
273 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
274
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000275Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000276methods provided by the :class:`TestCase` base class. If the test fails, an
277exception will be raised, and :mod:`unittest` will identify the test case as a
278:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
279helps you identify where the problem is: :dfn:`failures` are caused by incorrect
280results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
281code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283The way to run a test case will be described later. For now, note that to
284construct an instance of such a test case, we call its constructor without
285arguments::
286
287 testCase = DefaultWidgetSizeTestCase()
288
289Now, such test cases can be numerous, and their set-up can be repetitive. In
290the above case, constructing a :class:`Widget` in each of 100 Widget test case
291subclasses would mean unsightly duplication.
292
293Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000294:meth:`~TestCase.setUp`, which the testing framework will automatically call for
295us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000296
297 import unittest
298
299 class SimpleWidgetTestCase(unittest.TestCase):
300 def setUp(self):
301 self.widget = Widget('The widget')
302
303 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
304 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000305 self.assertEqual(self.widget.size(), (50,50),
306 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308 class WidgetResizeTestCase(SimpleWidgetTestCase):
309 def runTest(self):
310 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000311 self.assertEqual(self.widget.size(), (100,150),
312 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Benjamin Peterson52baa292009-03-24 00:56:30 +0000314If the :meth:`~TestCase.setUp` method raises an exception while the test is
315running, the framework will consider the test to have suffered an error, and the
316:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000317
Benjamin Peterson52baa292009-03-24 00:56:30 +0000318Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
319after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000320
321 import unittest
322
323 class SimpleWidgetTestCase(unittest.TestCase):
324 def setUp(self):
325 self.widget = Widget('The widget')
326
327 def tearDown(self):
328 self.widget.dispose()
329 self.widget = None
330
Benjamin Peterson52baa292009-03-24 00:56:30 +0000331If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
332be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334Such a working environment for the testing code is called a :dfn:`fixture`.
335
336Often, many small test cases will use the same fixture. In this case, we would
337end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
338classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000339discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
340mechanism::
341
342 import unittest
343
344 class WidgetTestCase(unittest.TestCase):
345 def setUp(self):
346 self.widget = Widget('The widget')
347
348 def tearDown(self):
349 self.widget.dispose()
350 self.widget = None
351
Ezio Melottid59e44a2010-02-28 03:46:13 +0000352 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000353 self.assertEqual(self.widget.size(), (50,50),
354 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Ezio Melottid59e44a2010-02-28 03:46:13 +0000356 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000357 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000358 self.assertEqual(self.widget.size(), (100,150),
359 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Benjamin Peterson52baa292009-03-24 00:56:30 +0000361Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
362provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000363the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000364separately for each instance. When creating an instance we must specify the
365test method it is to run. We do this by passing the method name in the
366constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000367
Ezio Melottid59e44a2010-02-28 03:46:13 +0000368 defaultSizeTestCase = WidgetTestCase('test_default_size')
369 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000370
371Test case instances are grouped together according to the features they test.
372:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
373represented by :mod:`unittest`'s :class:`TestSuite` class::
374
375 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000376 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
377 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379For the ease of running tests, as we will see later, it is a good idea to
380provide in each test module a callable object that returns a pre-built test
381suite::
382
383 def suite():
384 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000385 suite.addTest(WidgetTestCase('test_default_size'))
386 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000387 return suite
388
389or even::
390
391 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000392 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394 return unittest.TestSuite(map(WidgetTestCase, tests))
395
396Since it is a common pattern to create a :class:`TestCase` subclass with many
397similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
398class that can be used to automate the process of creating a test suite and
399populating it with individual tests. For example, ::
400
401 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
402
Ezio Melottid59e44a2010-02-28 03:46:13 +0000403will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
404``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000405name prefix to identify test methods automatically.
406
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000407Note that the order in which the various test cases will be run is
408determined by sorting the test function names with respect to the
409built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000410
411Often it is desirable to group suites of test cases together, so as to run tests
412for the whole system at once. This is easy, since :class:`TestSuite` instances
413can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
414added to a :class:`TestSuite`::
415
416 suite1 = module1.TheTestSuite()
417 suite2 = module2.TheTestSuite()
418 alltests = unittest.TestSuite([suite1, suite2])
419
420You can place the definitions of test cases and test suites in the same modules
421as the code they are to test (such as :file:`widget.py`), but there are several
422advantages to placing the test code in a separate module, such as
423:file:`test_widget.py`:
424
425* The test module can be run standalone from the command line.
426
427* The test code can more easily be separated from shipped code.
428
429* There is less temptation to change test code to fit the code it tests without
430 a good reason.
431
432* Test code should be modified much less frequently than the code it tests.
433
434* Tested code can be refactored more easily.
435
436* Tests for modules written in C must be in separate modules anyway, so why not
437 be consistent?
438
439* If the testing strategy changes, there is no need to change the source code.
440
441
442.. _legacy-unit-tests:
443
444Re-using old test code
445----------------------
446
447Some users will find that they have existing test code that they would like to
448run from :mod:`unittest`, without converting every old test function to a
449:class:`TestCase` subclass.
450
451For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
452This subclass of :class:`TestCase` can be used to wrap an existing test
453function. Set-up and tear-down functions can also be provided.
454
455Given the following test function::
456
457 def testSomething():
458 something = makeSomething()
459 assert something.name is not None
460 # ...
461
462one can create an equivalent test case instance as follows::
463
464 testcase = unittest.FunctionTestCase(testSomething)
465
466If there are additional set-up and tear-down methods that should be called as
467part of the test case's operation, they can also be provided like so::
468
469 testcase = unittest.FunctionTestCase(testSomething,
470 setUp=makeSomethingDB,
471 tearDown=deleteSomethingDB)
472
473To make migrating existing test suites easier, :mod:`unittest` supports tests
474raising :exc:`AssertionError` to indicate test failure. However, it is
475recommended that you use the explicit :meth:`TestCase.fail\*` and
476:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
477may treat :exc:`AssertionError` differently.
478
479.. note::
480
Benjamin Petersond2397752009-06-27 23:45:02 +0000481 Even though :class:`FunctionTestCase` can be used to quickly convert an
482 existing test base over to a :mod:`unittest`\ -based system, this approach is
483 not recommended. Taking the time to set up proper :class:`TestCase`
484 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000485
Benjamin Peterson52baa292009-03-24 00:56:30 +0000486In some cases, the existing tests may have been written using the :mod:`doctest`
487module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
488automatically build :class:`unittest.TestSuite` instances from the existing
489:mod:`doctest`\ -based tests.
490
Georg Brandl116aa622007-08-15 14:28:22 +0000491
Benjamin Peterson5254c042009-03-23 22:25:03 +0000492.. _unittest-skipping:
493
494Skipping tests and expected failures
495------------------------------------
496
Michael Foordf5c851a2010-02-05 21:48:03 +0000497.. versionadded:: 3.1
498
Benjamin Peterson5254c042009-03-23 22:25:03 +0000499Unittest supports skipping individual test methods and even whole classes of
500tests. In addition, it supports marking a test as a "expected failure," a test
501that is broken and will fail, but shouldn't be counted as a failure on a
502:class:`TestResult`.
503
504Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
505or one of its conditional variants.
506
507Basic skipping looks like this: ::
508
509 class MyTestCase(unittest.TestCase):
510
511 @unittest.skip("demonstrating skipping")
512 def test_nothing(self):
513 self.fail("shouldn't happen")
514
Benjamin Petersond2397752009-06-27 23:45:02 +0000515 @unittest.skipIf(mylib.__version__ < (1, 3),
516 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000517 def test_format(self):
518 # Tests that work for only a certain version of the library.
519 pass
520
521 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
522 def test_windows_support(self):
523 # windows specific testing code
524 pass
525
Benjamin Peterson5254c042009-03-23 22:25:03 +0000526This is the output of running the example above in verbose mode: ::
527
Benjamin Petersonded31c42009-03-30 15:04:16 +0000528 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000529 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000530 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000531
532 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000533 Ran 3 tests in 0.005s
534
535 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000536
537Classes can be skipped just like methods: ::
538
539 @skip("showing class skipping")
540 class MySkippedTestCase(unittest.TestCase):
541 def test_not_run(self):
542 pass
543
Benjamin Peterson52baa292009-03-24 00:56:30 +0000544:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
545that needs to be set up is not available.
546
Benjamin Peterson5254c042009-03-23 22:25:03 +0000547Expected failures use the :func:`expectedFailure` decorator. ::
548
549 class ExpectedFailureTestCase(unittest.TestCase):
550 @unittest.expectedFailure
551 def test_fail(self):
552 self.assertEqual(1, 0, "broken")
553
554It's easy to roll your own skipping decorators by making a decorator that calls
555:func:`skip` on the test when it wants it to be skipped. This decorator skips
556the test unless the passed object has a certain attribute: ::
557
558 def skipUnlessHasattr(obj, attr):
559 if hasattr(obj, attr):
560 return lambda func: func
561 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
562
563The following decorators implement test skipping and expected failures:
564
565.. function:: skip(reason)
566
567 Unconditionally skip the decorated test. *reason* should describe why the
568 test is being skipped.
569
570.. function:: skipIf(condition, reason)
571
572 Skip the decorated test if *condition* is true.
573
574.. function:: skipUnless(condition, reason)
575
576 Skip the decoratored test unless *condition* is true.
577
578.. function:: expectedFailure
579
580 Mark the test as an expected failure. If the test fails when run, the test
581 is not counted as a failure.
582
583
Georg Brandl116aa622007-08-15 14:28:22 +0000584.. _unittest-contents:
585
586Classes and functions
587---------------------
588
Benjamin Peterson52baa292009-03-24 00:56:30 +0000589This section describes in depth the API of :mod:`unittest`.
590
591
592.. _testcase-objects:
593
594Test cases
595~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000596
Georg Brandl7f01a132009-09-16 15:58:14 +0000597.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000598
599 Instances of the :class:`TestCase` class represent the smallest testable units
600 in the :mod:`unittest` universe. This class is intended to be used as a base
601 class, with specific tests being implemented by concrete subclasses. This class
602 implements the interface needed by the test runner to allow it to drive the
603 test, and methods that the test code can use to check for and report various
604 kinds of failure.
605
606 Each instance of :class:`TestCase` will run a single test method: the method
607 named *methodName*. If you remember, we had an earlier example that went
608 something like this::
609
610 def suite():
611 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000612 suite.addTest(WidgetTestCase('test_default_size'))
613 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000614 return suite
615
616 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
617 single test.
618
Benjamin Peterson52baa292009-03-24 00:56:30 +0000619 *methodName* defaults to :meth:`runTest`.
620
621 :class:`TestCase` instances provide three groups of methods: one group used
622 to run the test, another used by the test implementation to check conditions
623 and report failures, and some inquiry methods allowing information about the
624 test itself to be gathered.
625
626 Methods in the first group (running the test) are:
627
628
629 .. method:: setUp()
630
631 Method called to prepare the test fixture. This is called immediately
632 before calling the test method; any exception raised by this method will
633 be considered an error rather than a test failure. The default
634 implementation does nothing.
635
636
637 .. method:: tearDown()
638
639 Method called immediately after the test method has been called and the
640 result recorded. This is called even if the test method raised an
641 exception, so the implementation in subclasses may need to be particularly
642 careful about checking internal state. Any exception raised by this
643 method will be considered an error rather than a test failure. This
644 method will only be called if the :meth:`setUp` succeeds, regardless of
645 the outcome of the test method. The default implementation does nothing.
646
647
Georg Brandl7f01a132009-09-16 15:58:14 +0000648 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000649
650 Run the test, collecting the result into the test result object passed as
651 *result*. If *result* is omitted or :const:`None`, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000652 object is created (by calling the :meth:`defaultTestResult` method) and
653 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000654
655 The same effect may be had by simply calling the :class:`TestCase`
656 instance.
657
658
Benjamin Petersone549ead2009-03-28 21:42:05 +0000659 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000660
661 Calling this during the a test method or :meth:`setUp` skips the current
662 test. See :ref:`unittest-skipping` for more information.
663
664
665 .. method:: debug()
666
667 Run the test without collecting the result. This allows exceptions raised
668 by the test to be propagated to the caller, and can be used to support
669 running tests under a debugger.
670
671 The test code can use any of the following methods to check for and report
672 failures.
673
674
Georg Brandl7f01a132009-09-16 15:58:14 +0000675 .. method:: assertTrue(expr, msg=None)
676 assert_(expr, msg=None)
677 failUnless(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000678
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000679 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson52baa292009-03-24 00:56:30 +0000680 will be *msg* if given, otherwise it will be :const:`None`.
681
Raymond Hettinger35a88362009-04-09 00:08:24 +0000682 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000683 :meth:`failUnless`; use one of the ``assert`` variants.
Michael Foord34c94622010-02-10 15:51:42 +0000684 :meth:`assert_`; use :meth:`assertTrue`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000685
Benjamin Peterson52baa292009-03-24 00:56:30 +0000686
Georg Brandl7f01a132009-09-16 15:58:14 +0000687 .. method:: assertEqual(first, second, msg=None)
688 failUnlessEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000689
690 Test that *first* and *second* are equal. If the values do not compare
691 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000692 :const:`None`. Note that using :meth:`assertEqual` improves upon
693 doing the comparison as the first parameter to :meth:`assertTrue`: the
694 default value for *msg* include representations of both *first* and
695 *second*.
696
697 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000698 list, tuple, dict, set, frozenset or str or any type that a subclass
699 registers with :meth:`addTypeEqualityFunc` the type specific equality
700 function will be called in order to generate a more useful default
701 error message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000702
Raymond Hettinger35a88362009-04-09 00:08:24 +0000703 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000704 Added the automatic calling of type specific equality function.
705
Michael Foord28a817e2010-02-09 00:03:57 +0000706 .. versionchanged:: 3.2
707 :meth:`assertMultiLineEqual` added as the default type equality
708 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000709
Raymond Hettinger35a88362009-04-09 00:08:24 +0000710 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000711 :meth:`failUnlessEqual`; use :meth:`assertEqual`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000712
713
Georg Brandl7f01a132009-09-16 15:58:14 +0000714 .. method:: assertNotEqual(first, second, msg=None)
715 failIfEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000716
717 Test that *first* and *second* are not equal. If the values do compare
718 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000719 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
720 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson52baa292009-03-24 00:56:30 +0000721 default value for *msg* can be computed to include representations of both
722 *first* and *second*.
723
Raymond Hettinger35a88362009-04-09 00:08:24 +0000724 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000725 :meth:`failIfEqual`; use :meth:`assertNotEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000726
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000727
Georg Brandl7f01a132009-09-16 15:58:14 +0000728 .. method:: assertAlmostEqual(first, second, *, places=7, msg=None)
729 failUnlessAlmostEqual(first, second, *, places=7, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000730
731 Test that *first* and *second* are approximately equal by computing the
732 difference, rounding to the given number of decimal *places* (default 7),
733 and comparing to zero.
734
735 Note that comparing a given number of decimal places is not the same as
736 comparing a given number of significant digits. If the values do not
737 compare equal, the test will fail with the explanation given by *msg*, or
738 :const:`None`.
739
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000740 .. versionchanged:: 3.2
741 Objects that compare equal are automatically almost equal.
742
Raymond Hettinger35a88362009-04-09 00:08:24 +0000743 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000744 :meth:`failUnlessAlmostEqual`; use :meth:`assertAlmostEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000745
Benjamin Peterson52baa292009-03-24 00:56:30 +0000746
Georg Brandl7f01a132009-09-16 15:58:14 +0000747 .. method:: assertNotAlmostEqual(first, second, *, places=7, msg=None)
748 failIfAlmostEqual(first, second, *, places=7, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000749
750 Test that *first* and *second* are not approximately equal by computing
751 the difference, rounding to the given number of decimal *places* (default
752 7), and comparing to zero.
753
754 Note that comparing a given number of decimal places is not the same as
755 comparing a given number of significant digits. If the values do not
756 compare equal, the test will fail with the explanation given by *msg*, or
757 :const:`None`.
758
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000759 .. versionchanged:: 3.2
760 Objects that compare equal automatically fail.
761
Raymond Hettinger35a88362009-04-09 00:08:24 +0000762 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000763 :meth:`failIfAlmostEqual`; use :meth:`assertNotAlmostEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000764
765
766 .. method:: assertGreater(first, second, msg=None)
767 assertGreaterEqual(first, second, msg=None)
768 assertLess(first, second, msg=None)
769 assertLessEqual(first, second, msg=None)
770
771 Test that *first* is respectively >, >=, < or <= than *second* depending
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000772 on the method name. If not, the test will fail with an explanation
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000773 or with the explanation given by *msg*::
774
775 >>> self.assertGreaterEqual(3, 4)
776 AssertionError: "3" unexpectedly not greater than or equal to "4"
777
Raymond Hettinger35a88362009-04-09 00:08:24 +0000778 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000779
780
781 .. method:: assertMultiLineEqual(self, first, second, msg=None)
782
783 Test that the multiline string *first* is equal to the string *second*.
784 When not equal a diff of the two strings highlighting the differences
Michael Foord02834952010-02-08 23:10:39 +0000785 will be included in the error message. This method is used by default
786 when comparing strings with :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000787
Michael Foordabd91d52010-03-20 18:09:14 +0000788 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000789
Raymond Hettinger35a88362009-04-09 00:08:24 +0000790 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000791
792
Ezio Melotti732b6822010-01-16 19:40:06 +0000793 .. method:: assertRegexpMatches(text, regexp, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000794
795 Verifies that a *regexp* search matches *text*. Fails with an error
796 message including the pattern and the *text*. *regexp* may be
797 a regular expression object or a string containing a regular expression
798 suitable for use by :func:`re.search`.
799
Raymond Hettinger35a88362009-04-09 00:08:24 +0000800 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000801
802
803 .. method:: assertIn(first, second, msg=None)
804 assertNotIn(first, second, msg=None)
805
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000806 Tests that *first* is or is not in *second* with an explanatory error
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000807 message as appropriate.
808
Michael Foordabd91d52010-03-20 18:09:14 +0000809 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000810
Raymond Hettinger35a88362009-04-09 00:08:24 +0000811 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000812
813
Michael Foorde9abbee2010-02-05 20:54:27 +0000814 .. method:: assertSameElements(actual, expected, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000815
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000816 Test that sequence *expected* contains the same elements as *actual*,
817 regardless of their order. When they don't, an error message listing
818 the differences between the sequences will be generated.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000819
Michael Foorde9abbee2010-02-05 20:54:27 +0000820 Duplicate elements are ignored when comparing *actual* and *expected*.
821 It is the equivalent of ``assertEqual(set(expected), set(actual))``
Michael Foordabd91d52010-03-20 18:09:14 +0000822 but it works with sequences of unhashable objects as well. Because
823 duplicates are ignored, this method has been deprecated in favour of
824 :meth:`assertItemsEqual`.
Michael Foorde9abbee2010-02-05 20:54:27 +0000825
Michael Foordabd91d52010-03-20 18:09:14 +0000826 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000827
Raymond Hettinger35a88362009-04-09 00:08:24 +0000828 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000829
Michael Foordabd91d52010-03-20 18:09:14 +0000830 .. deprecated:: 3.2
831
832 .. method:: assertItemsEqual(actual, expected, msg=None)
833
834 Test that sequence *expected* contains the same elements as *actual*,
835 regardless of their order. When they don't, an error message listing the
836 differences between the sequences will be generated.
837
838 Duplicate elements are *not* ignored when comparing *actual* and
839 *expected*. It verifies if each element has the same count in both
840 sequences. It is the equivalent of ``assertEqual(sorted(expected),
841 sorted(actual))`` but it works with sequences of unhashable objects as
842 well.
843
844 If specified, *msg* will be used as the error message on failure.
845
846 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000847
848 .. method:: assertSetEqual(set1, set2, msg=None)
849
850 Tests that two sets are equal. If not, an error message is constructed
Michael Foord02834952010-02-08 23:10:39 +0000851 that lists the differences between the sets. This method is used by
852 default when comparing sets or frozensets with :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000853
854 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
855 method.
856
Michael Foordabd91d52010-03-20 18:09:14 +0000857 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000858
Raymond Hettinger35a88362009-04-09 00:08:24 +0000859 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000860
861
862 .. method:: assertDictEqual(expected, actual, msg=None)
863
864 Test that two dictionaries are equal. If not, an error message is
Michael Foord02834952010-02-08 23:10:39 +0000865 constructed that shows the differences in the dictionaries. This
866 method will be used by default to compare dictionaries in
867 calls to :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000868
Michael Foordabd91d52010-03-20 18:09:14 +0000869 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000870
Raymond Hettinger35a88362009-04-09 00:08:24 +0000871 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000872
873
874 .. method:: assertDictContainsSubset(expected, actual, msg=None)
875
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000876 Tests whether the key/value pairs in dictionary *actual* are a
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000877 superset of those in *expected*. If not, an error message listing
878 the missing keys and mismatched values is generated.
879
Michael Foordabd91d52010-03-20 18:09:14 +0000880 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000881
Raymond Hettinger35a88362009-04-09 00:08:24 +0000882 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000883
884
885 .. method:: assertListEqual(list1, list2, msg=None)
886 assertTupleEqual(tuple1, tuple2, msg=None)
887
888 Tests that two lists or tuples are equal. If not an error message is
889 constructed that shows only the differences between the two. An error
890 is also raised if either of the parameters are of the wrong type.
Michael Foord02834952010-02-08 23:10:39 +0000891 These methods are used by default when comparing lists or tuples with
892 :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000893
Michael Foordabd91d52010-03-20 18:09:14 +0000894 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000895
Raymond Hettinger35a88362009-04-09 00:08:24 +0000896 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000897
898
899 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
900
901 Tests that two sequences are equal. If a *seq_type* is supplied, both
902 *seq1* and *seq2* must be instances of *seq_type* or a failure will
903 be raised. If the sequences are different an error message is
904 constructed that shows the difference between the two.
905
Michael Foordabd91d52010-03-20 18:09:14 +0000906 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000907
908 This method is used to implement :meth:`assertListEqual` and
909 :meth:`assertTupleEqual`.
910
Raymond Hettinger35a88362009-04-09 00:08:24 +0000911 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000912
Benjamin Peterson52baa292009-03-24 00:56:30 +0000913
Georg Brandl7f01a132009-09-16 15:58:14 +0000914 .. method:: assertRaises(exception, callable, *args, **kwds)
915 failUnlessRaises(exception, callable, *args, **kwds)
916 assertRaises(exception)
917 failUnlessRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000918
919 Test that an exception is raised when *callable* is called with any
920 positional or keyword arguments that are also passed to
921 :meth:`assertRaises`. The test passes if *exception* is raised, is an
922 error if another exception is raised, or fails if no exception is raised.
923 To catch any of a group of exceptions, a tuple containing the exception
924 classes may be passed as *exception*.
925
Georg Brandl7f01a132009-09-16 15:58:14 +0000926 If only the *exception* argument is given, returns a context manager so
927 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000928
Michael Foord41531f22010-02-05 21:13:40 +0000929 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000930 do_something()
931
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000932 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000933 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000934 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000935
Michael Foord41531f22010-02-05 21:13:40 +0000936 with self.assertRaises(SomeException) as cm:
937 do_something()
938
Ezio Melotti49008232010-02-08 21:57:48 +0000939 the_exception = cm.exception
Michael Foordb112a412010-02-05 23:32:33 +0000940 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000941
Ezio Melotti49008232010-02-08 21:57:48 +0000942 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000943 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000944
Ezio Melotti49008232010-02-08 21:57:48 +0000945 .. versionchanged:: 3.2
946 Added the :attr:`exception` attribute.
947
Raymond Hettinger35a88362009-04-09 00:08:24 +0000948 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000949 :meth:`failUnlessRaises`; use :meth:`assertRaises`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000950
Benjamin Peterson52baa292009-03-24 00:56:30 +0000951
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000952 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
953
954 Like :meth:`assertRaises` but also tests that *regexp* matches
955 on the string representation of the raised exception. *regexp* may be
956 a regular expression object or a string containing a regular expression
957 suitable for use by :func:`re.search`. Examples::
958
959 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
960 int, 'XYZ')
961
962 or::
963
964 with self.assertRaisesRegexp(ValueError, 'literal'):
965 int('XYZ')
966
Raymond Hettinger35a88362009-04-09 00:08:24 +0000967 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000968
969
Georg Brandl7f01a132009-09-16 15:58:14 +0000970 .. method:: assertIsNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000971
972 This signals a test failure if *expr* is not None.
973
Raymond Hettinger35a88362009-04-09 00:08:24 +0000974 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000975
976
Georg Brandl7f01a132009-09-16 15:58:14 +0000977 .. method:: assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000978
979 The inverse of the :meth:`assertIsNone` method.
980 This signals a test failure if *expr* is None.
981
Raymond Hettinger35a88362009-04-09 00:08:24 +0000982 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000983
984
Georg Brandl7f01a132009-09-16 15:58:14 +0000985 .. method:: assertIs(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000986
987 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
988 object.
989
Georg Brandl705d9d52009-05-05 09:29:50 +0000990 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000991
992
Georg Brandl7f01a132009-09-16 15:58:14 +0000993 .. method:: assertIsNot(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000994
995 The inverse of the :meth:`assertIs` method.
996 This signals a test failure if *expr1* and *expr2* evaluate to the same
997 object.
998
Georg Brandl705d9d52009-05-05 09:29:50 +0000999 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001000
1001
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001002 .. method:: assertIsInstance(obj, cls[, msg])
1003
1004 This signals a test failure if *obj* is not an instance of *cls* (which
1005 can be a class or a tuple of classes, as supported by :func:`isinstance`).
1006
1007 .. versionadded:: 3.2
1008
1009
1010 .. method:: assertNotIsInstance(obj, cls[, msg])
1011
1012 The inverse of the :meth:`assertIsInstance` method. This signals a test
1013 failure if *obj* is an instance of *cls*.
1014
1015 .. versionadded:: 3.2
1016
1017
Georg Brandl7f01a132009-09-16 15:58:14 +00001018 .. method:: assertFalse(expr, msg=None)
1019 failIf(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001020
1021 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001022 This signals a test failure if *expr* is true, with *msg* or :const:`None`
1023 for the error message.
1024
Raymond Hettinger35a88362009-04-09 00:08:24 +00001025 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +00001026 :meth:`failIf`; use :meth:`assertFalse`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001027
Benjamin Peterson52baa292009-03-24 00:56:30 +00001028
Georg Brandl7f01a132009-09-16 15:58:14 +00001029 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001030
1031 Signals a test failure unconditionally, with *msg* or :const:`None` for
1032 the error message.
1033
1034
1035 .. attribute:: failureException
1036
1037 This class attribute gives the exception raised by the test method. If a
1038 test framework needs to use a specialized exception, possibly to carry
1039 additional information, it must subclass this exception in order to "play
1040 fair" with the framework. The initial value of this attribute is
1041 :exc:`AssertionError`.
1042
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001043
1044 .. attribute:: longMessage
1045
1046 If set to True then any explicit failure message you pass in to the
1047 assert methods will be appended to the end of the normal failure message.
1048 The normal messages contain useful information about the objects involved,
1049 for example the message from assertEqual shows you the repr of the two
1050 unequal objects. Setting this attribute to True allows you to have a
1051 custom error message in addition to the normal one.
1052
1053 This attribute defaults to False, meaning that a custom message passed
1054 to an assert method will silence the normal message.
1055
1056 The class setting can be overridden in individual tests by assigning an
1057 instance attribute to True or False before calling the assert methods.
1058
Raymond Hettinger35a88362009-04-09 00:08:24 +00001059 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001060
1061
Benjamin Peterson52baa292009-03-24 00:56:30 +00001062 Testing frameworks can use the following methods to collect information on
1063 the test:
1064
1065
1066 .. method:: countTestCases()
1067
1068 Return the number of tests represented by this test object. For
1069 :class:`TestCase` instances, this will always be ``1``.
1070
1071
1072 .. method:: defaultTestResult()
1073
1074 Return an instance of the test result class that should be used for this
1075 test case class (if no other result instance is provided to the
1076 :meth:`run` method).
1077
1078 For :class:`TestCase` instances, this will always be an instance of
1079 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1080 as necessary.
1081
1082
1083 .. method:: id()
1084
1085 Return a string identifying the specific test case. This is usually the
1086 full name of the test method, including the module and class name.
1087
1088
1089 .. method:: shortDescription()
1090
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001091 Returns a description of the test, or :const:`None` if no description
1092 has been provided. The default implementation of this method
1093 returns the first line of the test method's docstring, if available,
Michael Foord34c94622010-02-10 15:51:42 +00001094 or :const:`None`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001095
Michael Foord34c94622010-02-10 15:51:42 +00001096 .. versionchanged:: 3.1,3.2
1097 In 3.1 this was changed to add the test name to the short description
1098 even in the presence of a docstring. This caused compatibility issues
1099 with unittest extensions and adding the test name was moved to the
1100 :class:`TextTestResult`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001101
1102 .. method:: addTypeEqualityFunc(typeobj, function)
1103
1104 Registers a type specific :meth:`assertEqual` equality checking
1105 function to be called by :meth:`assertEqual` when both objects it has
1106 been asked to compare are exactly *typeobj* (not subclasses).
1107 *function* must take two positional arguments and a third msg=None
1108 keyword argument just as :meth:`assertEqual` does. It must raise
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001109 ``self.failureException`` when inequality between the first two
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001110 parameters is detected.
1111
1112 One good use of custom equality checking functions for a type
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001113 is to raise ``self.failureException`` with an error message useful
1114 for debugging the problem by explaining the inequalities in detail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001115
Raymond Hettinger35a88362009-04-09 00:08:24 +00001116 .. versionadded:: 3.1
Georg Brandl116aa622007-08-15 14:28:22 +00001117
1118
Georg Brandl7f01a132009-09-16 15:58:14 +00001119 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001120
1121 Add a function to be called after :meth:`tearDown` to cleanup resources
1122 used during the test. Functions will be called in reverse order to the
1123 order they are added (LIFO). They are called with any arguments and
1124 keyword arguments passed into :meth:`addCleanup` when they are
1125 added.
1126
1127 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1128 then any cleanup functions added will still be called.
1129
Georg Brandl853947a2010-01-31 18:53:23 +00001130 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001131
1132
1133 .. method:: doCleanups()
1134
1135 This method is called uncoditionally after :meth:`tearDown`, or
1136 after :meth:`setUp` if :meth:`setUp` raises an exception.
1137
1138 It is responsible for calling all the cleanup functions added by
1139 :meth:`addCleanup`. If you need cleanup functions to be called
1140 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1141 yourself.
1142
1143 :meth:`doCleanups` pops methods off the stack of cleanup
1144 functions one at a time, so it can be called at any time.
1145
Georg Brandl853947a2010-01-31 18:53:23 +00001146 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001147
1148
Georg Brandl7f01a132009-09-16 15:58:14 +00001149.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001150
1151 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001152 allows the test runner to drive the test, but does not provide the methods
1153 which test code can use to check and report errors. This is used to create
1154 test cases using legacy test code, allowing it to be integrated into a
1155 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001156
1157
Benjamin Peterson52baa292009-03-24 00:56:30 +00001158.. _testsuite-objects:
1159
Benjamin Peterson52baa292009-03-24 00:56:30 +00001160Grouping tests
1161~~~~~~~~~~~~~~
1162
Georg Brandl7f01a132009-09-16 15:58:14 +00001163.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001164
1165 This class represents an aggregation of individual tests cases and test suites.
1166 The class presents the interface needed by the test runner to allow it to be run
1167 as any other test case. Running a :class:`TestSuite` instance is the same as
1168 iterating over the suite, running each test individually.
1169
1170 If *tests* is given, it must be an iterable of individual test cases or other
1171 test suites that will be used to build the suite initially. Additional methods
1172 are provided to add test cases and suites to the collection later on.
1173
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001174 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1175 they do not actually implement a test. Instead, they are used to aggregate
1176 tests into groups of tests that should be run together. Some additional
1177 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001178
1179
1180 .. method:: TestSuite.addTest(test)
1181
1182 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1183
1184
1185 .. method:: TestSuite.addTests(tests)
1186
1187 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1188 instances to this test suite.
1189
Benjamin Petersond2397752009-06-27 23:45:02 +00001190 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1191 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001192
1193 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1194
1195
1196 .. method:: run(result)
1197
1198 Run the tests associated with this suite, collecting the result into the
1199 test result object passed as *result*. Note that unlike
1200 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1201 be passed in.
1202
1203
1204 .. method:: debug()
1205
1206 Run the tests associated with this suite without collecting the
1207 result. This allows exceptions raised by the test to be propagated to the
1208 caller and can be used to support running tests under a debugger.
1209
1210
1211 .. method:: countTestCases()
1212
1213 Return the number of tests represented by this test object, including all
1214 individual tests and sub-suites.
1215
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001216
1217 .. method:: __iter__()
1218
1219 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1220 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1221 that this method maybe called several times on a single suite
1222 (for example when counting tests or comparing for equality)
1223 so the tests returned must be the same for repeated iterations.
1224
Georg Brandl853947a2010-01-31 18:53:23 +00001225 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001226 In earlier versions the :class:`TestSuite` accessed tests directly rather
1227 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1228 for providing tests.
1229
Benjamin Peterson52baa292009-03-24 00:56:30 +00001230 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1231 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1232
1233
Benjamin Peterson52baa292009-03-24 00:56:30 +00001234Loading and running tests
1235~~~~~~~~~~~~~~~~~~~~~~~~~
1236
Georg Brandl116aa622007-08-15 14:28:22 +00001237.. class:: TestLoader()
1238
Benjamin Peterson52baa292009-03-24 00:56:30 +00001239 The :class:`TestLoader` class is used to create test suites from classes and
1240 modules. Normally, there is no need to create an instance of this class; the
1241 :mod:`unittest` module provides an instance that can be shared as
1242 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1243 customization of some configurable properties.
1244
1245 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001246
Michael Foordabd91d52010-03-20 18:09:14 +00001247a
Benjamin Peterson52baa292009-03-24 00:56:30 +00001248 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001249
Benjamin Peterson52baa292009-03-24 00:56:30 +00001250 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1251 :class:`testCaseClass`.
1252
1253
1254 .. method:: loadTestsFromModule(module)
1255
1256 Return a suite of all tests cases contained in the given module. This
1257 method searches *module* for classes derived from :class:`TestCase` and
1258 creates an instance of the class for each test method defined for the
1259 class.
1260
Georg Brandle720c0a2009-04-27 16:20:50 +00001261 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001262
1263 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1264 convenient in sharing fixtures and helper functions, defining test
1265 methods on base classes that are not intended to be instantiated
1266 directly does not play well with this method. Doing so, however, can
1267 be useful when the fixtures are different and defined in subclasses.
1268
Benjamin Petersond2397752009-06-27 23:45:02 +00001269 If a module provides a ``load_tests`` function it will be called to
1270 load the tests. This allows modules to customize test loading.
1271 This is the `load_tests protocol`_.
1272
Georg Brandl853947a2010-01-31 18:53:23 +00001273 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001274 Support for ``load_tests`` added.
1275
Benjamin Peterson52baa292009-03-24 00:56:30 +00001276
Georg Brandl7f01a132009-09-16 15:58:14 +00001277 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001278
1279 Return a suite of all tests cases given a string specifier.
1280
1281 The specifier *name* is a "dotted name" that may resolve either to a
1282 module, a test case class, a test method within a test case class, a
1283 :class:`TestSuite` instance, or a callable object which returns a
1284 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1285 applied in the order listed here; that is, a method on a possible test
1286 case class will be picked up as "a test method within a test case class",
1287 rather than "a callable object".
1288
1289 For example, if you have a module :mod:`SampleTests` containing a
1290 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1291 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001292 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1293 return a suite which will run all three test methods. Using the specifier
1294 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1295 suite which will run only the :meth:`test_two` test method. The specifier
1296 can refer to modules and packages which have not been imported; they will
1297 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001298
1299 The method optionally resolves *name* relative to the given *module*.
1300
1301
Georg Brandl7f01a132009-09-16 15:58:14 +00001302 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001303
1304 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1305 than a single name. The return value is a test suite which supports all
1306 the tests defined for each name.
1307
1308
1309 .. method:: getTestCaseNames(testCaseClass)
1310
1311 Return a sorted sequence of method names found within *testCaseClass*;
1312 this should be a subclass of :class:`TestCase`.
1313
Benjamin Petersond2397752009-06-27 23:45:02 +00001314
1315 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1316
1317 Find and return all test modules from the specified start directory,
1318 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001319 *pattern* will be loaded. (Using shell style pattern matching.) Only
1320 module names that are importable (i.e. are valid Python identifiers) will
1321 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001322
1323 All test modules must be importable from the top level of the project. If
1324 the start directory is not the top level directory then the top level
1325 directory must be specified separately.
1326
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001327 If importing a module fails, for example due to a syntax error, then this
1328 will be recorded as a single error and discovery will continue.
1329
Benjamin Petersond2397752009-06-27 23:45:02 +00001330 If a test package name (directory with :file:`__init__.py`) matches the
1331 pattern then the package will be checked for a ``load_tests``
1332 function. If this exists then it will be called with *loader*, *tests*,
1333 *pattern*.
1334
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001335 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001336 ``load_tests`` is responsible for loading all tests in the package.
1337
1338 The pattern is deliberately not stored as a loader attribute so that
1339 packages can continue discovery themselves. *top_level_dir* is stored so
1340 ``load_tests`` does not need to pass this argument in to
1341 ``loader.discover()``.
1342
Georg Brandl853947a2010-01-31 18:53:23 +00001343 .. versionadded:: 3.2
1344
Benjamin Petersond2397752009-06-27 23:45:02 +00001345
Benjamin Peterson52baa292009-03-24 00:56:30 +00001346 The following attributes of a :class:`TestLoader` can be configured either by
1347 subclassing or assignment on an instance:
1348
1349
1350 .. attribute:: testMethodPrefix
1351
1352 String giving the prefix of method names which will be interpreted as test
1353 methods. The default value is ``'test'``.
1354
1355 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1356 methods.
1357
1358
1359 .. attribute:: sortTestMethodsUsing
1360
1361 Function to be used to compare method names when sorting them in
1362 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1363
1364
1365 .. attribute:: suiteClass
1366
1367 Callable object that constructs a test suite from a list of tests. No
1368 methods on the resulting object are needed. The default value is the
1369 :class:`TestSuite` class.
1370
1371 This affects all the :meth:`loadTestsFrom\*` methods.
1372
1373
Benjamin Peterson52baa292009-03-24 00:56:30 +00001374.. class:: TestResult
1375
1376 This class is used to compile information about which tests have succeeded
1377 and which have failed.
1378
1379 A :class:`TestResult` object stores the results of a set of tests. The
1380 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1381 properly recorded; test authors do not need to worry about recording the
1382 outcome of tests.
1383
1384 Testing frameworks built on top of :mod:`unittest` may want access to the
1385 :class:`TestResult` object generated by running a set of tests for reporting
1386 purposes; a :class:`TestResult` instance is returned by the
1387 :meth:`TestRunner.run` method for this purpose.
1388
1389 :class:`TestResult` instances have the following attributes that will be of
1390 interest when inspecting the results of running a set of tests:
1391
1392
1393 .. attribute:: errors
1394
1395 A list containing 2-tuples of :class:`TestCase` instances and strings
1396 holding formatted tracebacks. Each tuple represents a test which raised an
1397 unexpected exception.
1398
Benjamin Peterson52baa292009-03-24 00:56:30 +00001399 .. attribute:: failures
1400
1401 A list containing 2-tuples of :class:`TestCase` instances and strings
1402 holding formatted tracebacks. Each tuple represents a test where a failure
1403 was explicitly signalled using the :meth:`TestCase.fail\*` or
1404 :meth:`TestCase.assert\*` methods.
1405
Benjamin Peterson52baa292009-03-24 00:56:30 +00001406 .. attribute:: skipped
1407
1408 A list containing 2-tuples of :class:`TestCase` instances and strings
1409 holding the reason for skipping the test.
1410
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001411 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001412
1413 .. attribute:: expectedFailures
1414
1415 A list contaning 2-tuples of :class:`TestCase` instances and strings
1416 holding formatted tracebacks. Each tuple represents a expected failures
1417 of the test case.
1418
1419 .. attribute:: unexpectedSuccesses
1420
1421 A list containing :class:`TestCase` instances that were marked as expected
1422 failures, but succeeded.
1423
1424 .. attribute:: shouldStop
1425
1426 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1427
1428
1429 .. attribute:: testsRun
1430
1431 The total number of tests run so far.
1432
1433
1434 .. method:: wasSuccessful()
1435
1436 Return :const:`True` if all tests run so far have passed, otherwise returns
1437 :const:`False`.
1438
1439
1440 .. method:: stop()
1441
1442 This method can be called to signal that the set of tests being run should
1443 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1444 :class:`TestRunner` objects should respect this flag and return without
1445 running any additional tests.
1446
1447 For example, this feature is used by the :class:`TextTestRunner` class to
1448 stop the test framework when the user signals an interrupt from the
1449 keyboard. Interactive tools which provide :class:`TestRunner`
1450 implementations can use this in a similar manner.
1451
1452 The following methods of the :class:`TestResult` class are used to maintain
1453 the internal data structures, and may be extended in subclasses to support
1454 additional reporting requirements. This is particularly useful in building
1455 tools which support interactive reporting while tests are being run.
1456
1457
1458 .. method:: startTest(test)
1459
1460 Called when the test case *test* is about to be run.
1461
1462 The default implementation simply increments the instance's :attr:`testsRun`
1463 counter.
1464
1465
1466 .. method:: stopTest(test)
1467
1468 Called after the test case *test* has been executed, regardless of the
1469 outcome.
1470
1471 The default implementation does nothing.
1472
1473
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001474 .. method:: startTestRun(test)
1475
1476 Called once before any tests are executed.
1477
Georg Brandl853947a2010-01-31 18:53:23 +00001478 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001479
1480
1481 .. method:: stopTestRun(test)
1482
Ezio Melotti176d6c42010-01-27 20:58:07 +00001483 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001484
Georg Brandl853947a2010-01-31 18:53:23 +00001485 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001486
1487
Benjamin Peterson52baa292009-03-24 00:56:30 +00001488 .. method:: addError(test, err)
1489
1490 Called when the test case *test* raises an unexpected exception *err* is a
1491 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1492 traceback)``.
1493
1494 The default implementation appends a tuple ``(test, formatted_err)`` to
1495 the instance's :attr:`errors` attribute, where *formatted_err* is a
1496 formatted traceback derived from *err*.
1497
1498
1499 .. method:: addFailure(test, err)
1500
Benjamin Petersond2397752009-06-27 23:45:02 +00001501 Called when the test case *test* signals a failure. *err* is a tuple of
1502 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001503
1504 The default implementation appends a tuple ``(test, formatted_err)`` to
1505 the instance's :attr:`failures` attribute, where *formatted_err* is a
1506 formatted traceback derived from *err*.
1507
1508
1509 .. method:: addSuccess(test)
1510
1511 Called when the test case *test* succeeds.
1512
1513 The default implementation does nothing.
1514
1515
1516 .. method:: addSkip(test, reason)
1517
1518 Called when the test case *test* is skipped. *reason* is the reason the
1519 test gave for skipping.
1520
1521 The default implementation appends a tuple ``(test, reason)`` to the
1522 instance's :attr:`skipped` attribute.
1523
1524
1525 .. method:: addExpectedFailure(test, err)
1526
1527 Called when the test case *test* fails, but was marked with the
1528 :func:`expectedFailure` decorator.
1529
1530 The default implementation appends a tuple ``(test, formatted_err)`` to
1531 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1532 is a formatted traceback derived from *err*.
1533
1534
1535 .. method:: addUnexpectedSuccess(test)
1536
1537 Called when the test case *test* was marked with the
1538 :func:`expectedFailure` decorator, but succeeded.
1539
1540 The default implementation appends the test to the instance's
1541 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001542
Michael Foord34c94622010-02-10 15:51:42 +00001543.. class:: TextTestResult(stream, descriptions, verbosity)
1544
1545 A concrete implementation of :class:`TestResult` used by the
1546 :class:`TextTestRunner`.
1547
1548 .. versionadded:: 3.2
1549 This class was previously named ``_TextTestResult``. The old name still
1550 exists as an alias but is deprecated.
Georg Brandl116aa622007-08-15 14:28:22 +00001551
1552.. data:: defaultTestLoader
1553
1554 Instance of the :class:`TestLoader` class intended to be shared. If no
1555 customization of the :class:`TestLoader` is needed, this instance can be used
1556 instead of repeatedly creating new instances.
1557
1558
Michael Foord34c94622010-02-10 15:51:42 +00001559.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001560
1561 A basic test runner implementation which prints results on standard error. It
1562 has a few configurable parameters, but is essentially very simple. Graphical
1563 applications which run test suites should provide alternate implementations.
1564
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001565 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001566
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001567 This method returns the instance of ``TestResult`` used by :meth:`run`.
1568 It is not intended to be called directly, but can be overridden in
1569 subclasses to provide a custom ``TestResult``.
1570
Michael Foord34c94622010-02-10 15:51:42 +00001571 ``_makeResult()`` instantiates the class or callable passed in the
1572 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
1573 defaults to :class::`TextTestResult` if no ``resultclass`` is provided.
1574 The result class is instantiated with the following arguments::
1575
1576 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001577
Georg Brandl7f01a132009-09-16 15:58:14 +00001578.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001579
1580 A command-line program that runs a set of tests; this is primarily for making
1581 test modules conveniently executable. The simplest use for this function is to
1582 include the following line at the end of a test script::
1583
1584 if __name__ == '__main__':
1585 unittest.main()
1586
Benjamin Petersond2397752009-06-27 23:45:02 +00001587 You can run tests with more detailed information by passing in the verbosity
1588 argument::
1589
1590 if __name__ == '__main__':
1591 unittest.main(verbosity=2)
1592
Georg Brandl116aa622007-08-15 14:28:22 +00001593 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001594 created instance of it. By default ``main`` calls :func:`sys.exit` with
1595 an exit code indicating success or failure of the tests run.
1596
1597 ``main`` supports being used from the interactive interpreter by passing in the
1598 argument ``exit=False``. This displays the result on standard output without
1599 calling :func:`sys.exit`::
1600
1601 >>> from unittest import main
1602 >>> main(module='test_module', exit=False)
1603
1604 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1605 This stores the result of the tests run as the ``result`` attribute.
1606
Georg Brandl853947a2010-01-31 18:53:23 +00001607 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001608 The ``exit`` and ``verbosity`` parameters were added.
1609
1610
1611load_tests Protocol
1612###################
1613
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001614
Georg Brandl853947a2010-01-31 18:53:23 +00001615.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001616
1617
Benjamin Petersond2397752009-06-27 23:45:02 +00001618Modules or packages can customize how tests are loaded from them during normal
1619test runs or test discovery by implementing a function called ``load_tests``.
1620
1621If a test module defines ``load_tests`` it will be called by
1622:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1623
1624 load_tests(loader, standard_tests, None)
1625
1626It should return a :class:`TestSuite`.
1627
1628*loader* is the instance of :class:`TestLoader` doing the loading.
1629*standard_tests* are the tests that would be loaded by default from the
1630module. It is common for test modules to only want to add or remove tests
1631from the standard set of tests.
1632The third argument is used when loading packages as part of test discovery.
1633
1634A typical ``load_tests`` function that loads tests from a specific set of
1635:class:`TestCase` classes may look like::
1636
1637 test_cases = (TestCase1, TestCase2, TestCase3)
1638
1639 def load_tests(loader, tests, pattern):
1640 suite = TestSuite()
1641 for test_class in test_cases:
1642 tests = loader.loadTestsFromTestCase(test_class)
1643 suite.addTests(tests)
1644 return suite
1645
1646If discovery is started, either from the command line or by calling
1647:meth:`TestLoader.discover`, with a pattern that matches a package
1648name then the package :file:`__init__.py` will be checked for ``load_tests``.
1649
1650.. note::
1651
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001652 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00001653 that start with 'test' but *won't* match any test directories.
1654
1655 A pattern like 'test*' will match test packages as well as
1656 modules.
1657
1658If the package :file:`__init__.py` defines ``load_tests`` then it will be
1659called and discovery not continued into the package. ``load_tests``
1660is called with the following arguments::
1661
1662 load_tests(loader, standard_tests, pattern)
1663
1664This should return a :class:`TestSuite` representing all the tests
1665from the package. (``standard_tests`` will only contain tests
1666collected from :file:`__init__.py`.)
1667
1668Because the pattern is passed into ``load_tests`` the package is free to
1669continue (and potentially modify) test discovery. A 'do nothing'
1670``load_tests`` function for a test package would look like::
1671
1672 def load_tests(loader, standard_tests, pattern):
1673 # top level directory cached on loader instance
1674 this_dir = os.path.dirname(__file__)
1675 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1676 standard_tests.addTests(package_tests)
1677 return standard_tests