blob: 9839efbbf123c77cefe3a67f184e520a89498111 [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
Georg Brandl67b21b72010-08-17 15:07:14 +0000213.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000214 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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000223* :option:`-b` / :option:`--buffer`
Benjamin Petersonb48af542010-04-11 20:43:16 +0000224
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000225 The standard output and standard error streams are buffered during the test
Benjamin Petersonb48af542010-04-11 20:43:16 +0000226 run. Output during a passing test is discarded. Output is echoed normally
227 on test fail or error and is added to the failure messages.
228
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000229* :option:`-c` / :option:`--catch`
230
231 Control-C during the test run waits for the current test to end and then
232 reports all the results so far. A second control-C raises the normal
233 :exc:`KeyboardInterrupt` exception.
234
235 See `Signal Handling`_ for the functions that provide this functionality.
236
237* :option:`-f` / :option:`--failfast`
238
239 Stop the test run on the first error or failure.
240
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000241.. versionadded:: 3.2
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000242 The command line options ``-c``, ``-b`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000243
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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000273The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
274as positional arguments in that order. The following two command lines
275are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000276
277 python -m unittest discover -s project_directory -p '*_test.py'
278 python -m unittest discover project_directory '*_test.py'
279
Michael Foord16f3e902010-05-08 15:13:42 +0000280As well as being a path it is possible to pass a package name, for example
281``myproject.subpackage.test``, as the start directory. The package name you
282supply will then be imported and its location on the filesystem will be used
283as the start directory.
284
285.. caution::
286
Senthil Kumaran916bd382010-10-15 12:55:19 +0000287 Test discovery loads tests by importing them. Once test discovery has found
288 all the test files from the start directory you specify it turns the paths
289 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000290 imported as ``foo.bar.baz``.
291
292 If you have a package installed globally and attempt test discovery on
293 a different copy of the package then the import *could* happen from the
294 wrong place. If this happens test discovery will warn you and exit.
295
296 If you supply the start directory as a package name rather than a
297 path to a directory then discover assumes that whichever location it
298 imports from is the location you intended, so you will not get the
299 warning.
300
Benjamin Petersonb48af542010-04-11 20:43:16 +0000301Test modules and packages can customize test loading and discovery by through
302the `load_tests protocol`_.
303
304
Georg Brandl116aa622007-08-15 14:28:22 +0000305.. _organizing-tests:
306
307Organizing test code
308--------------------
309
310The basic building blocks of unit testing are :dfn:`test cases` --- single
311scenarios that must be set up and checked for correctness. In :mod:`unittest`,
312test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
313class. To make your own test cases you must write subclasses of
314:class:`TestCase`, or use :class:`FunctionTestCase`.
315
316An instance of a :class:`TestCase`\ -derived class is an object that can
317completely run a single test method, together with optional set-up and tidy-up
318code.
319
320The testing code of a :class:`TestCase` instance should be entirely self
321contained, such that it can be run either in isolation or in arbitrary
322combination with any number of other test cases.
323
Benjamin Peterson52baa292009-03-24 00:56:30 +0000324The simplest :class:`TestCase` subclass will simply override the
325:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000326
327 import unittest
328
329 class DefaultWidgetSizeTestCase(unittest.TestCase):
330 def runTest(self):
331 widget = Widget('The widget')
332 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
333
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000334Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000335methods provided by the :class:`TestCase` base class. If the test fails, an
336exception will be raised, and :mod:`unittest` will identify the test case as a
337:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
338helps you identify where the problem is: :dfn:`failures` are caused by incorrect
339results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
340code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000341
342The way to run a test case will be described later. For now, note that to
343construct an instance of such a test case, we call its constructor without
344arguments::
345
346 testCase = DefaultWidgetSizeTestCase()
347
348Now, such test cases can be numerous, and their set-up can be repetitive. In
349the above case, constructing a :class:`Widget` in each of 100 Widget test case
350subclasses would mean unsightly duplication.
351
352Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000353:meth:`~TestCase.setUp`, which the testing framework will automatically call for
354us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356 import unittest
357
358 class SimpleWidgetTestCase(unittest.TestCase):
359 def setUp(self):
360 self.widget = Widget('The widget')
361
362 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
363 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000364 self.assertEqual(self.widget.size(), (50,50),
365 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367 class WidgetResizeTestCase(SimpleWidgetTestCase):
368 def runTest(self):
369 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000370 self.assertEqual(self.widget.size(), (100,150),
371 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000372
Benjamin Peterson52baa292009-03-24 00:56:30 +0000373If the :meth:`~TestCase.setUp` method raises an exception while the test is
374running, the framework will consider the test to have suffered an error, and the
375:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Benjamin Peterson52baa292009-03-24 00:56:30 +0000377Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
378after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380 import unittest
381
382 class SimpleWidgetTestCase(unittest.TestCase):
383 def setUp(self):
384 self.widget = Widget('The widget')
385
386 def tearDown(self):
387 self.widget.dispose()
388 self.widget = None
389
Benjamin Peterson52baa292009-03-24 00:56:30 +0000390If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
391be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000392
393Such a working environment for the testing code is called a :dfn:`fixture`.
394
395Often, many small test cases will use the same fixture. In this case, we would
396end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
397classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000398discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
399mechanism::
400
401 import unittest
402
403 class WidgetTestCase(unittest.TestCase):
404 def setUp(self):
405 self.widget = Widget('The widget')
406
407 def tearDown(self):
408 self.widget.dispose()
409 self.widget = None
410
Ezio Melottid59e44a2010-02-28 03:46:13 +0000411 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000412 self.assertEqual(self.widget.size(), (50,50),
413 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Ezio Melottid59e44a2010-02-28 03:46:13 +0000415 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000416 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000417 self.assertEqual(self.widget.size(), (100,150),
418 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Benjamin Peterson52baa292009-03-24 00:56:30 +0000420Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
421provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000422the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000423separately for each instance. When creating an instance we must specify the
424test method it is to run. We do this by passing the method name in the
425constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Ezio Melottid59e44a2010-02-28 03:46:13 +0000427 defaultSizeTestCase = WidgetTestCase('test_default_size')
428 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000429
430Test case instances are grouped together according to the features they test.
431:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
432represented by :mod:`unittest`'s :class:`TestSuite` class::
433
434 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000435 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
436 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438For the ease of running tests, as we will see later, it is a good idea to
439provide in each test module a callable object that returns a pre-built test
440suite::
441
442 def suite():
443 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000444 suite.addTest(WidgetTestCase('test_default_size'))
445 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000446 return suite
447
448or even::
449
450 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000451 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000452
453 return unittest.TestSuite(map(WidgetTestCase, tests))
454
455Since it is a common pattern to create a :class:`TestCase` subclass with many
456similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
457class that can be used to automate the process of creating a test suite and
458populating it with individual tests. For example, ::
459
460 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
461
Ezio Melottid59e44a2010-02-28 03:46:13 +0000462will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
463``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000464name prefix to identify test methods automatically.
465
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000466Note that the order in which the various test cases will be run is
467determined by sorting the test function names with respect to the
468built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000469
470Often it is desirable to group suites of test cases together, so as to run tests
471for the whole system at once. This is easy, since :class:`TestSuite` instances
472can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
473added to a :class:`TestSuite`::
474
475 suite1 = module1.TheTestSuite()
476 suite2 = module2.TheTestSuite()
477 alltests = unittest.TestSuite([suite1, suite2])
478
479You can place the definitions of test cases and test suites in the same modules
480as the code they are to test (such as :file:`widget.py`), but there are several
481advantages to placing the test code in a separate module, such as
482:file:`test_widget.py`:
483
484* The test module can be run standalone from the command line.
485
486* The test code can more easily be separated from shipped code.
487
488* There is less temptation to change test code to fit the code it tests without
489 a good reason.
490
491* Test code should be modified much less frequently than the code it tests.
492
493* Tested code can be refactored more easily.
494
495* Tests for modules written in C must be in separate modules anyway, so why not
496 be consistent?
497
498* If the testing strategy changes, there is no need to change the source code.
499
500
501.. _legacy-unit-tests:
502
503Re-using old test code
504----------------------
505
506Some users will find that they have existing test code that they would like to
507run from :mod:`unittest`, without converting every old test function to a
508:class:`TestCase` subclass.
509
510For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
511This subclass of :class:`TestCase` can be used to wrap an existing test
512function. Set-up and tear-down functions can also be provided.
513
514Given the following test function::
515
516 def testSomething():
517 something = makeSomething()
518 assert something.name is not None
519 # ...
520
521one can create an equivalent test case instance as follows::
522
523 testcase = unittest.FunctionTestCase(testSomething)
524
525If there are additional set-up and tear-down methods that should be called as
526part of the test case's operation, they can also be provided like so::
527
528 testcase = unittest.FunctionTestCase(testSomething,
529 setUp=makeSomethingDB,
530 tearDown=deleteSomethingDB)
531
532To make migrating existing test suites easier, :mod:`unittest` supports tests
533raising :exc:`AssertionError` to indicate test failure. However, it is
534recommended that you use the explicit :meth:`TestCase.fail\*` and
535:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
536may treat :exc:`AssertionError` differently.
537
538.. note::
539
Benjamin Petersond2397752009-06-27 23:45:02 +0000540 Even though :class:`FunctionTestCase` can be used to quickly convert an
541 existing test base over to a :mod:`unittest`\ -based system, this approach is
542 not recommended. Taking the time to set up proper :class:`TestCase`
543 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000544
Benjamin Peterson52baa292009-03-24 00:56:30 +0000545In some cases, the existing tests may have been written using the :mod:`doctest`
546module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
547automatically build :class:`unittest.TestSuite` instances from the existing
548:mod:`doctest`\ -based tests.
549
Georg Brandl116aa622007-08-15 14:28:22 +0000550
Benjamin Peterson5254c042009-03-23 22:25:03 +0000551.. _unittest-skipping:
552
553Skipping tests and expected failures
554------------------------------------
555
Michael Foordf5c851a2010-02-05 21:48:03 +0000556.. versionadded:: 3.1
557
Benjamin Peterson5254c042009-03-23 22:25:03 +0000558Unittest supports skipping individual test methods and even whole classes of
559tests. In addition, it supports marking a test as a "expected failure," a test
560that is broken and will fail, but shouldn't be counted as a failure on a
561:class:`TestResult`.
562
563Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
564or one of its conditional variants.
565
566Basic skipping looks like this: ::
567
568 class MyTestCase(unittest.TestCase):
569
570 @unittest.skip("demonstrating skipping")
571 def test_nothing(self):
572 self.fail("shouldn't happen")
573
Benjamin Petersond2397752009-06-27 23:45:02 +0000574 @unittest.skipIf(mylib.__version__ < (1, 3),
575 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000576 def test_format(self):
577 # Tests that work for only a certain version of the library.
578 pass
579
580 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
581 def test_windows_support(self):
582 # windows specific testing code
583 pass
584
Benjamin Peterson5254c042009-03-23 22:25:03 +0000585This is the output of running the example above in verbose mode: ::
586
Benjamin Petersonded31c42009-03-30 15:04:16 +0000587 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000588 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000589 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000590
591 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000592 Ran 3 tests in 0.005s
593
594 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000595
596Classes can be skipped just like methods: ::
597
598 @skip("showing class skipping")
599 class MySkippedTestCase(unittest.TestCase):
600 def test_not_run(self):
601 pass
602
Benjamin Peterson52baa292009-03-24 00:56:30 +0000603:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
604that needs to be set up is not available.
605
Benjamin Peterson5254c042009-03-23 22:25:03 +0000606Expected failures use the :func:`expectedFailure` decorator. ::
607
608 class ExpectedFailureTestCase(unittest.TestCase):
609 @unittest.expectedFailure
610 def test_fail(self):
611 self.assertEqual(1, 0, "broken")
612
613It's easy to roll your own skipping decorators by making a decorator that calls
614:func:`skip` on the test when it wants it to be skipped. This decorator skips
615the test unless the passed object has a certain attribute: ::
616
617 def skipUnlessHasattr(obj, attr):
618 if hasattr(obj, attr):
619 return lambda func: func
620 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
621
622The following decorators implement test skipping and expected failures:
623
Georg Brandl8a1caa22010-07-29 16:01:11 +0000624.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000625
626 Unconditionally skip the decorated test. *reason* should describe why the
627 test is being skipped.
628
Georg Brandl8a1caa22010-07-29 16:01:11 +0000629.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000630
631 Skip the decorated test if *condition* is true.
632
Georg Brandl8a1caa22010-07-29 16:01:11 +0000633.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000634
Georg Brandl6faee4e2010-09-21 14:48:28 +0000635 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000636
Georg Brandl8a1caa22010-07-29 16:01:11 +0000637.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000638
639 Mark the test as an expected failure. If the test fails when run, the test
640 is not counted as a failure.
641
Benjamin Petersonb48af542010-04-11 20:43:16 +0000642Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
643Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
644
Benjamin Peterson5254c042009-03-23 22:25:03 +0000645
Georg Brandl116aa622007-08-15 14:28:22 +0000646.. _unittest-contents:
647
648Classes and functions
649---------------------
650
Benjamin Peterson52baa292009-03-24 00:56:30 +0000651This section describes in depth the API of :mod:`unittest`.
652
653
654.. _testcase-objects:
655
656Test cases
657~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000658
Georg Brandl7f01a132009-09-16 15:58:14 +0000659.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000660
661 Instances of the :class:`TestCase` class represent the smallest testable units
662 in the :mod:`unittest` universe. This class is intended to be used as a base
663 class, with specific tests being implemented by concrete subclasses. This class
664 implements the interface needed by the test runner to allow it to drive the
665 test, and methods that the test code can use to check for and report various
666 kinds of failure.
667
668 Each instance of :class:`TestCase` will run a single test method: the method
669 named *methodName*. If you remember, we had an earlier example that went
670 something like this::
671
672 def suite():
673 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000674 suite.addTest(WidgetTestCase('test_default_size'))
675 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000676 return suite
677
678 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
679 single test.
680
Benjamin Peterson52baa292009-03-24 00:56:30 +0000681 *methodName* defaults to :meth:`runTest`.
682
683 :class:`TestCase` instances provide three groups of methods: one group used
684 to run the test, another used by the test implementation to check conditions
685 and report failures, and some inquiry methods allowing information about the
686 test itself to be gathered.
687
688 Methods in the first group (running the test) are:
689
690
691 .. method:: setUp()
692
693 Method called to prepare the test fixture. This is called immediately
694 before calling the test method; any exception raised by this method will
695 be considered an error rather than a test failure. The default
696 implementation does nothing.
697
698
699 .. method:: tearDown()
700
701 Method called immediately after the test method has been called and the
702 result recorded. This is called even if the test method raised an
703 exception, so the implementation in subclasses may need to be particularly
704 careful about checking internal state. Any exception raised by this
705 method will be considered an error rather than a test failure. This
706 method will only be called if the :meth:`setUp` succeeds, regardless of
707 the outcome of the test method. The default implementation does nothing.
708
709
Benjamin Petersonb48af542010-04-11 20:43:16 +0000710 .. method:: setUpClass()
711
712 A class method called before tests in an individual class run.
713 ``setUpClass`` is called with the class as the only argument
714 and must be decorated as a :func:`classmethod`::
715
716 @classmethod
717 def setUpClass(cls):
718 ...
719
720 See `Class and Module Fixtures`_ for more details.
721
722 .. versionadded:: 3.2
723
724
725 .. method:: tearDownClass()
726
727 A class method called after tests in an individual class have run.
728 ``tearDownClass`` is called with the class as the only argument
729 and must be decorated as a :meth:`classmethod`::
730
731 @classmethod
732 def tearDownClass(cls):
733 ...
734
735 See `Class and Module Fixtures`_ for more details.
736
737 .. versionadded:: 3.2
738
739
Georg Brandl7f01a132009-09-16 15:58:14 +0000740 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000741
742 Run the test, collecting the result into the test result object passed as
743 *result*. If *result* is omitted or :const:`None`, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000744 object is created (by calling the :meth:`defaultTestResult` method) and
745 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000746
747 The same effect may be had by simply calling the :class:`TestCase`
748 instance.
749
750
Benjamin Petersone549ead2009-03-28 21:42:05 +0000751 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000752
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000753 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000754 test. See :ref:`unittest-skipping` for more information.
755
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000756 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000757
Benjamin Peterson52baa292009-03-24 00:56:30 +0000758
759 .. method:: debug()
760
761 Run the test without collecting the result. This allows exceptions raised
762 by the test to be propagated to the caller, and can be used to support
763 running tests under a debugger.
764
Benjamin Peterson52baa292009-03-24 00:56:30 +0000765
766
Ezio Melotti4370b302010-11-03 20:39:14 +0000767 The :class:`TestCase` class provides a number of methods to check for and
768 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000769
Ezio Melotti4370b302010-11-03 20:39:14 +0000770 +-----------------------------------------+-----------------------------+---------------+
771 | Method | Checks that | New in |
772 +=========================================+=============================+===============+
773 | :meth:`assertEqual(a, b) | ``a == b`` | |
774 | <TestCase.assertEqual>` | | |
775 +-----------------------------------------+-----------------------------+---------------+
776 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
777 | <TestCase.assertNotEqual>` | | |
778 +-----------------------------------------+-----------------------------+---------------+
779 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
780 | <TestCase.assertTrue>` | | |
781 +-----------------------------------------+-----------------------------+---------------+
782 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
783 | <TestCase.assertFalse>` | | |
784 +-----------------------------------------+-----------------------------+---------------+
785 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
786 | <TestCase.assertIs>` | | |
787 +-----------------------------------------+-----------------------------+---------------+
788 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
789 | <TestCase.assertIsNot>` | | |
790 +-----------------------------------------+-----------------------------+---------------+
791 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
792 | <TestCase.assertIsNone>` | | |
793 +-----------------------------------------+-----------------------------+---------------+
794 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
795 | <TestCase.assertIsNotNone>` | | |
796 +-----------------------------------------+-----------------------------+---------------+
797 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
798 | <TestCase.assertIn>` | | |
799 +-----------------------------------------+-----------------------------+---------------+
800 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
801 | <TestCase.assertNotIn>` | | |
802 +-----------------------------------------+-----------------------------+---------------+
803 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
804 | <TestCase.assertIsInstance>` | | |
805 +-----------------------------------------+-----------------------------+---------------+
806 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
807 | <TestCase.assertNotIsInstance>` | | |
808 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000809
Benjamin Peterson52baa292009-03-24 00:56:30 +0000810
Georg Brandl7f01a132009-09-16 15:58:14 +0000811 .. method:: assertEqual(first, second, msg=None)
812 failUnlessEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000813
814 Test that *first* and *second* are equal. If the values do not compare
815 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000816 :const:`None`. Note that using :meth:`assertEqual` improves upon
817 doing the comparison as the first parameter to :meth:`assertTrue`: the
818 default value for *msg* include representations of both *first* and
819 *second*.
820
821 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000822 list, tuple, dict, set, frozenset or str or any type that a subclass
823 registers with :meth:`addTypeEqualityFunc` the type specific equality
824 function will be called in order to generate a more useful default
825 error message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000826
Raymond Hettinger35a88362009-04-09 00:08:24 +0000827 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000828 Added the automatic calling of type specific equality function.
829
Michael Foord28a817e2010-02-09 00:03:57 +0000830 .. versionchanged:: 3.2
831 :meth:`assertMultiLineEqual` added as the default type equality
832 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000833
Raymond Hettinger35a88362009-04-09 00:08:24 +0000834 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000835 :meth:`failUnlessEqual`; use :meth:`assertEqual`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000836
837
Georg Brandl7f01a132009-09-16 15:58:14 +0000838 .. method:: assertNotEqual(first, second, msg=None)
839 failIfEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000840
841 Test that *first* and *second* are not equal. If the values do compare
842 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000843 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
844 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson52baa292009-03-24 00:56:30 +0000845 default value for *msg* can be computed to include representations of both
846 *first* and *second*.
847
Raymond Hettinger35a88362009-04-09 00:08:24 +0000848 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000849 :meth:`failIfEqual`; use :meth:`assertNotEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000850
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000851
Ezio Melotti4370b302010-11-03 20:39:14 +0000852 .. method:: assertTrue(expr, msg=None)
853 assert_(expr, msg=None)
854 failUnless(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000855
Ezio Melotti4370b302010-11-03 20:39:14 +0000856 Signal a test failure if *expr* is false; the explanation for the failure
857 will be *msg* if given, otherwise it will be :const:`None`.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000858
Raymond Hettinger35a88362009-04-09 00:08:24 +0000859 .. deprecated:: 3.1
Ezio Melotti4370b302010-11-03 20:39:14 +0000860 :meth:`failUnless` and :meth:`assert_`; use :meth:`assertTrue`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000861
Benjamin Peterson52baa292009-03-24 00:56:30 +0000862
Ezio Melotti4370b302010-11-03 20:39:14 +0000863 .. method:: assertFalse(expr, msg=None)
864 failIf(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000865
Ezio Melotti4370b302010-11-03 20:39:14 +0000866 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
867 This signals a test failure if *expr* is true, with *msg* or :const:`None`
868 for the error message.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000869
Raymond Hettinger35a88362009-04-09 00:08:24 +0000870 .. deprecated:: 3.1
Ezio Melotti4370b302010-11-03 20:39:14 +0000871 :meth:`failIf`; use :meth:`assertFalse`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000872
873
Ezio Melotti4370b302010-11-03 20:39:14 +0000874 .. method:: assertIs(expr1, expr2, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000875
Ezio Melotti4370b302010-11-03 20:39:14 +0000876 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
877 object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000878
Raymond Hettinger35a88362009-04-09 00:08:24 +0000879 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000880
881
Ezio Melotti4370b302010-11-03 20:39:14 +0000882 .. method:: assertIsNot(expr1, expr2, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000883
Ezio Melotti4370b302010-11-03 20:39:14 +0000884 The inverse of the :meth:`assertIs` method.
885 This signals a test failure if *expr1* and *expr2* evaluate to the same
886 object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000887
Raymond Hettinger35a88362009-04-09 00:08:24 +0000888 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000889
890
Ezio Melotti4370b302010-11-03 20:39:14 +0000891 .. method:: assertIsNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000892
Ezio Melotti4370b302010-11-03 20:39:14 +0000893 This signals a test failure if *expr* is not None.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000894
Raymond Hettinger35a88362009-04-09 00:08:24 +0000895 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000896
897
Ezio Melotti4370b302010-11-03 20:39:14 +0000898 .. method:: assertIsNotNone(expr, msg=None)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000899
Ezio Melotti4370b302010-11-03 20:39:14 +0000900 The inverse of the :meth:`assertIsNone` method.
901 This signals a test failure if *expr* is None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000902
Ezio Melotti4370b302010-11-03 20:39:14 +0000903 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000904
905
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000906 .. method:: assertIn(first, second, msg=None)
907 assertNotIn(first, second, msg=None)
908
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000909 Tests that *first* is or is not in *second* with an explanatory error
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000910 message as appropriate.
911
Michael Foordabd91d52010-03-20 18:09:14 +0000912 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000913
Raymond Hettinger35a88362009-04-09 00:08:24 +0000914 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000915
916
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000917 .. method:: assertIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000918
Ezio Melotti4370b302010-11-03 20:39:14 +0000919 This signals a test failure if *obj* is not an instance of *cls* (which
920 can be a class or a tuple of classes, as supported by :func:`isinstance`).
Michael Foordabd91d52010-03-20 18:09:14 +0000921
922 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000923
Georg Brandl67b21b72010-08-17 15:07:14 +0000924
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000925 .. method:: assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000926
Ezio Melotti4370b302010-11-03 20:39:14 +0000927 The inverse of the :meth:`assertIsInstance` method. This signals a test
928 failure if *obj* is an instance of *cls*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000929
Ezio Melotti4370b302010-11-03 20:39:14 +0000930 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000931
932
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000933
Ezio Melotti4370b302010-11-03 20:39:14 +0000934 It is also possible to check that exceptions and warnings are raised using
935 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000936
937
Ezio Melotti4370b302010-11-03 20:39:14 +0000938 +---------------------------------------------------------+--------------------------------------+------------+
939 | Method | Checks that | New in |
940 +=========================================================+======================================+============+
941 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | |
942 | <TestCase.assertRaises>` | | |
943 +---------------------------------------------------------+--------------------------------------+------------+
944 | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
945 | <TestCase.assertRaisesRegexp>` | and the message matches `re` | |
946 +---------------------------------------------------------+--------------------------------------+------------+
947 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
948 | <TestCase.assertWarns>` | | |
949 +---------------------------------------------------------+--------------------------------------+------------+
950 | :meth:`assertWarnsRegexp(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
951 | <TestCase.assertWarnsRegexp>` | and the message matches `re` | |
952 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000953
Georg Brandl7f01a132009-09-16 15:58:14 +0000954 .. method:: assertRaises(exception, callable, *args, **kwds)
955 failUnlessRaises(exception, callable, *args, **kwds)
956 assertRaises(exception)
957 failUnlessRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000958
959 Test that an exception is raised when *callable* is called with any
960 positional or keyword arguments that are also passed to
961 :meth:`assertRaises`. The test passes if *exception* is raised, is an
962 error if another exception is raised, or fails if no exception is raised.
963 To catch any of a group of exceptions, a tuple containing the exception
964 classes may be passed as *exception*.
965
Georg Brandl7f01a132009-09-16 15:58:14 +0000966 If only the *exception* argument is given, returns a context manager so
967 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000968
Michael Foord41531f22010-02-05 21:13:40 +0000969 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000970 do_something()
971
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000972 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000973 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000974 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000975
Georg Brandl8a1caa22010-07-29 16:01:11 +0000976 with self.assertRaises(SomeException) as cm:
977 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000978
Georg Brandl8a1caa22010-07-29 16:01:11 +0000979 the_exception = cm.exception
980 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000981
Ezio Melotti49008232010-02-08 21:57:48 +0000982 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000983 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000984
Ezio Melotti49008232010-02-08 21:57:48 +0000985 .. versionchanged:: 3.2
986 Added the :attr:`exception` attribute.
987
Raymond Hettinger35a88362009-04-09 00:08:24 +0000988 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000989 :meth:`failUnlessRaises`; use :meth:`assertRaises`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000990
Benjamin Peterson52baa292009-03-24 00:56:30 +0000991
Ezio Melotti327433f2010-11-03 20:51:17 +0000992 .. method:: assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
993 assertRaisesRegexp(exception, regexp)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000994
995 Like :meth:`assertRaises` but also tests that *regexp* matches
996 on the string representation of the raised exception. *regexp* may be
997 a regular expression object or a string containing a regular expression
998 suitable for use by :func:`re.search`. Examples::
999
1000 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
1001 int, 'XYZ')
1002
1003 or::
1004
1005 with self.assertRaisesRegexp(ValueError, 'literal'):
1006 int('XYZ')
1007
Raymond Hettinger35a88362009-04-09 00:08:24 +00001008 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001009
1010
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001011 .. method:: assertWarns(warning, callable, *args, **kwds)
1012 assertWarns(warning)
1013
1014 Test that a warning is triggered when *callable* is called with any
1015 positional or keyword arguments that are also passed to
1016 :meth:`assertWarns`. The test passes if *warning* is triggered and
1017 fails if it isn't. Also, any unexpected exception is an error.
1018 To catch any of a group of warnings, a tuple containing the warning
1019 classes may be passed as *warnings*.
1020
1021 If only the *warning* argument is given, returns a context manager so
1022 that the code under test can be written inline rather than as a function::
1023
1024 with self.assertWarns(SomeWarning):
1025 do_something()
1026
1027 The context manager will store the caught warning object in its
1028 :attr:`warning` attribute, and the source line which triggered the
1029 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1030 This can be useful if the intention is to perform additional checks
1031 on the exception raised::
1032
1033 with self.assertWarns(SomeWarning) as cm:
1034 do_something()
1035
1036 self.assertIn('myfile.py', cm.filename)
1037 self.assertEqual(320, cm.lineno)
1038
1039 This method works regardless of the warning filters in place when it
1040 is called.
1041
1042 .. versionadded:: 3.2
1043
1044
Ezio Melotti327433f2010-11-03 20:51:17 +00001045 .. method:: assertWarnsRegexp(warning, regexp, callable, *args, **kwds)
1046 assertWarnsRegexp(warning, regexp)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001047
1048 Like :meth:`assertWarns` but also tests that *regexp* matches on the
1049 message of the triggered warning. *regexp* may be a regular expression
1050 object or a string containing a regular expression suitable for use
1051 by :func:`re.search`. Example::
1052
1053 self.assertWarnsRegexp(DeprecationWarning,
1054 r'legacy_function\(\) is deprecated',
1055 legacy_function, 'XYZ')
1056
1057 or::
1058
1059 with self.assertWarnsRegexp(RuntimeWarning, 'unsafe frobnicating'):
1060 frobnicate('/etc/passwd')
1061
1062 .. versionadded:: 3.2
1063
1064
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001065
Ezio Melotti4370b302010-11-03 20:39:14 +00001066 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001067
Ezio Melotti4370b302010-11-03 20:39:14 +00001068 +---------------------------------------+--------------------------------+--------------+
1069 | Method | Checks that | New in |
1070 +=======================================+================================+==============+
1071 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1072 | <TestCase.assertAlmostEqual>` | | |
1073 +---------------------------------------+--------------------------------+--------------+
1074 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1075 | <TestCase.assertNotAlmostEqual>` | | |
1076 +---------------------------------------+--------------------------------+--------------+
1077 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1078 | <TestCase.assertGreater>` | | |
1079 +---------------------------------------+--------------------------------+--------------+
1080 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1081 | <TestCase.assertGreaterEqual>` | | |
1082 +---------------------------------------+--------------------------------+--------------+
1083 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1084 | <TestCase.assertLess>` | | |
1085 +---------------------------------------+--------------------------------+--------------+
1086 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1087 | <TestCase.assertLessEqual>` | | |
1088 +---------------------------------------+--------------------------------+--------------+
1089 | :meth:`assertRegexpMatches(s, re) | ``regex.search(s)`` | 3.1 |
1090 | <TestCase.assertRegexpMatches>` | | |
1091 +---------------------------------------+--------------------------------+--------------+
1092 | :meth:`assertNotRegexpMatches(s, re) | ``not regex.search(s)`` | 3.2 |
1093 | <TestCase.assertNotRegexpMatches>` | | |
1094 +---------------------------------------+--------------------------------+--------------+
1095 | :meth:`assertDictContainsSubset(a, b) | all the key/value pairs | 3.1 |
1096 | <TestCase.assertDictContainsSubset>` | in `a` exist in `b` | |
1097 +---------------------------------------+--------------------------------+--------------+
1098 | :meth:`assertItemsEqual(a, b) | `a` and `b` have the same | 3.2 |
1099 | <TestCase.assertItemsEqual>` | elements in the same number, | |
1100 | | regardless of their order | |
1101 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001102
1103
Ezio Melotti4370b302010-11-03 20:39:14 +00001104 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1105 failUnlessAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001106
Ezio Melotti4370b302010-11-03 20:39:14 +00001107 Test that *first* and *second* are approximately equal by computing the
1108 difference, rounding to the given number of decimal *places* (default 7),
1109 and comparing to zero.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001110
Ezio Melotti4370b302010-11-03 20:39:14 +00001111 Note that comparing a given number of decimal places is not the same as
1112 comparing a given number of significant digits. If the values do not
1113 compare equal, the test will fail with the explanation given by *msg*, or
1114 :const:`None`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001115
Ezio Melotti4370b302010-11-03 20:39:14 +00001116 If *delta* is supplied instead of *places* then the difference
1117 between *first* and *second* must be less than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001118
Ezio Melotti4370b302010-11-03 20:39:14 +00001119 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001120
Ezio Melotti4370b302010-11-03 20:39:14 +00001121 .. versionchanged:: 3.2
1122 Objects that compare equal are automatically almost equal.
1123 Added the ``delta`` keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001124
Raymond Hettinger35a88362009-04-09 00:08:24 +00001125 .. deprecated:: 3.1
Ezio Melotti4370b302010-11-03 20:39:14 +00001126 :meth:`failUnlessAlmostEqual`; use :meth:`assertAlmostEqual`.
1127
1128
1129 .. method:: assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
1130 failIfAlmostEqual(first, second, places=7, msg=None, delta=None)
1131
1132 Test that *first* and *second* are not approximately equal by computing
1133 the difference, rounding to the given number of decimal *places* (default
1134 7), and comparing to zero.
1135
1136 Note that comparing a given number of decimal places is not the same as
1137 comparing a given number of significant digits. If the values do not
1138 compare equal, the test will fail with the explanation given by *msg*, or
1139 :const:`None`.
1140
1141 If *delta* is supplied instead of *places* then the difference
1142 between *first* and *second* must be more than *delta*.
1143
1144 Supplying both *delta* and *places* raises a ``TypeError``.
1145
1146 .. versionchanged:: 3.2
1147 Objects that compare equal automatically fail. Added the ``delta``
1148 keyword argument.
1149
1150 .. deprecated:: 3.1
1151 :meth:`failIfAlmostEqual`; use :meth:`assertNotAlmostEqual`.
1152
1153
1154 .. method:: assertGreater(first, second, msg=None)
1155 assertGreaterEqual(first, second, msg=None)
1156 assertLess(first, second, msg=None)
1157 assertLessEqual(first, second, msg=None)
1158
1159 Test that *first* is respectively >, >=, < or <= than *second* depending
1160 on the method name. If not, the test will fail with an explanation
1161 or with the explanation given by *msg*::
1162
1163 >>> self.assertGreaterEqual(3, 4)
1164 AssertionError: "3" unexpectedly not greater than or equal to "4"
1165
1166 .. versionadded:: 3.1
1167
1168
1169 .. method:: assertRegexpMatches(text, regexp, msg=None)
1170
1171 Verifies that a *regexp* search matches *text*. Fails with an error
1172 message including the pattern and the *text*. *regexp* may be
1173 a regular expression object or a string containing a regular expression
1174 suitable for use by :func:`re.search`.
1175
1176 .. versionadded:: 3.1
1177
1178
1179 .. method:: assertNotRegexpMatches(text, regexp, msg=None)
1180
1181 Verifies that a *regexp* search does not match *text*. Fails with an error
1182 message including the pattern and the part of *text* that matches. *regexp*
1183 may be a regular expression object or a string containing a regular
1184 expression suitable for use by :func:`re.search`.
1185
1186 .. versionadded:: 3.2
1187
1188
1189 .. method:: assertDictContainsSubset(expected, actual, msg=None)
1190
1191 Tests whether the key/value pairs in dictionary *actual* are a
1192 superset of those in *expected*. If not, an error message listing
1193 the missing keys and mismatched values is generated.
1194
1195 If specified, *msg* will be used as the error message on failure.
1196
1197 .. versionadded:: 3.1
1198
1199
1200 .. method:: assertItemsEqual(actual, expected, msg=None)
1201
1202 Test that sequence *expected* contains the same elements as *actual*,
1203 regardless of their order. When they don't, an error message listing the
1204 differences between the sequences will be generated.
1205
1206 Duplicate elements are *not* ignored when comparing *actual* and
1207 *expected*. It verifies if each element has the same count in both
1208 sequences. It is the equivalent of ``assertEqual(sorted(expected),
1209 sorted(actual))`` but it works with sequences of unhashable objects as
1210 well.
1211
1212 If specified, *msg* will be used as the error message on failure.
1213
1214 .. versionadded:: 3.2
1215
1216
1217 .. method:: assertSameElements(actual, expected, msg=None)
1218
1219 Test that sequence *expected* contains the same elements as *actual*,
1220 regardless of their order. When they don't, an error message listing
1221 the differences between the sequences will be generated.
1222
1223 Duplicate elements are ignored when comparing *actual* and *expected*.
1224 It is the equivalent of ``assertEqual(set(expected), set(actual))``
1225 but it works with sequences of unhashable objects as well. Because
1226 duplicates are ignored, this method has been deprecated in favour of
1227 :meth:`assertItemsEqual`.
1228
1229 If specified, *msg* will be used as the error message on failure.
1230
1231 .. versionadded:: 3.1
1232 .. deprecated:: 3.2
1233
1234
1235
1236 The following methods are used automatically by :meth:`~TestCase.assertEqual`
1237 and usually is not necessary to invoke them directly:
1238
1239 +-----------------------------------------+-----------------------------+--------------+
1240 | Method | Used to compare | New in |
1241 +=========================================+=============================+==============+
1242 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1243 | <TestCase.assertMultiLineEqual>` | | |
1244 +-----------------------------------------+-----------------------------+--------------+
1245 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1246 | <TestCase.assertSequenceEqual>` | | |
1247 +-----------------------------------------+-----------------------------+--------------+
1248 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1249 | <TestCase.assertListEqual>` | | |
1250 +-----------------------------------------+-----------------------------+--------------+
1251 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1252 | <TestCase.assertTupleEqual>` | | |
1253 +-----------------------------------------+-----------------------------+--------------+
1254 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1255 | <TestCase.assertSetEqual>` | | |
1256 +-----------------------------------------+-----------------------------+--------------+
1257 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1258 | <TestCase.assertDictEqual>` | | |
1259 +-----------------------------------------+-----------------------------+--------------+
1260
1261
1262
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001263 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001264
1265 Test that the multiline string *first* is equal to the string *second*.
1266 When not equal a diff of the two strings highlighting the differences
1267 will be included in the error message. This method is used by default
1268 when comparing strings with :meth:`assertEqual`.
1269
1270 If specified, *msg* will be used as the error message on failure.
1271
1272 .. versionadded:: 3.1
1273
1274
1275 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
1276
1277 Tests that two sequences are equal. If a *seq_type* is supplied, both
1278 *seq1* and *seq2* must be instances of *seq_type* or a failure will
1279 be raised. If the sequences are different an error message is
1280 constructed that shows the difference between the two.
1281
1282 If specified, *msg* will be used as the error message on failure.
1283
1284 This method is used to implement :meth:`assertListEqual` and
1285 :meth:`assertTupleEqual`.
1286
1287 .. versionadded:: 3.1
1288
1289
1290 .. method:: assertListEqual(list1, list2, msg=None)
1291 assertTupleEqual(tuple1, tuple2, msg=None)
1292
1293 Tests that two lists or tuples are equal. If not an error message is
1294 constructed that shows only the differences between the two. An error
1295 is also raised if either of the parameters are of the wrong type.
1296 These methods are used by default when comparing lists or tuples with
1297 :meth:`assertEqual`.
1298
1299 If specified, *msg* will be used as the error message on failure.
1300
1301 .. versionadded:: 3.1
1302
1303
1304 .. method:: assertSetEqual(set1, set2, msg=None)
1305
1306 Tests that two sets are equal. If not, an error message is constructed
1307 that lists the differences between the sets. This method is used by
1308 default when comparing sets or frozensets with :meth:`assertEqual`.
1309
1310 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
1311 method.
1312
1313 If specified, *msg* will be used as the error message on failure.
1314
1315 .. versionadded:: 3.1
1316
1317
1318 .. method:: assertDictEqual(expected, actual, msg=None)
1319
1320 Test that two dictionaries are equal. If not, an error message is
1321 constructed that shows the differences in the dictionaries. This
1322 method will be used by default to compare dictionaries in
1323 calls to :meth:`assertEqual`.
1324
1325 If specified, *msg* will be used as the error message on failure.
1326
1327 .. versionadded:: 3.1
1328
1329
1330
1331 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001332
Benjamin Peterson52baa292009-03-24 00:56:30 +00001333
Georg Brandl7f01a132009-09-16 15:58:14 +00001334 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001335
1336 Signals a test failure unconditionally, with *msg* or :const:`None` for
1337 the error message.
1338
1339
1340 .. attribute:: failureException
1341
1342 This class attribute gives the exception raised by the test method. If a
1343 test framework needs to use a specialized exception, possibly to carry
1344 additional information, it must subclass this exception in order to "play
1345 fair" with the framework. The initial value of this attribute is
1346 :exc:`AssertionError`.
1347
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001348
1349 .. attribute:: longMessage
1350
1351 If set to True then any explicit failure message you pass in to the
1352 assert methods will be appended to the end of the normal failure message.
1353 The normal messages contain useful information about the objects involved,
1354 for example the message from assertEqual shows you the repr of the two
1355 unequal objects. Setting this attribute to True allows you to have a
1356 custom error message in addition to the normal one.
1357
1358 This attribute defaults to False, meaning that a custom message passed
1359 to an assert method will silence the normal message.
1360
1361 The class setting can be overridden in individual tests by assigning an
1362 instance attribute to True or False before calling the assert methods.
1363
Raymond Hettinger35a88362009-04-09 00:08:24 +00001364 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001365
1366
Michael Foord98b3e762010-06-05 21:59:55 +00001367 .. attribute:: maxDiff
1368
1369 This attribute controls the maximum length of diffs output by assert
1370 methods that report diffs on failure. It defaults to 80*8 characters.
1371 Assert methods affected by this attribute are
1372 :meth:`assertSequenceEqual` (including all the sequence comparison
1373 methods that delegate to it), :meth:`assertDictEqual` and
1374 :meth:`assertMultiLineEqual`.
1375
1376 Setting ``maxDiff`` to None means that there is no maximum length of
1377 diffs.
1378
1379 .. versionadded:: 3.2
1380
1381
Benjamin Peterson52baa292009-03-24 00:56:30 +00001382 Testing frameworks can use the following methods to collect information on
1383 the test:
1384
1385
1386 .. method:: countTestCases()
1387
1388 Return the number of tests represented by this test object. For
1389 :class:`TestCase` instances, this will always be ``1``.
1390
1391
1392 .. method:: defaultTestResult()
1393
1394 Return an instance of the test result class that should be used for this
1395 test case class (if no other result instance is provided to the
1396 :meth:`run` method).
1397
1398 For :class:`TestCase` instances, this will always be an instance of
1399 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1400 as necessary.
1401
1402
1403 .. method:: id()
1404
1405 Return a string identifying the specific test case. This is usually the
1406 full name of the test method, including the module and class name.
1407
1408
1409 .. method:: shortDescription()
1410
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001411 Returns a description of the test, or :const:`None` if no description
1412 has been provided. The default implementation of this method
1413 returns the first line of the test method's docstring, if available,
Michael Foord34c94622010-02-10 15:51:42 +00001414 or :const:`None`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001415
Michael Foord34c94622010-02-10 15:51:42 +00001416 .. versionchanged:: 3.1,3.2
1417 In 3.1 this was changed to add the test name to the short description
1418 even in the presence of a docstring. This caused compatibility issues
1419 with unittest extensions and adding the test name was moved to the
1420 :class:`TextTestResult`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001421
1422 .. method:: addTypeEqualityFunc(typeobj, function)
1423
1424 Registers a type specific :meth:`assertEqual` equality checking
1425 function to be called by :meth:`assertEqual` when both objects it has
1426 been asked to compare are exactly *typeobj* (not subclasses).
1427 *function* must take two positional arguments and a third msg=None
1428 keyword argument just as :meth:`assertEqual` does. It must raise
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001429 ``self.failureException`` when inequality between the first two
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001430 parameters is detected.
1431
1432 One good use of custom equality checking functions for a type
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001433 is to raise ``self.failureException`` with an error message useful
1434 for debugging the problem by explaining the inequalities in detail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001435
Raymond Hettinger35a88362009-04-09 00:08:24 +00001436 .. versionadded:: 3.1
Georg Brandl116aa622007-08-15 14:28:22 +00001437
1438
Georg Brandl7f01a132009-09-16 15:58:14 +00001439 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001440
1441 Add a function to be called after :meth:`tearDown` to cleanup resources
1442 used during the test. Functions will be called in reverse order to the
1443 order they are added (LIFO). They are called with any arguments and
1444 keyword arguments passed into :meth:`addCleanup` when they are
1445 added.
1446
1447 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1448 then any cleanup functions added will still be called.
1449
Georg Brandl853947a2010-01-31 18:53:23 +00001450 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001451
1452
1453 .. method:: doCleanups()
1454
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001455 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001456 after :meth:`setUp` if :meth:`setUp` raises an exception.
1457
1458 It is responsible for calling all the cleanup functions added by
1459 :meth:`addCleanup`. If you need cleanup functions to be called
1460 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1461 yourself.
1462
1463 :meth:`doCleanups` pops methods off the stack of cleanup
1464 functions one at a time, so it can be called at any time.
1465
Georg Brandl853947a2010-01-31 18:53:23 +00001466 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001467
1468
Georg Brandl7f01a132009-09-16 15:58:14 +00001469.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001470
1471 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001472 allows the test runner to drive the test, but does not provide the methods
1473 which test code can use to check and report errors. This is used to create
1474 test cases using legacy test code, allowing it to be integrated into a
1475 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001476
1477
Benjamin Peterson52baa292009-03-24 00:56:30 +00001478.. _testsuite-objects:
1479
Benjamin Peterson52baa292009-03-24 00:56:30 +00001480Grouping tests
1481~~~~~~~~~~~~~~
1482
Georg Brandl7f01a132009-09-16 15:58:14 +00001483.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001484
1485 This class represents an aggregation of individual tests cases and test suites.
1486 The class presents the interface needed by the test runner to allow it to be run
1487 as any other test case. Running a :class:`TestSuite` instance is the same as
1488 iterating over the suite, running each test individually.
1489
1490 If *tests* is given, it must be an iterable of individual test cases or other
1491 test suites that will be used to build the suite initially. Additional methods
1492 are provided to add test cases and suites to the collection later on.
1493
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001494 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1495 they do not actually implement a test. Instead, they are used to aggregate
1496 tests into groups of tests that should be run together. Some additional
1497 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001498
1499
1500 .. method:: TestSuite.addTest(test)
1501
1502 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1503
1504
1505 .. method:: TestSuite.addTests(tests)
1506
1507 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1508 instances to this test suite.
1509
Benjamin Petersond2397752009-06-27 23:45:02 +00001510 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1511 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001512
1513 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1514
1515
1516 .. method:: run(result)
1517
1518 Run the tests associated with this suite, collecting the result into the
1519 test result object passed as *result*. Note that unlike
1520 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1521 be passed in.
1522
1523
1524 .. method:: debug()
1525
1526 Run the tests associated with this suite without collecting the
1527 result. This allows exceptions raised by the test to be propagated to the
1528 caller and can be used to support running tests under a debugger.
1529
1530
1531 .. method:: countTestCases()
1532
1533 Return the number of tests represented by this test object, including all
1534 individual tests and sub-suites.
1535
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001536
1537 .. method:: __iter__()
1538
1539 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1540 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1541 that this method maybe called several times on a single suite
1542 (for example when counting tests or comparing for equality)
1543 so the tests returned must be the same for repeated iterations.
1544
Georg Brandl853947a2010-01-31 18:53:23 +00001545 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001546 In earlier versions the :class:`TestSuite` accessed tests directly rather
1547 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1548 for providing tests.
1549
Benjamin Peterson52baa292009-03-24 00:56:30 +00001550 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1551 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1552
1553
Benjamin Peterson52baa292009-03-24 00:56:30 +00001554Loading and running tests
1555~~~~~~~~~~~~~~~~~~~~~~~~~
1556
Georg Brandl116aa622007-08-15 14:28:22 +00001557.. class:: TestLoader()
1558
Benjamin Peterson52baa292009-03-24 00:56:30 +00001559 The :class:`TestLoader` class is used to create test suites from classes and
1560 modules. Normally, there is no need to create an instance of this class; the
1561 :mod:`unittest` module provides an instance that can be shared as
1562 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1563 customization of some configurable properties.
1564
1565 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001566
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001567
Benjamin Peterson52baa292009-03-24 00:56:30 +00001568 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001569
Benjamin Peterson52baa292009-03-24 00:56:30 +00001570 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1571 :class:`testCaseClass`.
1572
1573
1574 .. method:: loadTestsFromModule(module)
1575
1576 Return a suite of all tests cases contained in the given module. This
1577 method searches *module* for classes derived from :class:`TestCase` and
1578 creates an instance of the class for each test method defined for the
1579 class.
1580
Georg Brandle720c0a2009-04-27 16:20:50 +00001581 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001582
1583 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1584 convenient in sharing fixtures and helper functions, defining test
1585 methods on base classes that are not intended to be instantiated
1586 directly does not play well with this method. Doing so, however, can
1587 be useful when the fixtures are different and defined in subclasses.
1588
Benjamin Petersond2397752009-06-27 23:45:02 +00001589 If a module provides a ``load_tests`` function it will be called to
1590 load the tests. This allows modules to customize test loading.
1591 This is the `load_tests protocol`_.
1592
Georg Brandl853947a2010-01-31 18:53:23 +00001593 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001594 Support for ``load_tests`` added.
1595
Benjamin Peterson52baa292009-03-24 00:56:30 +00001596
Georg Brandl7f01a132009-09-16 15:58:14 +00001597 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001598
1599 Return a suite of all tests cases given a string specifier.
1600
1601 The specifier *name* is a "dotted name" that may resolve either to a
1602 module, a test case class, a test method within a test case class, a
1603 :class:`TestSuite` instance, or a callable object which returns a
1604 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1605 applied in the order listed here; that is, a method on a possible test
1606 case class will be picked up as "a test method within a test case class",
1607 rather than "a callable object".
1608
1609 For example, if you have a module :mod:`SampleTests` containing a
1610 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1611 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001612 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1613 return a suite which will run all three test methods. Using the specifier
1614 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1615 suite which will run only the :meth:`test_two` test method. The specifier
1616 can refer to modules and packages which have not been imported; they will
1617 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001618
1619 The method optionally resolves *name* relative to the given *module*.
1620
1621
Georg Brandl7f01a132009-09-16 15:58:14 +00001622 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001623
1624 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1625 than a single name. The return value is a test suite which supports all
1626 the tests defined for each name.
1627
1628
1629 .. method:: getTestCaseNames(testCaseClass)
1630
1631 Return a sorted sequence of method names found within *testCaseClass*;
1632 this should be a subclass of :class:`TestCase`.
1633
Benjamin Petersond2397752009-06-27 23:45:02 +00001634
1635 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1636
1637 Find and return all test modules from the specified start directory,
1638 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001639 *pattern* will be loaded. (Using shell style pattern matching.) Only
1640 module names that are importable (i.e. are valid Python identifiers) will
1641 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001642
1643 All test modules must be importable from the top level of the project. If
1644 the start directory is not the top level directory then the top level
1645 directory must be specified separately.
1646
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001647 If importing a module fails, for example due to a syntax error, then this
1648 will be recorded as a single error and discovery will continue.
1649
Benjamin Petersond2397752009-06-27 23:45:02 +00001650 If a test package name (directory with :file:`__init__.py`) matches the
1651 pattern then the package will be checked for a ``load_tests``
1652 function. If this exists then it will be called with *loader*, *tests*,
1653 *pattern*.
1654
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001655 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001656 ``load_tests`` is responsible for loading all tests in the package.
1657
1658 The pattern is deliberately not stored as a loader attribute so that
1659 packages can continue discovery themselves. *top_level_dir* is stored so
1660 ``load_tests`` does not need to pass this argument in to
1661 ``loader.discover()``.
1662
Benjamin Petersonb48af542010-04-11 20:43:16 +00001663 *start_dir* can be a dotted module name as well as a directory.
1664
Georg Brandl853947a2010-01-31 18:53:23 +00001665 .. versionadded:: 3.2
1666
Benjamin Petersond2397752009-06-27 23:45:02 +00001667
Benjamin Peterson52baa292009-03-24 00:56:30 +00001668 The following attributes of a :class:`TestLoader` can be configured either by
1669 subclassing or assignment on an instance:
1670
1671
1672 .. attribute:: testMethodPrefix
1673
1674 String giving the prefix of method names which will be interpreted as test
1675 methods. The default value is ``'test'``.
1676
1677 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1678 methods.
1679
1680
1681 .. attribute:: sortTestMethodsUsing
1682
1683 Function to be used to compare method names when sorting them in
1684 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1685
1686
1687 .. attribute:: suiteClass
1688
1689 Callable object that constructs a test suite from a list of tests. No
1690 methods on the resulting object are needed. The default value is the
1691 :class:`TestSuite` class.
1692
1693 This affects all the :meth:`loadTestsFrom\*` methods.
1694
1695
Benjamin Peterson52baa292009-03-24 00:56:30 +00001696.. class:: TestResult
1697
1698 This class is used to compile information about which tests have succeeded
1699 and which have failed.
1700
1701 A :class:`TestResult` object stores the results of a set of tests. The
1702 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1703 properly recorded; test authors do not need to worry about recording the
1704 outcome of tests.
1705
1706 Testing frameworks built on top of :mod:`unittest` may want access to the
1707 :class:`TestResult` object generated by running a set of tests for reporting
1708 purposes; a :class:`TestResult` instance is returned by the
1709 :meth:`TestRunner.run` method for this purpose.
1710
1711 :class:`TestResult` instances have the following attributes that will be of
1712 interest when inspecting the results of running a set of tests:
1713
1714
1715 .. attribute:: errors
1716
1717 A list containing 2-tuples of :class:`TestCase` instances and strings
1718 holding formatted tracebacks. Each tuple represents a test which raised an
1719 unexpected exception.
1720
Benjamin Peterson52baa292009-03-24 00:56:30 +00001721 .. attribute:: failures
1722
1723 A list containing 2-tuples of :class:`TestCase` instances and strings
1724 holding formatted tracebacks. Each tuple represents a test where a failure
1725 was explicitly signalled using the :meth:`TestCase.fail\*` or
1726 :meth:`TestCase.assert\*` methods.
1727
Benjamin Peterson52baa292009-03-24 00:56:30 +00001728 .. attribute:: skipped
1729
1730 A list containing 2-tuples of :class:`TestCase` instances and strings
1731 holding the reason for skipping the test.
1732
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001733 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001734
1735 .. attribute:: expectedFailures
1736
Georg Brandl6faee4e2010-09-21 14:48:28 +00001737 A list containing 2-tuples of :class:`TestCase` instances and strings
1738 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001739 of the test case.
1740
1741 .. attribute:: unexpectedSuccesses
1742
1743 A list containing :class:`TestCase` instances that were marked as expected
1744 failures, but succeeded.
1745
1746 .. attribute:: shouldStop
1747
1748 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1749
1750
1751 .. attribute:: testsRun
1752
1753 The total number of tests run so far.
1754
1755
Benjamin Petersonb48af542010-04-11 20:43:16 +00001756 .. attribute:: buffer
1757
1758 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1759 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1760 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1761 fails or errors. Any output is also attached to the failure / error message.
1762
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001763 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001764
1765
1766 .. attribute:: failfast
1767
1768 If set to true :meth:`stop` will be called on the first failure or error,
1769 halting the test run.
1770
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001771 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001772
1773
Benjamin Peterson52baa292009-03-24 00:56:30 +00001774 .. method:: wasSuccessful()
1775
1776 Return :const:`True` if all tests run so far have passed, otherwise returns
1777 :const:`False`.
1778
1779
1780 .. method:: stop()
1781
1782 This method can be called to signal that the set of tests being run should
1783 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1784 :class:`TestRunner` objects should respect this flag and return without
1785 running any additional tests.
1786
1787 For example, this feature is used by the :class:`TextTestRunner` class to
1788 stop the test framework when the user signals an interrupt from the
1789 keyboard. Interactive tools which provide :class:`TestRunner`
1790 implementations can use this in a similar manner.
1791
1792 The following methods of the :class:`TestResult` class are used to maintain
1793 the internal data structures, and may be extended in subclasses to support
1794 additional reporting requirements. This is particularly useful in building
1795 tools which support interactive reporting while tests are being run.
1796
1797
1798 .. method:: startTest(test)
1799
1800 Called when the test case *test* is about to be run.
1801
Benjamin Peterson52baa292009-03-24 00:56:30 +00001802 .. method:: stopTest(test)
1803
1804 Called after the test case *test* has been executed, regardless of the
1805 outcome.
1806
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001807 .. method:: startTestRun(test)
1808
1809 Called once before any tests are executed.
1810
Georg Brandl853947a2010-01-31 18:53:23 +00001811 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001812
1813
1814 .. method:: stopTestRun(test)
1815
Ezio Melotti176d6c42010-01-27 20:58:07 +00001816 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001817
Georg Brandl853947a2010-01-31 18:53:23 +00001818 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001819
1820
Benjamin Peterson52baa292009-03-24 00:56:30 +00001821 .. method:: addError(test, err)
1822
1823 Called when the test case *test* raises an unexpected exception *err* is a
1824 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1825 traceback)``.
1826
1827 The default implementation appends a tuple ``(test, formatted_err)`` to
1828 the instance's :attr:`errors` attribute, where *formatted_err* is a
1829 formatted traceback derived from *err*.
1830
1831
1832 .. method:: addFailure(test, err)
1833
Benjamin Petersond2397752009-06-27 23:45:02 +00001834 Called when the test case *test* signals a failure. *err* is a tuple of
1835 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001836
1837 The default implementation appends a tuple ``(test, formatted_err)`` to
1838 the instance's :attr:`failures` attribute, where *formatted_err* is a
1839 formatted traceback derived from *err*.
1840
1841
1842 .. method:: addSuccess(test)
1843
1844 Called when the test case *test* succeeds.
1845
1846 The default implementation does nothing.
1847
1848
1849 .. method:: addSkip(test, reason)
1850
1851 Called when the test case *test* is skipped. *reason* is the reason the
1852 test gave for skipping.
1853
1854 The default implementation appends a tuple ``(test, reason)`` to the
1855 instance's :attr:`skipped` attribute.
1856
1857
1858 .. method:: addExpectedFailure(test, err)
1859
1860 Called when the test case *test* fails, but was marked with the
1861 :func:`expectedFailure` decorator.
1862
1863 The default implementation appends a tuple ``(test, formatted_err)`` to
1864 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1865 is a formatted traceback derived from *err*.
1866
1867
1868 .. method:: addUnexpectedSuccess(test)
1869
1870 Called when the test case *test* was marked with the
1871 :func:`expectedFailure` decorator, but succeeded.
1872
1873 The default implementation appends the test to the instance's
1874 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001875
Georg Brandl67b21b72010-08-17 15:07:14 +00001876
Michael Foord34c94622010-02-10 15:51:42 +00001877.. class:: TextTestResult(stream, descriptions, verbosity)
1878
Georg Brandl67b21b72010-08-17 15:07:14 +00001879 A concrete implementation of :class:`TestResult` used by the
1880 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001881
Georg Brandl67b21b72010-08-17 15:07:14 +00001882 .. versionadded:: 3.2
1883 This class was previously named ``_TextTestResult``. The old name still
1884 exists as an alias but is deprecated.
1885
Georg Brandl116aa622007-08-15 14:28:22 +00001886
1887.. data:: defaultTestLoader
1888
1889 Instance of the :class:`TestLoader` class intended to be shared. If no
1890 customization of the :class:`TestLoader` is needed, this instance can be used
1891 instead of repeatedly creating new instances.
1892
1893
Michael Foord34c94622010-02-10 15:51:42 +00001894.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001895
1896 A basic test runner implementation which prints results on standard error. It
1897 has a few configurable parameters, but is essentially very simple. Graphical
1898 applications which run test suites should provide alternate implementations.
1899
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001900 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001901
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001902 This method returns the instance of ``TestResult`` used by :meth:`run`.
1903 It is not intended to be called directly, but can be overridden in
1904 subclasses to provide a custom ``TestResult``.
1905
Michael Foord34c94622010-02-10 15:51:42 +00001906 ``_makeResult()`` instantiates the class or callable passed in the
1907 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001908 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001909 The result class is instantiated with the following arguments::
1910
1911 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001912
Benjamin Petersonb48af542010-04-11 20:43:16 +00001913.. 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 +00001914
1915 A command-line program that runs a set of tests; this is primarily for making
1916 test modules conveniently executable. The simplest use for this function is to
1917 include the following line at the end of a test script::
1918
1919 if __name__ == '__main__':
1920 unittest.main()
1921
Benjamin Petersond2397752009-06-27 23:45:02 +00001922 You can run tests with more detailed information by passing in the verbosity
1923 argument::
1924
1925 if __name__ == '__main__':
1926 unittest.main(verbosity=2)
1927
Georg Brandl116aa622007-08-15 14:28:22 +00001928 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001929 created instance of it. By default ``main`` calls :func:`sys.exit` with
1930 an exit code indicating success or failure of the tests run.
1931
1932 ``main`` supports being used from the interactive interpreter by passing in the
1933 argument ``exit=False``. This displays the result on standard output without
1934 calling :func:`sys.exit`::
1935
1936 >>> from unittest import main
1937 >>> main(module='test_module', exit=False)
1938
Benjamin Petersonb48af542010-04-11 20:43:16 +00001939 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
1940 effect as the `failfast, catch and buffer command line options`_.
1941
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001942 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1943 This stores the result of the tests run as the ``result`` attribute.
1944
Georg Brandl853947a2010-01-31 18:53:23 +00001945 .. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001946 The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
1947 parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001948
1949
1950load_tests Protocol
1951###################
1952
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001953
Georg Brandl853947a2010-01-31 18:53:23 +00001954.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001955
1956
Benjamin Petersond2397752009-06-27 23:45:02 +00001957Modules or packages can customize how tests are loaded from them during normal
1958test runs or test discovery by implementing a function called ``load_tests``.
1959
1960If a test module defines ``load_tests`` it will be called by
1961:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1962
1963 load_tests(loader, standard_tests, None)
1964
1965It should return a :class:`TestSuite`.
1966
1967*loader* is the instance of :class:`TestLoader` doing the loading.
1968*standard_tests* are the tests that would be loaded by default from the
1969module. It is common for test modules to only want to add or remove tests
1970from the standard set of tests.
1971The third argument is used when loading packages as part of test discovery.
1972
1973A typical ``load_tests`` function that loads tests from a specific set of
1974:class:`TestCase` classes may look like::
1975
1976 test_cases = (TestCase1, TestCase2, TestCase3)
1977
1978 def load_tests(loader, tests, pattern):
1979 suite = TestSuite()
1980 for test_class in test_cases:
1981 tests = loader.loadTestsFromTestCase(test_class)
1982 suite.addTests(tests)
1983 return suite
1984
1985If discovery is started, either from the command line or by calling
1986:meth:`TestLoader.discover`, with a pattern that matches a package
1987name then the package :file:`__init__.py` will be checked for ``load_tests``.
1988
1989.. note::
1990
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001991 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00001992 that start with 'test' but *won't* match any test directories.
1993
1994 A pattern like 'test*' will match test packages as well as
1995 modules.
1996
1997If the package :file:`__init__.py` defines ``load_tests`` then it will be
1998called and discovery not continued into the package. ``load_tests``
1999is called with the following arguments::
2000
2001 load_tests(loader, standard_tests, pattern)
2002
2003This should return a :class:`TestSuite` representing all the tests
2004from the package. (``standard_tests`` will only contain tests
2005collected from :file:`__init__.py`.)
2006
2007Because the pattern is passed into ``load_tests`` the package is free to
2008continue (and potentially modify) test discovery. A 'do nothing'
2009``load_tests`` function for a test package would look like::
2010
2011 def load_tests(loader, standard_tests, pattern):
2012 # top level directory cached on loader instance
2013 this_dir = os.path.dirname(__file__)
2014 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2015 standard_tests.addTests(package_tests)
2016 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002017
2018
2019Class and Module Fixtures
2020-------------------------
2021
2022Class and module level fixtures are implemented in :class:`TestSuite`. When
2023the test suite encounters a test from a new class then :meth:`tearDownClass`
2024from the previous class (if there is one) is called, followed by
2025:meth:`setUpClass` from the new class.
2026
2027Similarly if a test is from a different module from the previous test then
2028``tearDownModule`` from the previous module is run, followed by
2029``setUpModule`` from the new module.
2030
2031After all the tests have run the final ``tearDownClass`` and
2032``tearDownModule`` are run.
2033
2034Note that shared fixtures do not play well with [potential] features like test
2035parallelization and they break test isolation. They should be used with care.
2036
2037The default ordering of tests created by the unittest test loaders is to group
2038all tests from the same modules and classes together. This will lead to
2039``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2040module. If you randomize the order, so that tests from different modules and
2041classes are adjacent to each other, then these shared fixture functions may be
2042called multiple times in a single test run.
2043
2044Shared fixtures are not intended to work with suites with non-standard
2045ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2046support shared fixtures.
2047
2048If there are any exceptions raised during one of the shared fixture functions
2049the test is reported as an error. Because there is no corresponding test
2050instance an ``_ErrorHolder`` object (that has the same interface as a
2051:class:`TestCase`) is created to represent the error. If you are just using
2052the standard unittest test runner then this detail doesn't matter, but if you
2053are a framework author it may be relevant.
2054
2055
2056setUpClass and tearDownClass
2057~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2058
2059These must be implemented as class methods::
2060
2061 import unittest
2062
2063 class Test(unittest.TestCase):
2064 @classmethod
2065 def setUpClass(cls):
2066 cls._connection = createExpensiveConnectionObject()
2067
2068 @classmethod
2069 def tearDownClass(cls):
2070 cls._connection.destroy()
2071
2072If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2073then you must call up to them yourself. The implementations in
2074:class:`TestCase` are empty.
2075
2076If an exception is raised during a ``setUpClass`` then the tests in the class
2077are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002078have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
2079``SkipTest`` exception then the class will be reported as having been skipped
2080instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002081
2082
2083setUpModule and tearDownModule
2084~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2085
2086These should be implemented as functions::
2087
2088 def setUpModule():
2089 createConnection()
2090
2091 def tearDownModule():
2092 closeConnection()
2093
2094If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002095module will be run and the ``tearDownModule`` will not be run. If the exception is a
2096``SkipTest`` exception then the module will be reported as having been skipped
2097instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002098
2099
2100Signal Handling
2101---------------
2102
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002103The :option:`-c`/:option:`--catch` command line option to unittest, along with the ``catchbreak``
Benjamin Petersonb48af542010-04-11 20:43:16 +00002104parameter to :func:`unittest.main()`, provide more friendly handling of
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002105control-C during a test run. With catch break behavior enabled control-C will
Benjamin Petersonb48af542010-04-11 20:43:16 +00002106allow the currently running test to complete, and the test run will then end
2107and report all the results so far. A second control-c will raise a
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002108:exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002109
Michael Foordde4ceab2010-04-25 19:53:49 +00002110The control-c handling signal handler attempts to remain compatible with code or
2111tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2112handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2113i.e. it has been replaced by the system under test and delegated to, then it
2114calls the default handler. This will normally be the expected behavior by code
2115that replaces an installed handler and delegates to it. For individual tests
2116that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2117decorator can be used.
2118
2119There are a few utility functions for framework authors to enable control-c
2120handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002121
2122.. function:: installHandler()
2123
2124 Install the control-c handler. When a :const:`signal.SIGINT` is received
2125 (usually in response to the user pressing control-c) all registered results
2126 have :meth:`~TestResult.stop` called.
2127
Michael Foord469b1f02010-04-26 23:41:26 +00002128 .. versionadded:: 3.2
2129
Benjamin Petersonb48af542010-04-11 20:43:16 +00002130.. function:: registerResult(result)
2131
2132 Register a :class:`TestResult` object for control-c handling. Registering a
2133 result stores a weak reference to it, so it doesn't prevent the result from
2134 being garbage collected.
2135
Michael Foordde4ceab2010-04-25 19:53:49 +00002136 Registering a :class:`TestResult` object has no side-effects if control-c
2137 handling is not enabled, so test frameworks can unconditionally register
2138 all results they create independently of whether or not handling is enabled.
2139
Michael Foord469b1f02010-04-26 23:41:26 +00002140 .. versionadded:: 3.2
2141
Benjamin Petersonb48af542010-04-11 20:43:16 +00002142.. function:: removeResult(result)
2143
2144 Remove a registered result. Once a result has been removed then
2145 :meth:`~TestResult.stop` will no longer be called on that result object in
2146 response to a control-c.
2147
Michael Foord469b1f02010-04-26 23:41:26 +00002148 .. versionadded:: 3.2
2149
Michael Foordde4ceab2010-04-25 19:53:49 +00002150.. function:: removeHandler(function=None)
2151
2152 When called without arguments this function removes the control-c handler
2153 if it has been installed. This function can also be used as a test decorator
2154 to temporarily remove the handler whilst the test is being executed::
2155
2156 @unittest.removeHandler
2157 def test_signal_handling(self):
2158 ...
2159
Michael Foord469b1f02010-04-26 23:41:26 +00002160 .. versionadded:: 3.2
2161