blob: 7dc85954b61f48d339f11962c37fb2e2a336e1aa [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
Benjamin Petersonb48af542010-04-11 20:43:16 +000077 `unittest2: A backport of new unittest features for Python 2.4-2.6 <http://pypi.python.org/pypi/unittest2>`_
78 Many new features were added to unittest in Python 2.7, including test
79 discovery. unittest2 allows you to use these features with earlier
80 versions of Python.
81
Georg Brandl116aa622007-08-15 14:28:22 +000082 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000083 Kent Beck's original paper on testing frameworks using the pattern shared
84 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000085
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000086 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000087 Third-party unittest frameworks with a lighter-weight syntax for writing
88 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000089
Benjamin Petersonb48af542010-04-11 20:43:16 +000090 `The Python Testing Tools Taxonomy <http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy>`_
91 An extensive list of Python testing tools including functional testing
92 frameworks and mock object libraries.
Benjamin Petersond2397752009-06-27 23:45:02 +000093
Benjamin Petersonb48af542010-04-11 20:43:16 +000094 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
95 A special-interest-group for discussion of testing, and testing tools,
96 in Python.
Benjamin Petersond2397752009-06-27 23:45:02 +000097
Georg Brandl116aa622007-08-15 14:28:22 +000098.. _unittest-minimal-example:
99
100Basic example
101-------------
102
103The :mod:`unittest` module provides a rich set of tools for constructing and
104running tests. This section demonstrates that a small subset of the tools
105suffice to meet the needs of most users.
106
107Here is a short script to test three functions from the :mod:`random` module::
108
109 import random
110 import unittest
111
112 class TestSequenceFunctions(unittest.TestCase):
113
114 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000115 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +0000116
Benjamin Peterson52baa292009-03-24 00:56:30 +0000117 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000118 # make sure the shuffled sequence does not lose any elements
119 random.shuffle(self.seq)
120 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000121 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +0000122
Benjamin Peterson847a4112010-03-14 15:04:17 +0000123 # should raise an exception for an immutable sequence
124 self.assertRaises(TypeError, random.shuffle, (1,2,3))
125
Benjamin Peterson52baa292009-03-24 00:56:30 +0000126 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000127 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000128 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000129
Benjamin Peterson52baa292009-03-24 00:56:30 +0000130 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000131 with self.assertRaises(ValueError):
132 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000133 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000134 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000135
136 if __name__ == '__main__':
137 unittest.main()
138
Benjamin Peterson52baa292009-03-24 00:56:30 +0000139A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000140individual tests are defined with methods whose names start with the letters
141``test``. This naming convention informs the test runner about which methods
142represent tests.
143
Benjamin Peterson52baa292009-03-24 00:56:30 +0000144The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000145expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000146:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
147These methods are used instead of the :keyword:`assert` statement so the test
148runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000149
Benjamin Peterson52baa292009-03-24 00:56:30 +0000150When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
151method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
152defined, the test runner will invoke that method after each test. In the
153example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
154test.
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156The final block shows a simple way to run the tests. :func:`unittest.main`
157provides a command line interface to the test script. When run from the command
158line, the above script produces an output that looks like this::
159
160 ...
161 ----------------------------------------------------------------------
162 Ran 3 tests in 0.000s
163
164 OK
165
166Instead of :func:`unittest.main`, there are other ways to run the tests with a
167finer level of control, less terse output, and no requirement to be run from the
168command line. For example, the last two lines may be replaced with::
169
170 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
171 unittest.TextTestRunner(verbosity=2).run(suite)
172
173Running the revised script from the interpreter or another script produces the
174following output::
175
Ezio Melottid59e44a2010-02-28 03:46:13 +0000176 test_choice (__main__.TestSequenceFunctions) ... ok
177 test_sample (__main__.TestSequenceFunctions) ... ok
178 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180 ----------------------------------------------------------------------
181 Ran 3 tests in 0.110s
182
183 OK
184
185The above examples show the most commonly used :mod:`unittest` features which
186are sufficient to meet many everyday testing needs. The remainder of the
187documentation explores the full feature set from first principles.
188
Benjamin Petersonb48af542010-04-11 20:43:16 +0000189
190.. _unittest-command-line-interface:
191
192Command Line Interface
193----------------------
194
195The unittest module can be used from the command line to run tests from
196modules, classes or even individual test methods::
197
198 python -m unittest test_module1 test_module2
199 python -m unittest test_module.TestClass
200 python -m unittest test_module.TestClass.test_method
201
202You can pass in a list with any combination of module names, and fully
203qualified class or method names.
204
205You can run tests with more detail (higher verbosity) by passing in the -v flag::
206
207 python -m unittest -v test_module
208
209For a list of all the command line options::
210
211 python -m unittest -h
212
213.. versionchanged:: 3.2
214 In earlier versions it was only possible to run individual test methods and
215 not modules or classes.
216
217
218failfast, catch and buffer command line options
219~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
220
221unittest supports three command options.
222
223* -f / --failfast
224
225 Stop the test run on the first error or failure.
226
227* -c / --catch
228
229 Control-c during the test run waits for the current test to end and then
230 reports all the results so far. A second control-c raises the normal
231 ``KeyboardInterrupt`` exception.
232
233 See `Signal Handling`_ for the functions that provide this functionality.
234
235* -b / --buffer
236
237 The standard out and standard error streams are buffered during the test
238 run. Output during a passing test is discarded. Output is echoed normally
239 on test fail or error and is added to the failure messages.
240
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000241.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000242 The command line options ``-c``, ``-b`` and ``-f`` where added.
243
244The command line can also be used for test discovery, for running all of the
245tests in a project or just a subset.
246
247
248.. _unittest-test-discovery:
249
250Test Discovery
251--------------
252
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000253.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000254
255Unittest supports simple test discovery. For a project's tests to be
256compatible with test discovery they must all be importable from the top level
257directory of the project (in other words, they must all be in Python packages).
258
259Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
260used from the command line. The basic command line usage is::
261
262 cd project_directory
263 python -m unittest discover
264
265The ``discover`` sub-command has the following options:
266
267 -v, --verbose Verbose output
268 -s directory Directory to start discovery ('.' default)
269 -p pattern Pattern to match test files ('test*.py' default)
270 -t directory Top level directory of project (default to
271 start directory)
272
273The -s, -p, & -t options can be passsed in as positional arguments. The
274following two command lines are equivalent::
275
276 python -m unittest discover -s project_directory -p '*_test.py'
277 python -m unittest discover project_directory '*_test.py'
278
279Test modules and packages can customize test loading and discovery by through
280the `load_tests protocol`_.
281
282
Georg Brandl116aa622007-08-15 14:28:22 +0000283.. _organizing-tests:
284
285Organizing test code
286--------------------
287
288The basic building blocks of unit testing are :dfn:`test cases` --- single
289scenarios that must be set up and checked for correctness. In :mod:`unittest`,
290test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
291class. To make your own test cases you must write subclasses of
292:class:`TestCase`, or use :class:`FunctionTestCase`.
293
294An instance of a :class:`TestCase`\ -derived class is an object that can
295completely run a single test method, together with optional set-up and tidy-up
296code.
297
298The testing code of a :class:`TestCase` instance should be entirely self
299contained, such that it can be run either in isolation or in arbitrary
300combination with any number of other test cases.
301
Benjamin Peterson52baa292009-03-24 00:56:30 +0000302The simplest :class:`TestCase` subclass will simply override the
303:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305 import unittest
306
307 class DefaultWidgetSizeTestCase(unittest.TestCase):
308 def runTest(self):
309 widget = Widget('The widget')
310 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
311
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000312Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000313methods provided by the :class:`TestCase` base class. If the test fails, an
314exception will be raised, and :mod:`unittest` will identify the test case as a
315:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
316helps you identify where the problem is: :dfn:`failures` are caused by incorrect
317results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
318code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000319
320The way to run a test case will be described later. For now, note that to
321construct an instance of such a test case, we call its constructor without
322arguments::
323
324 testCase = DefaultWidgetSizeTestCase()
325
326Now, such test cases can be numerous, and their set-up can be repetitive. In
327the above case, constructing a :class:`Widget` in each of 100 Widget test case
328subclasses would mean unsightly duplication.
329
330Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000331:meth:`~TestCase.setUp`, which the testing framework will automatically call for
332us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334 import unittest
335
336 class SimpleWidgetTestCase(unittest.TestCase):
337 def setUp(self):
338 self.widget = Widget('The widget')
339
340 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
341 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000342 self.assertEqual(self.widget.size(), (50,50),
343 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000344
345 class WidgetResizeTestCase(SimpleWidgetTestCase):
346 def runTest(self):
347 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000348 self.assertEqual(self.widget.size(), (100,150),
349 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000350
Benjamin Peterson52baa292009-03-24 00:56:30 +0000351If the :meth:`~TestCase.setUp` method raises an exception while the test is
352running, the framework will consider the test to have suffered an error, and the
353:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000354
Benjamin Peterson52baa292009-03-24 00:56:30 +0000355Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
356after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000357
358 import unittest
359
360 class SimpleWidgetTestCase(unittest.TestCase):
361 def setUp(self):
362 self.widget = Widget('The widget')
363
364 def tearDown(self):
365 self.widget.dispose()
366 self.widget = None
367
Benjamin Peterson52baa292009-03-24 00:56:30 +0000368If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
369be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
371Such a working environment for the testing code is called a :dfn:`fixture`.
372
373Often, many small test cases will use the same fixture. In this case, we would
374end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
375classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000376discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
377mechanism::
378
379 import unittest
380
381 class WidgetTestCase(unittest.TestCase):
382 def setUp(self):
383 self.widget = Widget('The widget')
384
385 def tearDown(self):
386 self.widget.dispose()
387 self.widget = None
388
Ezio Melottid59e44a2010-02-28 03:46:13 +0000389 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000390 self.assertEqual(self.widget.size(), (50,50),
391 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000392
Ezio Melottid59e44a2010-02-28 03:46:13 +0000393 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000394 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000395 self.assertEqual(self.widget.size(), (100,150),
396 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000397
Benjamin Peterson52baa292009-03-24 00:56:30 +0000398Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
399provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000400the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000401separately for each instance. When creating an instance we must specify the
402test method it is to run. We do this by passing the method name in the
403constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000404
Ezio Melottid59e44a2010-02-28 03:46:13 +0000405 defaultSizeTestCase = WidgetTestCase('test_default_size')
406 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000407
408Test case instances are grouped together according to the features they test.
409:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
410represented by :mod:`unittest`'s :class:`TestSuite` class::
411
412 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000413 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
414 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416For the ease of running tests, as we will see later, it is a good idea to
417provide in each test module a callable object that returns a pre-built test
418suite::
419
420 def suite():
421 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000422 suite.addTest(WidgetTestCase('test_default_size'))
423 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000424 return suite
425
426or even::
427
428 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000429 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431 return unittest.TestSuite(map(WidgetTestCase, tests))
432
433Since it is a common pattern to create a :class:`TestCase` subclass with many
434similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
435class that can be used to automate the process of creating a test suite and
436populating it with individual tests. For example, ::
437
438 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
439
Ezio Melottid59e44a2010-02-28 03:46:13 +0000440will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
441``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000442name prefix to identify test methods automatically.
443
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000444Note that the order in which the various test cases will be run is
445determined by sorting the test function names with respect to the
446built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000447
448Often it is desirable to group suites of test cases together, so as to run tests
449for the whole system at once. This is easy, since :class:`TestSuite` instances
450can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
451added to a :class:`TestSuite`::
452
453 suite1 = module1.TheTestSuite()
454 suite2 = module2.TheTestSuite()
455 alltests = unittest.TestSuite([suite1, suite2])
456
457You can place the definitions of test cases and test suites in the same modules
458as the code they are to test (such as :file:`widget.py`), but there are several
459advantages to placing the test code in a separate module, such as
460:file:`test_widget.py`:
461
462* The test module can be run standalone from the command line.
463
464* The test code can more easily be separated from shipped code.
465
466* There is less temptation to change test code to fit the code it tests without
467 a good reason.
468
469* Test code should be modified much less frequently than the code it tests.
470
471* Tested code can be refactored more easily.
472
473* Tests for modules written in C must be in separate modules anyway, so why not
474 be consistent?
475
476* If the testing strategy changes, there is no need to change the source code.
477
478
479.. _legacy-unit-tests:
480
481Re-using old test code
482----------------------
483
484Some users will find that they have existing test code that they would like to
485run from :mod:`unittest`, without converting every old test function to a
486:class:`TestCase` subclass.
487
488For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
489This subclass of :class:`TestCase` can be used to wrap an existing test
490function. Set-up and tear-down functions can also be provided.
491
492Given the following test function::
493
494 def testSomething():
495 something = makeSomething()
496 assert something.name is not None
497 # ...
498
499one can create an equivalent test case instance as follows::
500
501 testcase = unittest.FunctionTestCase(testSomething)
502
503If there are additional set-up and tear-down methods that should be called as
504part of the test case's operation, they can also be provided like so::
505
506 testcase = unittest.FunctionTestCase(testSomething,
507 setUp=makeSomethingDB,
508 tearDown=deleteSomethingDB)
509
510To make migrating existing test suites easier, :mod:`unittest` supports tests
511raising :exc:`AssertionError` to indicate test failure. However, it is
512recommended that you use the explicit :meth:`TestCase.fail\*` and
513:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
514may treat :exc:`AssertionError` differently.
515
516.. note::
517
Benjamin Petersond2397752009-06-27 23:45:02 +0000518 Even though :class:`FunctionTestCase` can be used to quickly convert an
519 existing test base over to a :mod:`unittest`\ -based system, this approach is
520 not recommended. Taking the time to set up proper :class:`TestCase`
521 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000522
Benjamin Peterson52baa292009-03-24 00:56:30 +0000523In some cases, the existing tests may have been written using the :mod:`doctest`
524module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
525automatically build :class:`unittest.TestSuite` instances from the existing
526:mod:`doctest`\ -based tests.
527
Georg Brandl116aa622007-08-15 14:28:22 +0000528
Benjamin Peterson5254c042009-03-23 22:25:03 +0000529.. _unittest-skipping:
530
531Skipping tests and expected failures
532------------------------------------
533
Michael Foordf5c851a2010-02-05 21:48:03 +0000534.. versionadded:: 3.1
535
Benjamin Peterson5254c042009-03-23 22:25:03 +0000536Unittest supports skipping individual test methods and even whole classes of
537tests. In addition, it supports marking a test as a "expected failure," a test
538that is broken and will fail, but shouldn't be counted as a failure on a
539:class:`TestResult`.
540
541Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
542or one of its conditional variants.
543
544Basic skipping looks like this: ::
545
546 class MyTestCase(unittest.TestCase):
547
548 @unittest.skip("demonstrating skipping")
549 def test_nothing(self):
550 self.fail("shouldn't happen")
551
Benjamin Petersond2397752009-06-27 23:45:02 +0000552 @unittest.skipIf(mylib.__version__ < (1, 3),
553 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000554 def test_format(self):
555 # Tests that work for only a certain version of the library.
556 pass
557
558 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
559 def test_windows_support(self):
560 # windows specific testing code
561 pass
562
Benjamin Peterson5254c042009-03-23 22:25:03 +0000563This is the output of running the example above in verbose mode: ::
564
Benjamin Petersonded31c42009-03-30 15:04:16 +0000565 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000566 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000567 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000568
569 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000570 Ran 3 tests in 0.005s
571
572 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000573
574Classes can be skipped just like methods: ::
575
576 @skip("showing class skipping")
577 class MySkippedTestCase(unittest.TestCase):
578 def test_not_run(self):
579 pass
580
Benjamin Peterson52baa292009-03-24 00:56:30 +0000581:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
582that needs to be set up is not available.
583
Benjamin Peterson5254c042009-03-23 22:25:03 +0000584Expected failures use the :func:`expectedFailure` decorator. ::
585
586 class ExpectedFailureTestCase(unittest.TestCase):
587 @unittest.expectedFailure
588 def test_fail(self):
589 self.assertEqual(1, 0, "broken")
590
591It's easy to roll your own skipping decorators by making a decorator that calls
592:func:`skip` on the test when it wants it to be skipped. This decorator skips
593the test unless the passed object has a certain attribute: ::
594
595 def skipUnlessHasattr(obj, attr):
596 if hasattr(obj, attr):
597 return lambda func: func
598 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
599
600The following decorators implement test skipping and expected failures:
601
602.. function:: skip(reason)
603
604 Unconditionally skip the decorated test. *reason* should describe why the
605 test is being skipped.
606
607.. function:: skipIf(condition, reason)
608
609 Skip the decorated test if *condition* is true.
610
611.. function:: skipUnless(condition, reason)
612
613 Skip the decoratored test unless *condition* is true.
614
615.. function:: expectedFailure
616
617 Mark the test as an expected failure. If the test fails when run, the test
618 is not counted as a failure.
619
Benjamin Petersonb48af542010-04-11 20:43:16 +0000620Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
621Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
622
Benjamin Peterson5254c042009-03-23 22:25:03 +0000623
Georg Brandl116aa622007-08-15 14:28:22 +0000624.. _unittest-contents:
625
626Classes and functions
627---------------------
628
Benjamin Peterson52baa292009-03-24 00:56:30 +0000629This section describes in depth the API of :mod:`unittest`.
630
631
632.. _testcase-objects:
633
634Test cases
635~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000636
Georg Brandl7f01a132009-09-16 15:58:14 +0000637.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000638
639 Instances of the :class:`TestCase` class represent the smallest testable units
640 in the :mod:`unittest` universe. This class is intended to be used as a base
641 class, with specific tests being implemented by concrete subclasses. This class
642 implements the interface needed by the test runner to allow it to drive the
643 test, and methods that the test code can use to check for and report various
644 kinds of failure.
645
646 Each instance of :class:`TestCase` will run a single test method: the method
647 named *methodName*. If you remember, we had an earlier example that went
648 something like this::
649
650 def suite():
651 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000652 suite.addTest(WidgetTestCase('test_default_size'))
653 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000654 return suite
655
656 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
657 single test.
658
Benjamin Peterson52baa292009-03-24 00:56:30 +0000659 *methodName* defaults to :meth:`runTest`.
660
661 :class:`TestCase` instances provide three groups of methods: one group used
662 to run the test, another used by the test implementation to check conditions
663 and report failures, and some inquiry methods allowing information about the
664 test itself to be gathered.
665
666 Methods in the first group (running the test) are:
667
668
669 .. method:: setUp()
670
671 Method called to prepare the test fixture. This is called immediately
672 before calling the test method; any exception raised by this method will
673 be considered an error rather than a test failure. The default
674 implementation does nothing.
675
676
677 .. method:: tearDown()
678
679 Method called immediately after the test method has been called and the
680 result recorded. This is called even if the test method raised an
681 exception, so the implementation in subclasses may need to be particularly
682 careful about checking internal state. Any exception raised by this
683 method will be considered an error rather than a test failure. This
684 method will only be called if the :meth:`setUp` succeeds, regardless of
685 the outcome of the test method. The default implementation does nothing.
686
687
Benjamin Petersonb48af542010-04-11 20:43:16 +0000688 .. method:: setUpClass()
689
690 A class method called before tests in an individual class run.
691 ``setUpClass`` is called with the class as the only argument
692 and must be decorated as a :func:`classmethod`::
693
694 @classmethod
695 def setUpClass(cls):
696 ...
697
698 See `Class and Module Fixtures`_ for more details.
699
700 .. versionadded:: 3.2
701
702
703 .. method:: tearDownClass()
704
705 A class method called after tests in an individual class have run.
706 ``tearDownClass`` is called with the class as the only argument
707 and must be decorated as a :meth:`classmethod`::
708
709 @classmethod
710 def tearDownClass(cls):
711 ...
712
713 See `Class and Module Fixtures`_ for more details.
714
715 .. versionadded:: 3.2
716
717
Georg Brandl7f01a132009-09-16 15:58:14 +0000718 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000719
720 Run the test, collecting the result into the test result object passed as
721 *result*. If *result* is omitted or :const:`None`, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000722 object is created (by calling the :meth:`defaultTestResult` method) and
723 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000724
725 The same effect may be had by simply calling the :class:`TestCase`
726 instance.
727
728
Benjamin Petersone549ead2009-03-28 21:42:05 +0000729 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000730
731 Calling this during the a test method or :meth:`setUp` skips the current
732 test. See :ref:`unittest-skipping` for more information.
733
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000734 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000735
Benjamin Peterson52baa292009-03-24 00:56:30 +0000736
737 .. method:: debug()
738
739 Run the test without collecting the result. This allows exceptions raised
740 by the test to be propagated to the caller, and can be used to support
741 running tests under a debugger.
742
743 The test code can use any of the following methods to check for and report
744 failures.
745
746
Georg Brandl7f01a132009-09-16 15:58:14 +0000747 .. method:: assertTrue(expr, msg=None)
748 assert_(expr, msg=None)
749 failUnless(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000750
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000751 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson52baa292009-03-24 00:56:30 +0000752 will be *msg* if given, otherwise it will be :const:`None`.
753
Raymond Hettinger35a88362009-04-09 00:08:24 +0000754 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000755 :meth:`failUnless`; use one of the ``assert`` variants.
Michael Foord34c94622010-02-10 15:51:42 +0000756 :meth:`assert_`; use :meth:`assertTrue`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000757
Benjamin Peterson52baa292009-03-24 00:56:30 +0000758
Georg Brandl7f01a132009-09-16 15:58:14 +0000759 .. method:: assertEqual(first, second, msg=None)
760 failUnlessEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000761
762 Test that *first* and *second* are equal. If the values do not compare
763 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000764 :const:`None`. Note that using :meth:`assertEqual` improves upon
765 doing the comparison as the first parameter to :meth:`assertTrue`: the
766 default value for *msg* include representations of both *first* and
767 *second*.
768
769 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000770 list, tuple, dict, set, frozenset or str or any type that a subclass
771 registers with :meth:`addTypeEqualityFunc` the type specific equality
772 function will be called in order to generate a more useful default
773 error message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000774
Raymond Hettinger35a88362009-04-09 00:08:24 +0000775 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000776 Added the automatic calling of type specific equality function.
777
Michael Foord28a817e2010-02-09 00:03:57 +0000778 .. versionchanged:: 3.2
779 :meth:`assertMultiLineEqual` added as the default type equality
780 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000781
Raymond Hettinger35a88362009-04-09 00:08:24 +0000782 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000783 :meth:`failUnlessEqual`; use :meth:`assertEqual`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000784
785
Georg Brandl7f01a132009-09-16 15:58:14 +0000786 .. method:: assertNotEqual(first, second, msg=None)
787 failIfEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000788
789 Test that *first* and *second* are not equal. If the values do compare
790 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000791 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
792 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson52baa292009-03-24 00:56:30 +0000793 default value for *msg* can be computed to include representations of both
794 *first* and *second*.
795
Raymond Hettinger35a88362009-04-09 00:08:24 +0000796 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000797 :meth:`failIfEqual`; use :meth:`assertNotEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000798
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000799
Benjamin Petersonb48af542010-04-11 20:43:16 +0000800 .. method:: assertAlmostEqual(first, second, *, places=7, msg=None, delta=None)
801 failUnlessAlmostEqual(first, second, *, places=7, msg=None, delta=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000802
803 Test that *first* and *second* are approximately equal by computing the
804 difference, rounding to the given number of decimal *places* (default 7),
805 and comparing to zero.
806
807 Note that comparing a given number of decimal places is not the same as
808 comparing a given number of significant digits. If the values do not
809 compare equal, the test will fail with the explanation given by *msg*, or
810 :const:`None`.
811
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000812 .. versionchanged:: 3.2
813 Objects that compare equal are automatically almost equal.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000814 Added the ``delta`` keyword argument.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000815
Raymond Hettinger35a88362009-04-09 00:08:24 +0000816 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000817 :meth:`failUnlessAlmostEqual`; use :meth:`assertAlmostEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000818
Benjamin Peterson52baa292009-03-24 00:56:30 +0000819
Benjamin Petersonb48af542010-04-11 20:43:16 +0000820 .. method:: assertNotAlmostEqual(first, second, *, places=7, msg=None, delta=None)
821 failIfAlmostEqual(first, second, *, places=7, msg=None, delta=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000822
823 Test that *first* and *second* are not approximately equal by computing
824 the difference, rounding to the given number of decimal *places* (default
825 7), and comparing to zero.
826
827 Note that comparing a given number of decimal places is not the same as
828 comparing a given number of significant digits. If the values do not
829 compare equal, the test will fail with the explanation given by *msg*, or
830 :const:`None`.
831
Benjamin Petersonb48af542010-04-11 20:43:16 +0000832 If *delta* is supplied instead of *places* then the the difference
833 between *first* and *second* must be more than *delta*.
834
835 Supplying both *delta* and *places* raises a ``TypeError``.
836
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000837 .. versionchanged:: 3.2
838 Objects that compare equal automatically fail.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000839 Added the ``delta`` keyword argument.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000840
Raymond Hettinger35a88362009-04-09 00:08:24 +0000841 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000842 :meth:`failIfAlmostEqual`; use :meth:`assertNotAlmostEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000843
844
845 .. method:: assertGreater(first, second, msg=None)
846 assertGreaterEqual(first, second, msg=None)
847 assertLess(first, second, msg=None)
848 assertLessEqual(first, second, msg=None)
849
850 Test that *first* is respectively >, >=, < or <= than *second* depending
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000851 on the method name. If not, the test will fail with an explanation
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000852 or with the explanation given by *msg*::
853
854 >>> self.assertGreaterEqual(3, 4)
855 AssertionError: "3" unexpectedly not greater than or equal to "4"
856
Raymond Hettinger35a88362009-04-09 00:08:24 +0000857 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000858
859
860 .. method:: assertMultiLineEqual(self, first, second, msg=None)
861
862 Test that the multiline string *first* is equal to the string *second*.
863 When not equal a diff of the two strings highlighting the differences
Michael Foord02834952010-02-08 23:10:39 +0000864 will be included in the error message. This method is used by default
865 when comparing strings with :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000866
Michael Foordabd91d52010-03-20 18:09:14 +0000867 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000868
Raymond Hettinger35a88362009-04-09 00:08:24 +0000869 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000870
871
Ezio Melotti732b6822010-01-16 19:40:06 +0000872 .. method:: assertRegexpMatches(text, regexp, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000873
874 Verifies that a *regexp* search matches *text*. Fails with an error
875 message including the pattern and the *text*. *regexp* may be
876 a regular expression object or a string containing a regular expression
877 suitable for use by :func:`re.search`.
878
Raymond Hettinger35a88362009-04-09 00:08:24 +0000879 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000880
881
Benjamin Petersonb48af542010-04-11 20:43:16 +0000882 .. method:: assertNotRegexpMatches(text, regexp, msg=None)
883
884 Verifies that a *regexp* search does not match *text*. Fails with an error
885 message including the pattern and the *text*. *regexp* may be
886 a regular expression object or a string containing a regular expression
887 suitable for use by :func:`re.search`.
888
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000889 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000890
891
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000892 .. method:: assertIn(first, second, msg=None)
893 assertNotIn(first, second, msg=None)
894
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000895 Tests that *first* is or is not in *second* with an explanatory error
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000896 message as appropriate.
897
Michael Foordabd91d52010-03-20 18:09:14 +0000898 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000899
Raymond Hettinger35a88362009-04-09 00:08:24 +0000900 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000901
902
Michael Foorde9abbee2010-02-05 20:54:27 +0000903 .. method:: assertSameElements(actual, expected, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000904
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000905 Test that sequence *expected* contains the same elements as *actual*,
906 regardless of their order. When they don't, an error message listing
907 the differences between the sequences will be generated.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000908
Michael Foorde9abbee2010-02-05 20:54:27 +0000909 Duplicate elements are ignored when comparing *actual* and *expected*.
910 It is the equivalent of ``assertEqual(set(expected), set(actual))``
Michael Foordabd91d52010-03-20 18:09:14 +0000911 but it works with sequences of unhashable objects as well. Because
912 duplicates are ignored, this method has been deprecated in favour of
913 :meth:`assertItemsEqual`.
Michael Foorde9abbee2010-02-05 20:54:27 +0000914
Michael Foordabd91d52010-03-20 18:09:14 +0000915 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000916
Raymond Hettinger35a88362009-04-09 00:08:24 +0000917 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000918
Michael Foordabd91d52010-03-20 18:09:14 +0000919 .. deprecated:: 3.2
920
921 .. method:: assertItemsEqual(actual, expected, msg=None)
922
923 Test that sequence *expected* contains the same elements as *actual*,
924 regardless of their order. When they don't, an error message listing the
925 differences between the sequences will be generated.
926
927 Duplicate elements are *not* ignored when comparing *actual* and
928 *expected*. It verifies if each element has the same count in both
929 sequences. It is the equivalent of ``assertEqual(sorted(expected),
930 sorted(actual))`` but it works with sequences of unhashable objects as
931 well.
932
933 If specified, *msg* will be used as the error message on failure.
934
935 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000936
937 .. method:: assertSetEqual(set1, set2, msg=None)
938
939 Tests that two sets are equal. If not, an error message is constructed
Michael Foord02834952010-02-08 23:10:39 +0000940 that lists the differences between the sets. This method is used by
941 default when comparing sets or frozensets with :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000942
943 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
944 method.
945
Michael Foordabd91d52010-03-20 18:09:14 +0000946 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000947
Raymond Hettinger35a88362009-04-09 00:08:24 +0000948 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000949
950
951 .. method:: assertDictEqual(expected, actual, msg=None)
952
953 Test that two dictionaries are equal. If not, an error message is
Michael Foord02834952010-02-08 23:10:39 +0000954 constructed that shows the differences in the dictionaries. This
955 method will be used by default to compare dictionaries in
956 calls to :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000957
Michael Foordabd91d52010-03-20 18:09:14 +0000958 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000959
Raymond Hettinger35a88362009-04-09 00:08:24 +0000960 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000961
962
963 .. method:: assertDictContainsSubset(expected, actual, msg=None)
964
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000965 Tests whether the key/value pairs in dictionary *actual* are a
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000966 superset of those in *expected*. If not, an error message listing
967 the missing keys and mismatched values is generated.
968
Michael Foordabd91d52010-03-20 18:09:14 +0000969 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000970
Raymond Hettinger35a88362009-04-09 00:08:24 +0000971 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000972
973
974 .. method:: assertListEqual(list1, list2, msg=None)
975 assertTupleEqual(tuple1, tuple2, msg=None)
976
977 Tests that two lists or tuples are equal. If not an error message is
978 constructed that shows only the differences between the two. An error
979 is also raised if either of the parameters are of the wrong type.
Michael Foord02834952010-02-08 23:10:39 +0000980 These methods are used by default when comparing lists or tuples with
981 :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000982
Michael Foordabd91d52010-03-20 18:09:14 +0000983 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000984
Raymond Hettinger35a88362009-04-09 00:08:24 +0000985 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000986
987
988 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
989
990 Tests that two sequences are equal. If a *seq_type* is supplied, both
991 *seq1* and *seq2* must be instances of *seq_type* or a failure will
992 be raised. If the sequences are different an error message is
993 constructed that shows the difference between the two.
994
Michael Foordabd91d52010-03-20 18:09:14 +0000995 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000996
997 This method is used to implement :meth:`assertListEqual` and
998 :meth:`assertTupleEqual`.
999
Raymond Hettinger35a88362009-04-09 00:08:24 +00001000 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001001
Benjamin Peterson52baa292009-03-24 00:56:30 +00001002
Georg Brandl7f01a132009-09-16 15:58:14 +00001003 .. method:: assertRaises(exception, callable, *args, **kwds)
1004 failUnlessRaises(exception, callable, *args, **kwds)
1005 assertRaises(exception)
1006 failUnlessRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001007
1008 Test that an exception is raised when *callable* is called with any
1009 positional or keyword arguments that are also passed to
1010 :meth:`assertRaises`. The test passes if *exception* is raised, is an
1011 error if another exception is raised, or fails if no exception is raised.
1012 To catch any of a group of exceptions, a tuple containing the exception
1013 classes may be passed as *exception*.
1014
Georg Brandl7f01a132009-09-16 15:58:14 +00001015 If only the *exception* argument is given, returns a context manager so
1016 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +00001017
Michael Foord41531f22010-02-05 21:13:40 +00001018 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +00001019 do_something()
1020
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00001021 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +00001022 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +00001023 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00001024
Michael Foord41531f22010-02-05 21:13:40 +00001025 with self.assertRaises(SomeException) as cm:
1026 do_something()
1027
Ezio Melotti49008232010-02-08 21:57:48 +00001028 the_exception = cm.exception
Michael Foordb112a412010-02-05 23:32:33 +00001029 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +00001030
Ezio Melotti49008232010-02-08 21:57:48 +00001031 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +00001032 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001033
Ezio Melotti49008232010-02-08 21:57:48 +00001034 .. versionchanged:: 3.2
1035 Added the :attr:`exception` attribute.
1036
Raymond Hettinger35a88362009-04-09 00:08:24 +00001037 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +00001038 :meth:`failUnlessRaises`; use :meth:`assertRaises`.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001039
Benjamin Peterson52baa292009-03-24 00:56:30 +00001040
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001041 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
1042
1043 Like :meth:`assertRaises` but also tests that *regexp* matches
1044 on the string representation of the raised exception. *regexp* may be
1045 a regular expression object or a string containing a regular expression
1046 suitable for use by :func:`re.search`. Examples::
1047
1048 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
1049 int, 'XYZ')
1050
1051 or::
1052
1053 with self.assertRaisesRegexp(ValueError, 'literal'):
1054 int('XYZ')
1055
Raymond Hettinger35a88362009-04-09 00:08:24 +00001056 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001057
1058
Georg Brandl7f01a132009-09-16 15:58:14 +00001059 .. method:: assertIsNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001060
1061 This signals a test failure if *expr* is not None.
1062
Raymond Hettinger35a88362009-04-09 00:08:24 +00001063 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001064
1065
Georg Brandl7f01a132009-09-16 15:58:14 +00001066 .. method:: assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001067
1068 The inverse of the :meth:`assertIsNone` method.
1069 This signals a test failure if *expr* is None.
1070
Raymond Hettinger35a88362009-04-09 00:08:24 +00001071 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001072
1073
Georg Brandl7f01a132009-09-16 15:58:14 +00001074 .. method:: assertIs(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001075
1076 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
1077 object.
1078
Georg Brandl705d9d52009-05-05 09:29:50 +00001079 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001080
1081
Georg Brandl7f01a132009-09-16 15:58:14 +00001082 .. method:: assertIsNot(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001083
1084 The inverse of the :meth:`assertIs` method.
1085 This signals a test failure if *expr1* and *expr2* evaluate to the same
1086 object.
1087
Georg Brandl705d9d52009-05-05 09:29:50 +00001088 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001089
1090
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001091 .. method:: assertIsInstance(obj, cls[, msg])
1092
1093 This signals a test failure if *obj* is not an instance of *cls* (which
1094 can be a class or a tuple of classes, as supported by :func:`isinstance`).
1095
1096 .. versionadded:: 3.2
1097
1098
1099 .. method:: assertNotIsInstance(obj, cls[, msg])
1100
1101 The inverse of the :meth:`assertIsInstance` method. This signals a test
1102 failure if *obj* is an instance of *cls*.
1103
1104 .. versionadded:: 3.2
1105
1106
Georg Brandl7f01a132009-09-16 15:58:14 +00001107 .. method:: assertFalse(expr, msg=None)
1108 failIf(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001109
1110 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001111 This signals a test failure if *expr* is true, with *msg* or :const:`None`
1112 for the error message.
1113
Raymond Hettinger35a88362009-04-09 00:08:24 +00001114 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +00001115 :meth:`failIf`; use :meth:`assertFalse`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001116
Benjamin Peterson52baa292009-03-24 00:56:30 +00001117
Georg Brandl7f01a132009-09-16 15:58:14 +00001118 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001119
1120 Signals a test failure unconditionally, with *msg* or :const:`None` for
1121 the error message.
1122
1123
1124 .. attribute:: failureException
1125
1126 This class attribute gives the exception raised by the test method. If a
1127 test framework needs to use a specialized exception, possibly to carry
1128 additional information, it must subclass this exception in order to "play
1129 fair" with the framework. The initial value of this attribute is
1130 :exc:`AssertionError`.
1131
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001132
1133 .. attribute:: longMessage
1134
1135 If set to True then any explicit failure message you pass in to the
1136 assert methods will be appended to the end of the normal failure message.
1137 The normal messages contain useful information about the objects involved,
1138 for example the message from assertEqual shows you the repr of the two
1139 unequal objects. Setting this attribute to True allows you to have a
1140 custom error message in addition to the normal one.
1141
1142 This attribute defaults to False, meaning that a custom message passed
1143 to an assert method will silence the normal message.
1144
1145 The class setting can be overridden in individual tests by assigning an
1146 instance attribute to True or False before calling the assert methods.
1147
Raymond Hettinger35a88362009-04-09 00:08:24 +00001148 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001149
1150
Benjamin Peterson52baa292009-03-24 00:56:30 +00001151 Testing frameworks can use the following methods to collect information on
1152 the test:
1153
1154
1155 .. method:: countTestCases()
1156
1157 Return the number of tests represented by this test object. For
1158 :class:`TestCase` instances, this will always be ``1``.
1159
1160
1161 .. method:: defaultTestResult()
1162
1163 Return an instance of the test result class that should be used for this
1164 test case class (if no other result instance is provided to the
1165 :meth:`run` method).
1166
1167 For :class:`TestCase` instances, this will always be an instance of
1168 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1169 as necessary.
1170
1171
1172 .. method:: id()
1173
1174 Return a string identifying the specific test case. This is usually the
1175 full name of the test method, including the module and class name.
1176
1177
1178 .. method:: shortDescription()
1179
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001180 Returns a description of the test, or :const:`None` if no description
1181 has been provided. The default implementation of this method
1182 returns the first line of the test method's docstring, if available,
Michael Foord34c94622010-02-10 15:51:42 +00001183 or :const:`None`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001184
Michael Foord34c94622010-02-10 15:51:42 +00001185 .. versionchanged:: 3.1,3.2
1186 In 3.1 this was changed to add the test name to the short description
1187 even in the presence of a docstring. This caused compatibility issues
1188 with unittest extensions and adding the test name was moved to the
1189 :class:`TextTestResult`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001190
1191 .. method:: addTypeEqualityFunc(typeobj, function)
1192
1193 Registers a type specific :meth:`assertEqual` equality checking
1194 function to be called by :meth:`assertEqual` when both objects it has
1195 been asked to compare are exactly *typeobj* (not subclasses).
1196 *function* must take two positional arguments and a third msg=None
1197 keyword argument just as :meth:`assertEqual` does. It must raise
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001198 ``self.failureException`` when inequality between the first two
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001199 parameters is detected.
1200
1201 One good use of custom equality checking functions for a type
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001202 is to raise ``self.failureException`` with an error message useful
1203 for debugging the problem by explaining the inequalities in detail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001204
Raymond Hettinger35a88362009-04-09 00:08:24 +00001205 .. versionadded:: 3.1
Georg Brandl116aa622007-08-15 14:28:22 +00001206
1207
Georg Brandl7f01a132009-09-16 15:58:14 +00001208 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001209
1210 Add a function to be called after :meth:`tearDown` to cleanup resources
1211 used during the test. Functions will be called in reverse order to the
1212 order they are added (LIFO). They are called with any arguments and
1213 keyword arguments passed into :meth:`addCleanup` when they are
1214 added.
1215
1216 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1217 then any cleanup functions added will still be called.
1218
Georg Brandl853947a2010-01-31 18:53:23 +00001219 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001220
1221
1222 .. method:: doCleanups()
1223
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001224 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001225 after :meth:`setUp` if :meth:`setUp` raises an exception.
1226
1227 It is responsible for calling all the cleanup functions added by
1228 :meth:`addCleanup`. If you need cleanup functions to be called
1229 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1230 yourself.
1231
1232 :meth:`doCleanups` pops methods off the stack of cleanup
1233 functions one at a time, so it can be called at any time.
1234
Georg Brandl853947a2010-01-31 18:53:23 +00001235 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001236
1237
Georg Brandl7f01a132009-09-16 15:58:14 +00001238.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001239
1240 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001241 allows the test runner to drive the test, but does not provide the methods
1242 which test code can use to check and report errors. This is used to create
1243 test cases using legacy test code, allowing it to be integrated into a
1244 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001245
1246
Benjamin Peterson52baa292009-03-24 00:56:30 +00001247.. _testsuite-objects:
1248
Benjamin Peterson52baa292009-03-24 00:56:30 +00001249Grouping tests
1250~~~~~~~~~~~~~~
1251
Georg Brandl7f01a132009-09-16 15:58:14 +00001252.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001253
1254 This class represents an aggregation of individual tests cases and test suites.
1255 The class presents the interface needed by the test runner to allow it to be run
1256 as any other test case. Running a :class:`TestSuite` instance is the same as
1257 iterating over the suite, running each test individually.
1258
1259 If *tests* is given, it must be an iterable of individual test cases or other
1260 test suites that will be used to build the suite initially. Additional methods
1261 are provided to add test cases and suites to the collection later on.
1262
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001263 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1264 they do not actually implement a test. Instead, they are used to aggregate
1265 tests into groups of tests that should be run together. Some additional
1266 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001267
1268
1269 .. method:: TestSuite.addTest(test)
1270
1271 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1272
1273
1274 .. method:: TestSuite.addTests(tests)
1275
1276 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1277 instances to this test suite.
1278
Benjamin Petersond2397752009-06-27 23:45:02 +00001279 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1280 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001281
1282 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1283
1284
1285 .. method:: run(result)
1286
1287 Run the tests associated with this suite, collecting the result into the
1288 test result object passed as *result*. Note that unlike
1289 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1290 be passed in.
1291
1292
1293 .. method:: debug()
1294
1295 Run the tests associated with this suite without collecting the
1296 result. This allows exceptions raised by the test to be propagated to the
1297 caller and can be used to support running tests under a debugger.
1298
1299
1300 .. method:: countTestCases()
1301
1302 Return the number of tests represented by this test object, including all
1303 individual tests and sub-suites.
1304
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001305
1306 .. method:: __iter__()
1307
1308 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1309 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1310 that this method maybe called several times on a single suite
1311 (for example when counting tests or comparing for equality)
1312 so the tests returned must be the same for repeated iterations.
1313
Georg Brandl853947a2010-01-31 18:53:23 +00001314 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001315 In earlier versions the :class:`TestSuite` accessed tests directly rather
1316 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1317 for providing tests.
1318
Benjamin Peterson52baa292009-03-24 00:56:30 +00001319 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1320 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1321
1322
Benjamin Peterson52baa292009-03-24 00:56:30 +00001323Loading and running tests
1324~~~~~~~~~~~~~~~~~~~~~~~~~
1325
Georg Brandl116aa622007-08-15 14:28:22 +00001326.. class:: TestLoader()
1327
Benjamin Peterson52baa292009-03-24 00:56:30 +00001328 The :class:`TestLoader` class is used to create test suites from classes and
1329 modules. Normally, there is no need to create an instance of this class; the
1330 :mod:`unittest` module provides an instance that can be shared as
1331 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1332 customization of some configurable properties.
1333
1334 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001335
Michael Foordabd91d52010-03-20 18:09:14 +00001336a
Benjamin Peterson52baa292009-03-24 00:56:30 +00001337 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001338
Benjamin Peterson52baa292009-03-24 00:56:30 +00001339 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1340 :class:`testCaseClass`.
1341
1342
1343 .. method:: loadTestsFromModule(module)
1344
1345 Return a suite of all tests cases contained in the given module. This
1346 method searches *module* for classes derived from :class:`TestCase` and
1347 creates an instance of the class for each test method defined for the
1348 class.
1349
Georg Brandle720c0a2009-04-27 16:20:50 +00001350 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001351
1352 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1353 convenient in sharing fixtures and helper functions, defining test
1354 methods on base classes that are not intended to be instantiated
1355 directly does not play well with this method. Doing so, however, can
1356 be useful when the fixtures are different and defined in subclasses.
1357
Benjamin Petersond2397752009-06-27 23:45:02 +00001358 If a module provides a ``load_tests`` function it will be called to
1359 load the tests. This allows modules to customize test loading.
1360 This is the `load_tests protocol`_.
1361
Georg Brandl853947a2010-01-31 18:53:23 +00001362 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001363 Support for ``load_tests`` added.
1364
Benjamin Peterson52baa292009-03-24 00:56:30 +00001365
Georg Brandl7f01a132009-09-16 15:58:14 +00001366 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001367
1368 Return a suite of all tests cases given a string specifier.
1369
1370 The specifier *name* is a "dotted name" that may resolve either to a
1371 module, a test case class, a test method within a test case class, a
1372 :class:`TestSuite` instance, or a callable object which returns a
1373 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1374 applied in the order listed here; that is, a method on a possible test
1375 case class will be picked up as "a test method within a test case class",
1376 rather than "a callable object".
1377
1378 For example, if you have a module :mod:`SampleTests` containing a
1379 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1380 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001381 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1382 return a suite which will run all three test methods. Using the specifier
1383 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1384 suite which will run only the :meth:`test_two` test method. The specifier
1385 can refer to modules and packages which have not been imported; they will
1386 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001387
1388 The method optionally resolves *name* relative to the given *module*.
1389
1390
Georg Brandl7f01a132009-09-16 15:58:14 +00001391 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001392
1393 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1394 than a single name. The return value is a test suite which supports all
1395 the tests defined for each name.
1396
1397
1398 .. method:: getTestCaseNames(testCaseClass)
1399
1400 Return a sorted sequence of method names found within *testCaseClass*;
1401 this should be a subclass of :class:`TestCase`.
1402
Benjamin Petersond2397752009-06-27 23:45:02 +00001403
1404 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1405
1406 Find and return all test modules from the specified start directory,
1407 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001408 *pattern* will be loaded. (Using shell style pattern matching.) Only
1409 module names that are importable (i.e. are valid Python identifiers) will
1410 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001411
1412 All test modules must be importable from the top level of the project. If
1413 the start directory is not the top level directory then the top level
1414 directory must be specified separately.
1415
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001416 If importing a module fails, for example due to a syntax error, then this
1417 will be recorded as a single error and discovery will continue.
1418
Benjamin Petersond2397752009-06-27 23:45:02 +00001419 If a test package name (directory with :file:`__init__.py`) matches the
1420 pattern then the package will be checked for a ``load_tests``
1421 function. If this exists then it will be called with *loader*, *tests*,
1422 *pattern*.
1423
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001424 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001425 ``load_tests`` is responsible for loading all tests in the package.
1426
1427 The pattern is deliberately not stored as a loader attribute so that
1428 packages can continue discovery themselves. *top_level_dir* is stored so
1429 ``load_tests`` does not need to pass this argument in to
1430 ``loader.discover()``.
1431
Benjamin Petersonb48af542010-04-11 20:43:16 +00001432 *start_dir* can be a dotted module name as well as a directory.
1433
Georg Brandl853947a2010-01-31 18:53:23 +00001434 .. versionadded:: 3.2
1435
Benjamin Petersond2397752009-06-27 23:45:02 +00001436
Benjamin Peterson52baa292009-03-24 00:56:30 +00001437 The following attributes of a :class:`TestLoader` can be configured either by
1438 subclassing or assignment on an instance:
1439
1440
1441 .. attribute:: testMethodPrefix
1442
1443 String giving the prefix of method names which will be interpreted as test
1444 methods. The default value is ``'test'``.
1445
1446 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1447 methods.
1448
1449
1450 .. attribute:: sortTestMethodsUsing
1451
1452 Function to be used to compare method names when sorting them in
1453 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1454
1455
1456 .. attribute:: suiteClass
1457
1458 Callable object that constructs a test suite from a list of tests. No
1459 methods on the resulting object are needed. The default value is the
1460 :class:`TestSuite` class.
1461
1462 This affects all the :meth:`loadTestsFrom\*` methods.
1463
1464
Benjamin Peterson52baa292009-03-24 00:56:30 +00001465.. class:: TestResult
1466
1467 This class is used to compile information about which tests have succeeded
1468 and which have failed.
1469
1470 A :class:`TestResult` object stores the results of a set of tests. The
1471 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1472 properly recorded; test authors do not need to worry about recording the
1473 outcome of tests.
1474
1475 Testing frameworks built on top of :mod:`unittest` may want access to the
1476 :class:`TestResult` object generated by running a set of tests for reporting
1477 purposes; a :class:`TestResult` instance is returned by the
1478 :meth:`TestRunner.run` method for this purpose.
1479
1480 :class:`TestResult` instances have the following attributes that will be of
1481 interest when inspecting the results of running a set of tests:
1482
1483
1484 .. attribute:: errors
1485
1486 A list containing 2-tuples of :class:`TestCase` instances and strings
1487 holding formatted tracebacks. Each tuple represents a test which raised an
1488 unexpected exception.
1489
Benjamin Peterson52baa292009-03-24 00:56:30 +00001490 .. attribute:: failures
1491
1492 A list containing 2-tuples of :class:`TestCase` instances and strings
1493 holding formatted tracebacks. Each tuple represents a test where a failure
1494 was explicitly signalled using the :meth:`TestCase.fail\*` or
1495 :meth:`TestCase.assert\*` methods.
1496
Benjamin Peterson52baa292009-03-24 00:56:30 +00001497 .. attribute:: skipped
1498
1499 A list containing 2-tuples of :class:`TestCase` instances and strings
1500 holding the reason for skipping the test.
1501
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001502 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001503
1504 .. attribute:: expectedFailures
1505
1506 A list contaning 2-tuples of :class:`TestCase` instances and strings
1507 holding formatted tracebacks. Each tuple represents a expected failures
1508 of the test case.
1509
1510 .. attribute:: unexpectedSuccesses
1511
1512 A list containing :class:`TestCase` instances that were marked as expected
1513 failures, but succeeded.
1514
1515 .. attribute:: shouldStop
1516
1517 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1518
1519
1520 .. attribute:: testsRun
1521
1522 The total number of tests run so far.
1523
1524
Benjamin Petersonb48af542010-04-11 20:43:16 +00001525 .. attribute:: buffer
1526
1527 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1528 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1529 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1530 fails or errors. Any output is also attached to the failure / error message.
1531
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001532 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001533
1534
1535 .. attribute:: failfast
1536
1537 If set to true :meth:`stop` will be called on the first failure or error,
1538 halting the test run.
1539
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001540 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001541
1542
Benjamin Peterson52baa292009-03-24 00:56:30 +00001543 .. method:: wasSuccessful()
1544
1545 Return :const:`True` if all tests run so far have passed, otherwise returns
1546 :const:`False`.
1547
1548
1549 .. method:: stop()
1550
1551 This method can be called to signal that the set of tests being run should
1552 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1553 :class:`TestRunner` objects should respect this flag and return without
1554 running any additional tests.
1555
1556 For example, this feature is used by the :class:`TextTestRunner` class to
1557 stop the test framework when the user signals an interrupt from the
1558 keyboard. Interactive tools which provide :class:`TestRunner`
1559 implementations can use this in a similar manner.
1560
1561 The following methods of the :class:`TestResult` class are used to maintain
1562 the internal data structures, and may be extended in subclasses to support
1563 additional reporting requirements. This is particularly useful in building
1564 tools which support interactive reporting while tests are being run.
1565
1566
1567 .. method:: startTest(test)
1568
1569 Called when the test case *test* is about to be run.
1570
Benjamin Peterson52baa292009-03-24 00:56:30 +00001571 .. method:: stopTest(test)
1572
1573 Called after the test case *test* has been executed, regardless of the
1574 outcome.
1575
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001576 .. method:: startTestRun(test)
1577
1578 Called once before any tests are executed.
1579
Georg Brandl853947a2010-01-31 18:53:23 +00001580 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001581
1582
1583 .. method:: stopTestRun(test)
1584
Ezio Melotti176d6c42010-01-27 20:58:07 +00001585 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001586
Georg Brandl853947a2010-01-31 18:53:23 +00001587 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001588
1589
Benjamin Peterson52baa292009-03-24 00:56:30 +00001590 .. method:: addError(test, err)
1591
1592 Called when the test case *test* raises an unexpected exception *err* is a
1593 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1594 traceback)``.
1595
1596 The default implementation appends a tuple ``(test, formatted_err)`` to
1597 the instance's :attr:`errors` attribute, where *formatted_err* is a
1598 formatted traceback derived from *err*.
1599
1600
1601 .. method:: addFailure(test, err)
1602
Benjamin Petersond2397752009-06-27 23:45:02 +00001603 Called when the test case *test* signals a failure. *err* is a tuple of
1604 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001605
1606 The default implementation appends a tuple ``(test, formatted_err)`` to
1607 the instance's :attr:`failures` attribute, where *formatted_err* is a
1608 formatted traceback derived from *err*.
1609
1610
1611 .. method:: addSuccess(test)
1612
1613 Called when the test case *test* succeeds.
1614
1615 The default implementation does nothing.
1616
1617
1618 .. method:: addSkip(test, reason)
1619
1620 Called when the test case *test* is skipped. *reason* is the reason the
1621 test gave for skipping.
1622
1623 The default implementation appends a tuple ``(test, reason)`` to the
1624 instance's :attr:`skipped` attribute.
1625
1626
1627 .. method:: addExpectedFailure(test, err)
1628
1629 Called when the test case *test* fails, but was marked with the
1630 :func:`expectedFailure` decorator.
1631
1632 The default implementation appends a tuple ``(test, formatted_err)`` to
1633 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1634 is a formatted traceback derived from *err*.
1635
1636
1637 .. method:: addUnexpectedSuccess(test)
1638
1639 Called when the test case *test* was marked with the
1640 :func:`expectedFailure` decorator, but succeeded.
1641
1642 The default implementation appends the test to the instance's
1643 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001644
Michael Foord34c94622010-02-10 15:51:42 +00001645.. class:: TextTestResult(stream, descriptions, verbosity)
1646
1647 A concrete implementation of :class:`TestResult` used by the
1648 :class:`TextTestRunner`.
1649
1650 .. versionadded:: 3.2
1651 This class was previously named ``_TextTestResult``. The old name still
1652 exists as an alias but is deprecated.
Georg Brandl116aa622007-08-15 14:28:22 +00001653
1654.. data:: defaultTestLoader
1655
1656 Instance of the :class:`TestLoader` class intended to be shared. If no
1657 customization of the :class:`TestLoader` is needed, this instance can be used
1658 instead of repeatedly creating new instances.
1659
1660
Michael Foord34c94622010-02-10 15:51:42 +00001661.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001662
1663 A basic test runner implementation which prints results on standard error. It
1664 has a few configurable parameters, but is essentially very simple. Graphical
1665 applications which run test suites should provide alternate implementations.
1666
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001667 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001668
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001669 This method returns the instance of ``TestResult`` used by :meth:`run`.
1670 It is not intended to be called directly, but can be overridden in
1671 subclasses to provide a custom ``TestResult``.
1672
Michael Foord34c94622010-02-10 15:51:42 +00001673 ``_makeResult()`` instantiates the class or callable passed in the
1674 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001675 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001676 The result class is instantiated with the following arguments::
1677
1678 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001679
Benjamin Petersonb48af542010-04-11 20:43:16 +00001680.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001681
1682 A command-line program that runs a set of tests; this is primarily for making
1683 test modules conveniently executable. The simplest use for this function is to
1684 include the following line at the end of a test script::
1685
1686 if __name__ == '__main__':
1687 unittest.main()
1688
Benjamin Petersond2397752009-06-27 23:45:02 +00001689 You can run tests with more detailed information by passing in the verbosity
1690 argument::
1691
1692 if __name__ == '__main__':
1693 unittest.main(verbosity=2)
1694
Georg Brandl116aa622007-08-15 14:28:22 +00001695 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001696 created instance of it. By default ``main`` calls :func:`sys.exit` with
1697 an exit code indicating success or failure of the tests run.
1698
1699 ``main`` supports being used from the interactive interpreter by passing in the
1700 argument ``exit=False``. This displays the result on standard output without
1701 calling :func:`sys.exit`::
1702
1703 >>> from unittest import main
1704 >>> main(module='test_module', exit=False)
1705
Benjamin Petersonb48af542010-04-11 20:43:16 +00001706 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
1707 effect as the `failfast, catch and buffer command line options`_.
1708
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001709 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1710 This stores the result of the tests run as the ``result`` attribute.
1711
Georg Brandl853947a2010-01-31 18:53:23 +00001712 .. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001713 The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
1714 parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001715
1716
1717load_tests Protocol
1718###################
1719
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001720
Georg Brandl853947a2010-01-31 18:53:23 +00001721.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001722
1723
Benjamin Petersond2397752009-06-27 23:45:02 +00001724Modules or packages can customize how tests are loaded from them during normal
1725test runs or test discovery by implementing a function called ``load_tests``.
1726
1727If a test module defines ``load_tests`` it will be called by
1728:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1729
1730 load_tests(loader, standard_tests, None)
1731
1732It should return a :class:`TestSuite`.
1733
1734*loader* is the instance of :class:`TestLoader` doing the loading.
1735*standard_tests* are the tests that would be loaded by default from the
1736module. It is common for test modules to only want to add or remove tests
1737from the standard set of tests.
1738The third argument is used when loading packages as part of test discovery.
1739
1740A typical ``load_tests`` function that loads tests from a specific set of
1741:class:`TestCase` classes may look like::
1742
1743 test_cases = (TestCase1, TestCase2, TestCase3)
1744
1745 def load_tests(loader, tests, pattern):
1746 suite = TestSuite()
1747 for test_class in test_cases:
1748 tests = loader.loadTestsFromTestCase(test_class)
1749 suite.addTests(tests)
1750 return suite
1751
1752If discovery is started, either from the command line or by calling
1753:meth:`TestLoader.discover`, with a pattern that matches a package
1754name then the package :file:`__init__.py` will be checked for ``load_tests``.
1755
1756.. note::
1757
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001758 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00001759 that start with 'test' but *won't* match any test directories.
1760
1761 A pattern like 'test*' will match test packages as well as
1762 modules.
1763
1764If the package :file:`__init__.py` defines ``load_tests`` then it will be
1765called and discovery not continued into the package. ``load_tests``
1766is called with the following arguments::
1767
1768 load_tests(loader, standard_tests, pattern)
1769
1770This should return a :class:`TestSuite` representing all the tests
1771from the package. (``standard_tests`` will only contain tests
1772collected from :file:`__init__.py`.)
1773
1774Because the pattern is passed into ``load_tests`` the package is free to
1775continue (and potentially modify) test discovery. A 'do nothing'
1776``load_tests`` function for a test package would look like::
1777
1778 def load_tests(loader, standard_tests, pattern):
1779 # top level directory cached on loader instance
1780 this_dir = os.path.dirname(__file__)
1781 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1782 standard_tests.addTests(package_tests)
1783 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00001784
1785
1786Class and Module Fixtures
1787-------------------------
1788
1789Class and module level fixtures are implemented in :class:`TestSuite`. When
1790the test suite encounters a test from a new class then :meth:`tearDownClass`
1791from the previous class (if there is one) is called, followed by
1792:meth:`setUpClass` from the new class.
1793
1794Similarly if a test is from a different module from the previous test then
1795``tearDownModule`` from the previous module is run, followed by
1796``setUpModule`` from the new module.
1797
1798After all the tests have run the final ``tearDownClass`` and
1799``tearDownModule`` are run.
1800
1801Note that shared fixtures do not play well with [potential] features like test
1802parallelization and they break test isolation. They should be used with care.
1803
1804The default ordering of tests created by the unittest test loaders is to group
1805all tests from the same modules and classes together. This will lead to
1806``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
1807module. If you randomize the order, so that tests from different modules and
1808classes are adjacent to each other, then these shared fixture functions may be
1809called multiple times in a single test run.
1810
1811Shared fixtures are not intended to work with suites with non-standard
1812ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
1813support shared fixtures.
1814
1815If there are any exceptions raised during one of the shared fixture functions
1816the test is reported as an error. Because there is no corresponding test
1817instance an ``_ErrorHolder`` object (that has the same interface as a
1818:class:`TestCase`) is created to represent the error. If you are just using
1819the standard unittest test runner then this detail doesn't matter, but if you
1820are a framework author it may be relevant.
1821
1822
1823setUpClass and tearDownClass
1824~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1825
1826These must be implemented as class methods::
1827
1828 import unittest
1829
1830 class Test(unittest.TestCase):
1831 @classmethod
1832 def setUpClass(cls):
1833 cls._connection = createExpensiveConnectionObject()
1834
1835 @classmethod
1836 def tearDownClass(cls):
1837 cls._connection.destroy()
1838
1839If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
1840then you must call up to them yourself. The implementations in
1841:class:`TestCase` are empty.
1842
1843If an exception is raised during a ``setUpClass`` then the tests in the class
1844are not run and the ``tearDownClass`` is not run. Skipped classes will not
1845have ``setUpClass`` or ``tearDownClass`` run.
1846
1847
1848setUpModule and tearDownModule
1849~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1850
1851These should be implemented as functions::
1852
1853 def setUpModule():
1854 createConnection()
1855
1856 def tearDownModule():
1857 closeConnection()
1858
1859If an exception is raised in a ``setUpModule`` then none of the tests in the
1860module will be run and the ``tearDownModule`` will not be run.
1861
1862
1863Signal Handling
1864---------------
1865
1866The -c / --catch command line option to unittest, along with the ``catchbreak``
1867parameter to :func:`unittest.main()`, provide more friendly handling of
1868control-c during a test run. With catch break behavior enabled control-c will
1869allow the currently running test to complete, and the test run will then end
1870and report all the results so far. A second control-c will raise a
1871``KeyboardInterrupt`` in the usual way.
1872
Michael Foordde4ceab2010-04-25 19:53:49 +00001873The control-c handling signal handler attempts to remain compatible with code or
1874tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
1875handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
1876i.e. it has been replaced by the system under test and delegated to, then it
1877calls the default handler. This will normally be the expected behavior by code
1878that replaces an installed handler and delegates to it. For individual tests
1879that need ``unittest`` control-c handling disabled the :func:`removeHandler`
1880decorator can be used.
1881
1882There are a few utility functions for framework authors to enable control-c
1883handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001884
1885.. function:: installHandler()
1886
1887 Install the control-c handler. When a :const:`signal.SIGINT` is received
1888 (usually in response to the user pressing control-c) all registered results
1889 have :meth:`~TestResult.stop` called.
1890
Michael Foord469b1f02010-04-26 23:41:26 +00001891 .. versionadded:: 3.2
1892
Benjamin Petersonb48af542010-04-11 20:43:16 +00001893.. function:: registerResult(result)
1894
1895 Register a :class:`TestResult` object for control-c handling. Registering a
1896 result stores a weak reference to it, so it doesn't prevent the result from
1897 being garbage collected.
1898
Michael Foordde4ceab2010-04-25 19:53:49 +00001899 Registering a :class:`TestResult` object has no side-effects if control-c
1900 handling is not enabled, so test frameworks can unconditionally register
1901 all results they create independently of whether or not handling is enabled.
1902
Michael Foord469b1f02010-04-26 23:41:26 +00001903 .. versionadded:: 3.2
1904
Benjamin Petersonb48af542010-04-11 20:43:16 +00001905.. function:: removeResult(result)
1906
1907 Remove a registered result. Once a result has been removed then
1908 :meth:`~TestResult.stop` will no longer be called on that result object in
1909 response to a control-c.
1910
Michael Foord469b1f02010-04-26 23:41:26 +00001911 .. versionadded:: 3.2
1912
Michael Foordde4ceab2010-04-25 19:53:49 +00001913.. function:: removeHandler(function=None)
1914
1915 When called without arguments this function removes the control-c handler
1916 if it has been installed. This function can also be used as a test decorator
1917 to temporarily remove the handler whilst the test is being executed::
1918
1919 @unittest.removeHandler
1920 def test_signal_handling(self):
1921 ...
1922
Michael Foord469b1f02010-04-26 23:41:26 +00001923 .. versionadded:: 3.2
1924