blob: d463d7f462ec92362334dc11a0d3ac998c9f9f17 [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`
Éric Araujo713d3032010-11-18 16:38:46 +0000157provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000158line, 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
Éric Araujo713d3032010-11-18 16:38:46 +0000209For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000210
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
Éric Araujo713d3032010-11-18 16:38:46 +0000218failfast, catch and buffer command-line options
Benjamin Petersonb48af542010-04-11 20:43:16 +0000219~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
220
Éric Araujo713d3032010-11-18 16:38:46 +0000221:program:`unittest` supports three command-line options.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000222
Éric Araujo713d3032010-11-18 16:38:46 +0000223.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000224
Éric Araujo713d3032010-11-18 16:38:46 +0000225.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000226
Éric Araujo713d3032010-11-18 16:38:46 +0000227 The standard output and standard error streams are buffered during the test
228 run. Output during a passing test is discarded. Output is echoed normally
229 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000230
Éric Araujo713d3032010-11-18 16:38:46 +0000231.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000232
Éric Araujo713d3032010-11-18 16:38:46 +0000233 Control-C during the test run waits for the current test to end and then
234 reports all the results so far. A second control-C raises the normal
235 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000236
Éric Araujo713d3032010-11-18 16:38:46 +0000237 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000238
Éric Araujo713d3032010-11-18 16:38:46 +0000239.. cmdoption:: -f, --failfast
240
241 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000242
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000243.. versionadded:: 3.2
Éric Araujo713d3032010-11-18 16:38:46 +0000244 The command-line options :option:`-c`, :option:`-b` and :option:`-f` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000245
246The command line can also be used for test discovery, for running all of the
247tests in a project or just a subset.
248
249
250.. _unittest-test-discovery:
251
252Test Discovery
253--------------
254
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000255.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000256
257Unittest supports simple test discovery. For a project's tests to be
258compatible with test discovery they must all be importable from the top level
259directory of the project (in other words, they must all be in Python packages).
260
261Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000262used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000263
264 cd project_directory
265 python -m unittest discover
266
267The ``discover`` sub-command has the following options:
268
Éric Araujo713d3032010-11-18 16:38:46 +0000269.. program:: unittest discover
270
271.. cmdoption:: -v, --verbose
272
273 Verbose output
274
275.. cmdoption:: -s directory
276
277 Directory to start discovery ('.' default)
278
279.. cmdoption:: -p pattern
280
281 Pattern to match test files ('test*.py' default)
282
283.. cmdoption:: -t directory
284
285 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000286
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000287The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
288as positional arguments in that order. The following two command lines
289are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000290
291 python -m unittest discover -s project_directory -p '*_test.py'
292 python -m unittest discover project_directory '*_test.py'
293
Michael Foord16f3e902010-05-08 15:13:42 +0000294As well as being a path it is possible to pass a package name, for example
295``myproject.subpackage.test``, as the start directory. The package name you
296supply will then be imported and its location on the filesystem will be used
297as the start directory.
298
299.. caution::
300
Senthil Kumaran916bd382010-10-15 12:55:19 +0000301 Test discovery loads tests by importing them. Once test discovery has found
302 all the test files from the start directory you specify it turns the paths
303 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000304 imported as ``foo.bar.baz``.
305
306 If you have a package installed globally and attempt test discovery on
307 a different copy of the package then the import *could* happen from the
308 wrong place. If this happens test discovery will warn you and exit.
309
310 If you supply the start directory as a package name rather than a
311 path to a directory then discover assumes that whichever location it
312 imports from is the location you intended, so you will not get the
313 warning.
314
Benjamin Petersonb48af542010-04-11 20:43:16 +0000315Test modules and packages can customize test loading and discovery by through
316the `load_tests protocol`_.
317
318
Georg Brandl116aa622007-08-15 14:28:22 +0000319.. _organizing-tests:
320
321Organizing test code
322--------------------
323
324The basic building blocks of unit testing are :dfn:`test cases` --- single
325scenarios that must be set up and checked for correctness. In :mod:`unittest`,
326test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
327class. To make your own test cases you must write subclasses of
328:class:`TestCase`, or use :class:`FunctionTestCase`.
329
330An instance of a :class:`TestCase`\ -derived class is an object that can
331completely run a single test method, together with optional set-up and tidy-up
332code.
333
334The testing code of a :class:`TestCase` instance should be entirely self
335contained, such that it can be run either in isolation or in arbitrary
336combination with any number of other test cases.
337
Benjamin Peterson52baa292009-03-24 00:56:30 +0000338The simplest :class:`TestCase` subclass will simply override the
339:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000340
341 import unittest
342
343 class DefaultWidgetSizeTestCase(unittest.TestCase):
344 def runTest(self):
345 widget = Widget('The widget')
346 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
347
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000348Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000349methods provided by the :class:`TestCase` base class. If the test fails, an
350exception will be raised, and :mod:`unittest` will identify the test case as a
351:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
352helps you identify where the problem is: :dfn:`failures` are caused by incorrect
353results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
354code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356The way to run a test case will be described later. For now, note that to
357construct an instance of such a test case, we call its constructor without
358arguments::
359
360 testCase = DefaultWidgetSizeTestCase()
361
362Now, such test cases can be numerous, and their set-up can be repetitive. In
363the above case, constructing a :class:`Widget` in each of 100 Widget test case
364subclasses would mean unsightly duplication.
365
366Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000367:meth:`~TestCase.setUp`, which the testing framework will automatically call for
368us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000369
370 import unittest
371
372 class SimpleWidgetTestCase(unittest.TestCase):
373 def setUp(self):
374 self.widget = Widget('The widget')
375
376 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
377 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000378 self.assertEqual(self.widget.size(), (50,50),
379 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000380
381 class WidgetResizeTestCase(SimpleWidgetTestCase):
382 def runTest(self):
383 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000384 self.assertEqual(self.widget.size(), (100,150),
385 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000386
Benjamin Peterson52baa292009-03-24 00:56:30 +0000387If the :meth:`~TestCase.setUp` method raises an exception while the test is
388running, the framework will consider the test to have suffered an error, and the
389:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Benjamin Peterson52baa292009-03-24 00:56:30 +0000391Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
392after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394 import unittest
395
396 class SimpleWidgetTestCase(unittest.TestCase):
397 def setUp(self):
398 self.widget = Widget('The widget')
399
400 def tearDown(self):
401 self.widget.dispose()
402 self.widget = None
403
Benjamin Peterson52baa292009-03-24 00:56:30 +0000404If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
405be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407Such a working environment for the testing code is called a :dfn:`fixture`.
408
409Often, many small test cases will use the same fixture. In this case, we would
410end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
411classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000412discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
413mechanism::
414
415 import unittest
416
417 class WidgetTestCase(unittest.TestCase):
418 def setUp(self):
419 self.widget = Widget('The widget')
420
421 def tearDown(self):
422 self.widget.dispose()
423 self.widget = None
424
Ezio Melottid59e44a2010-02-28 03:46:13 +0000425 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000426 self.assertEqual(self.widget.size(), (50,50),
427 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000428
Ezio Melottid59e44a2010-02-28 03:46:13 +0000429 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000430 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000431 self.assertEqual(self.widget.size(), (100,150),
432 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000433
Benjamin Peterson52baa292009-03-24 00:56:30 +0000434Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
435provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000436the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000437separately for each instance. When creating an instance we must specify the
438test method it is to run. We do this by passing the method name in the
439constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000440
Ezio Melottid59e44a2010-02-28 03:46:13 +0000441 defaultSizeTestCase = WidgetTestCase('test_default_size')
442 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000443
444Test case instances are grouped together according to the features they test.
445:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
446represented by :mod:`unittest`'s :class:`TestSuite` class::
447
448 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000449 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
450 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000451
452For the ease of running tests, as we will see later, it is a good idea to
453provide in each test module a callable object that returns a pre-built test
454suite::
455
456 def suite():
457 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000458 suite.addTest(WidgetTestCase('test_default_size'))
459 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000460 return suite
461
462or even::
463
464 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000465 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000466
467 return unittest.TestSuite(map(WidgetTestCase, tests))
468
469Since it is a common pattern to create a :class:`TestCase` subclass with many
470similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
471class that can be used to automate the process of creating a test suite and
472populating it with individual tests. For example, ::
473
474 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
475
Ezio Melottid59e44a2010-02-28 03:46:13 +0000476will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
477``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000478name prefix to identify test methods automatically.
479
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000480Note that the order in which the various test cases will be run is
481determined by sorting the test function names with respect to the
482built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484Often it is desirable to group suites of test cases together, so as to run tests
485for the whole system at once. This is easy, since :class:`TestSuite` instances
486can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
487added to a :class:`TestSuite`::
488
489 suite1 = module1.TheTestSuite()
490 suite2 = module2.TheTestSuite()
491 alltests = unittest.TestSuite([suite1, suite2])
492
493You can place the definitions of test cases and test suites in the same modules
494as the code they are to test (such as :file:`widget.py`), but there are several
495advantages to placing the test code in a separate module, such as
496:file:`test_widget.py`:
497
498* The test module can be run standalone from the command line.
499
500* The test code can more easily be separated from shipped code.
501
502* There is less temptation to change test code to fit the code it tests without
503 a good reason.
504
505* Test code should be modified much less frequently than the code it tests.
506
507* Tested code can be refactored more easily.
508
509* Tests for modules written in C must be in separate modules anyway, so why not
510 be consistent?
511
512* If the testing strategy changes, there is no need to change the source code.
513
514
515.. _legacy-unit-tests:
516
517Re-using old test code
518----------------------
519
520Some users will find that they have existing test code that they would like to
521run from :mod:`unittest`, without converting every old test function to a
522:class:`TestCase` subclass.
523
524For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
525This subclass of :class:`TestCase` can be used to wrap an existing test
526function. Set-up and tear-down functions can also be provided.
527
528Given the following test function::
529
530 def testSomething():
531 something = makeSomething()
532 assert something.name is not None
533 # ...
534
535one can create an equivalent test case instance as follows::
536
537 testcase = unittest.FunctionTestCase(testSomething)
538
539If there are additional set-up and tear-down methods that should be called as
540part of the test case's operation, they can also be provided like so::
541
542 testcase = unittest.FunctionTestCase(testSomething,
543 setUp=makeSomethingDB,
544 tearDown=deleteSomethingDB)
545
546To make migrating existing test suites easier, :mod:`unittest` supports tests
547raising :exc:`AssertionError` to indicate test failure. However, it is
548recommended that you use the explicit :meth:`TestCase.fail\*` and
549:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
550may treat :exc:`AssertionError` differently.
551
552.. note::
553
Benjamin Petersond2397752009-06-27 23:45:02 +0000554 Even though :class:`FunctionTestCase` can be used to quickly convert an
555 existing test base over to a :mod:`unittest`\ -based system, this approach is
556 not recommended. Taking the time to set up proper :class:`TestCase`
557 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000558
Benjamin Peterson52baa292009-03-24 00:56:30 +0000559In some cases, the existing tests may have been written using the :mod:`doctest`
560module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
561automatically build :class:`unittest.TestSuite` instances from the existing
562:mod:`doctest`\ -based tests.
563
Georg Brandl116aa622007-08-15 14:28:22 +0000564
Benjamin Peterson5254c042009-03-23 22:25:03 +0000565.. _unittest-skipping:
566
567Skipping tests and expected failures
568------------------------------------
569
Michael Foordf5c851a2010-02-05 21:48:03 +0000570.. versionadded:: 3.1
571
Benjamin Peterson5254c042009-03-23 22:25:03 +0000572Unittest supports skipping individual test methods and even whole classes of
573tests. In addition, it supports marking a test as a "expected failure," a test
574that is broken and will fail, but shouldn't be counted as a failure on a
575:class:`TestResult`.
576
577Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
578or one of its conditional variants.
579
580Basic skipping looks like this: ::
581
582 class MyTestCase(unittest.TestCase):
583
584 @unittest.skip("demonstrating skipping")
585 def test_nothing(self):
586 self.fail("shouldn't happen")
587
Benjamin Petersond2397752009-06-27 23:45:02 +0000588 @unittest.skipIf(mylib.__version__ < (1, 3),
589 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000590 def test_format(self):
591 # Tests that work for only a certain version of the library.
592 pass
593
594 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
595 def test_windows_support(self):
596 # windows specific testing code
597 pass
598
Benjamin Peterson5254c042009-03-23 22:25:03 +0000599This is the output of running the example above in verbose mode: ::
600
Benjamin Petersonded31c42009-03-30 15:04:16 +0000601 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000602 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000603 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000604
605 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000606 Ran 3 tests in 0.005s
607
608 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000609
610Classes can be skipped just like methods: ::
611
612 @skip("showing class skipping")
613 class MySkippedTestCase(unittest.TestCase):
614 def test_not_run(self):
615 pass
616
Benjamin Peterson52baa292009-03-24 00:56:30 +0000617:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
618that needs to be set up is not available.
619
Benjamin Peterson5254c042009-03-23 22:25:03 +0000620Expected failures use the :func:`expectedFailure` decorator. ::
621
622 class ExpectedFailureTestCase(unittest.TestCase):
623 @unittest.expectedFailure
624 def test_fail(self):
625 self.assertEqual(1, 0, "broken")
626
627It's easy to roll your own skipping decorators by making a decorator that calls
628:func:`skip` on the test when it wants it to be skipped. This decorator skips
629the test unless the passed object has a certain attribute: ::
630
631 def skipUnlessHasattr(obj, attr):
632 if hasattr(obj, attr):
633 return lambda func: func
634 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
635
636The following decorators implement test skipping and expected failures:
637
Georg Brandl8a1caa22010-07-29 16:01:11 +0000638.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000639
640 Unconditionally skip the decorated test. *reason* should describe why the
641 test is being skipped.
642
Georg Brandl8a1caa22010-07-29 16:01:11 +0000643.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000644
645 Skip the decorated test if *condition* is true.
646
Georg Brandl8a1caa22010-07-29 16:01:11 +0000647.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000648
Georg Brandl6faee4e2010-09-21 14:48:28 +0000649 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000650
Georg Brandl8a1caa22010-07-29 16:01:11 +0000651.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000652
653 Mark the test as an expected failure. If the test fails when run, the test
654 is not counted as a failure.
655
Benjamin Petersonb48af542010-04-11 20:43:16 +0000656Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
657Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
658
Benjamin Peterson5254c042009-03-23 22:25:03 +0000659
Georg Brandl116aa622007-08-15 14:28:22 +0000660.. _unittest-contents:
661
662Classes and functions
663---------------------
664
Benjamin Peterson52baa292009-03-24 00:56:30 +0000665This section describes in depth the API of :mod:`unittest`.
666
667
668.. _testcase-objects:
669
670Test cases
671~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000672
Georg Brandl7f01a132009-09-16 15:58:14 +0000673.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000674
675 Instances of the :class:`TestCase` class represent the smallest testable units
676 in the :mod:`unittest` universe. This class is intended to be used as a base
677 class, with specific tests being implemented by concrete subclasses. This class
678 implements the interface needed by the test runner to allow it to drive the
679 test, and methods that the test code can use to check for and report various
680 kinds of failure.
681
682 Each instance of :class:`TestCase` will run a single test method: the method
683 named *methodName*. If you remember, we had an earlier example that went
684 something like this::
685
686 def suite():
687 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000688 suite.addTest(WidgetTestCase('test_default_size'))
689 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000690 return suite
691
692 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
693 single test.
694
Benjamin Peterson52baa292009-03-24 00:56:30 +0000695 *methodName* defaults to :meth:`runTest`.
696
697 :class:`TestCase` instances provide three groups of methods: one group used
698 to run the test, another used by the test implementation to check conditions
699 and report failures, and some inquiry methods allowing information about the
700 test itself to be gathered.
701
702 Methods in the first group (running the test) are:
703
704
705 .. method:: setUp()
706
707 Method called to prepare the test fixture. This is called immediately
708 before calling the test method; any exception raised by this method will
709 be considered an error rather than a test failure. The default
710 implementation does nothing.
711
712
713 .. method:: tearDown()
714
715 Method called immediately after the test method has been called and the
716 result recorded. This is called even if the test method raised an
717 exception, so the implementation in subclasses may need to be particularly
718 careful about checking internal state. Any exception raised by this
719 method will be considered an error rather than a test failure. This
720 method will only be called if the :meth:`setUp` succeeds, regardless of
721 the outcome of the test method. The default implementation does nothing.
722
723
Benjamin Petersonb48af542010-04-11 20:43:16 +0000724 .. method:: setUpClass()
725
726 A class method called before tests in an individual class run.
727 ``setUpClass`` is called with the class as the only argument
728 and must be decorated as a :func:`classmethod`::
729
730 @classmethod
731 def setUpClass(cls):
732 ...
733
734 See `Class and Module Fixtures`_ for more details.
735
736 .. versionadded:: 3.2
737
738
739 .. method:: tearDownClass()
740
741 A class method called after tests in an individual class have run.
742 ``tearDownClass`` is called with the class as the only argument
743 and must be decorated as a :meth:`classmethod`::
744
745 @classmethod
746 def tearDownClass(cls):
747 ...
748
749 See `Class and Module Fixtures`_ for more details.
750
751 .. versionadded:: 3.2
752
753
Georg Brandl7f01a132009-09-16 15:58:14 +0000754 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000755
756 Run the test, collecting the result into the test result object passed as
757 *result*. If *result* is omitted or :const:`None`, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000758 object is created (by calling the :meth:`defaultTestResult` method) and
759 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000760
761 The same effect may be had by simply calling the :class:`TestCase`
762 instance.
763
764
Benjamin Petersone549ead2009-03-28 21:42:05 +0000765 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000766
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000767 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000768 test. See :ref:`unittest-skipping` for more information.
769
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000770 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000771
Benjamin Peterson52baa292009-03-24 00:56:30 +0000772
773 .. method:: debug()
774
775 Run the test without collecting the result. This allows exceptions raised
776 by the test to be propagated to the caller, and can be used to support
777 running tests under a debugger.
778
Benjamin Peterson52baa292009-03-24 00:56:30 +0000779
780
Ezio Melotti4370b302010-11-03 20:39:14 +0000781 The :class:`TestCase` class provides a number of methods to check for and
782 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000783
Ezio Melotti4370b302010-11-03 20:39:14 +0000784 +-----------------------------------------+-----------------------------+---------------+
785 | Method | Checks that | New in |
786 +=========================================+=============================+===============+
787 | :meth:`assertEqual(a, b) | ``a == b`` | |
788 | <TestCase.assertEqual>` | | |
789 +-----------------------------------------+-----------------------------+---------------+
790 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
791 | <TestCase.assertNotEqual>` | | |
792 +-----------------------------------------+-----------------------------+---------------+
793 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
794 | <TestCase.assertTrue>` | | |
795 +-----------------------------------------+-----------------------------+---------------+
796 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
797 | <TestCase.assertFalse>` | | |
798 +-----------------------------------------+-----------------------------+---------------+
799 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
800 | <TestCase.assertIs>` | | |
801 +-----------------------------------------+-----------------------------+---------------+
802 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
803 | <TestCase.assertIsNot>` | | |
804 +-----------------------------------------+-----------------------------+---------------+
805 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
806 | <TestCase.assertIsNone>` | | |
807 +-----------------------------------------+-----------------------------+---------------+
808 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
809 | <TestCase.assertIsNotNone>` | | |
810 +-----------------------------------------+-----------------------------+---------------+
811 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
812 | <TestCase.assertIn>` | | |
813 +-----------------------------------------+-----------------------------+---------------+
814 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
815 | <TestCase.assertNotIn>` | | |
816 +-----------------------------------------+-----------------------------+---------------+
817 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
818 | <TestCase.assertIsInstance>` | | |
819 +-----------------------------------------+-----------------------------+---------------+
820 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
821 | <TestCase.assertNotIsInstance>` | | |
822 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000823
Benjamin Peterson52baa292009-03-24 00:56:30 +0000824
Georg Brandl7f01a132009-09-16 15:58:14 +0000825 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000826
827 Test that *first* and *second* are equal. If the values do not compare
Ezio Melotti4841fd62010-11-05 15:43:40 +0000828 equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000829
830 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000831 list, tuple, dict, set, frozenset or str or any type that a subclass
832 registers with :meth:`addTypeEqualityFunc` the type specific equality
833 function will be called in order to generate a more useful default
834 error message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000835
Ezio Melotti4841fd62010-11-05 15:43:40 +0000836 If specified, *msg* will be used as the error message on failure.
837
Raymond Hettinger35a88362009-04-09 00:08:24 +0000838 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000839 Added the automatic calling of type specific equality function.
840
Michael Foord28a817e2010-02-09 00:03:57 +0000841 .. versionchanged:: 3.2
842 :meth:`assertMultiLineEqual` added as the default type equality
843 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000844
Benjamin Peterson52baa292009-03-24 00:56:30 +0000845
Georg Brandl7f01a132009-09-16 15:58:14 +0000846 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000847
848 Test that *first* and *second* are not equal. If the values do compare
Ezio Melotti4841fd62010-11-05 15:43:40 +0000849 equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000850
Ezio Melotti4370b302010-11-03 20:39:14 +0000851 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000852 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000853
Ezio Melotti4841fd62010-11-05 15:43:40 +0000854 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000855
Ezio Melotti4841fd62010-11-05 15:43:40 +0000856 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
857 is True`` (use ``assertIs(expr, True)`` for the latter). This method
858 should also be avoided when more specific methods are available (e.g.
859 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
860 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000861
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000862
Ezio Melotti9794a262010-11-04 14:52:13 +0000863 .. method:: assertIs(first, second, msg=None)
864 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000865
Ezio Melotti9794a262010-11-04 14:52:13 +0000866 Test that *first* and *second* evaluate (or don't evaluate) to the same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000867
Raymond Hettinger35a88362009-04-09 00:08:24 +0000868 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000869
870
Ezio Melotti4370b302010-11-03 20:39:14 +0000871 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000872 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000873
Ezio Melotti9794a262010-11-04 14:52:13 +0000874 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000875
Ezio Melotti4370b302010-11-03 20:39:14 +0000876 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000877
878
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000879 .. method:: assertIn(first, second, msg=None)
880 assertNotIn(first, second, msg=None)
881
Ezio Melotti4841fd62010-11-05 15:43:40 +0000882 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000883
Raymond Hettinger35a88362009-04-09 00:08:24 +0000884 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000885
886
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000887 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000888 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000889
Ezio Melotti9794a262010-11-04 14:52:13 +0000890 Test that *obj* is (or is not) an instance of *cls* (which can be a
891 class or a tuple of classes, as supported by :func:`isinstance`).
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000892
Ezio Melotti4370b302010-11-03 20:39:14 +0000893 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000894
895
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000896
Ezio Melotti4370b302010-11-03 20:39:14 +0000897 It is also possible to check that exceptions and warnings are raised using
898 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000899
Ezio Melotti4370b302010-11-03 20:39:14 +0000900 +---------------------------------------------------------+--------------------------------------+------------+
901 | Method | Checks that | New in |
902 +=========================================================+======================================+============+
903 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | |
904 | <TestCase.assertRaises>` | | |
905 +---------------------------------------------------------+--------------------------------------+------------+
906 | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
907 | <TestCase.assertRaisesRegexp>` | and the message matches `re` | |
908 +---------------------------------------------------------+--------------------------------------+------------+
909 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
910 | <TestCase.assertWarns>` | | |
911 +---------------------------------------------------------+--------------------------------------+------------+
912 | :meth:`assertWarnsRegexp(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
913 | <TestCase.assertWarnsRegexp>` | and the message matches `re` | |
914 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000915
Georg Brandl7f01a132009-09-16 15:58:14 +0000916 .. method:: assertRaises(exception, callable, *args, **kwds)
Georg Brandl7f01a132009-09-16 15:58:14 +0000917 assertRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000918
919 Test that an exception is raised when *callable* is called with any
920 positional or keyword arguments that are also passed to
921 :meth:`assertRaises`. The test passes if *exception* is raised, is an
922 error if another exception is raised, or fails if no exception is raised.
923 To catch any of a group of exceptions, a tuple containing the exception
924 classes may be passed as *exception*.
925
Georg Brandl7f01a132009-09-16 15:58:14 +0000926 If only the *exception* argument is given, returns a context manager so
927 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000928
Michael Foord41531f22010-02-05 21:13:40 +0000929 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000930 do_something()
931
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000932 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000933 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000934 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000935
Georg Brandl8a1caa22010-07-29 16:01:11 +0000936 with self.assertRaises(SomeException) as cm:
937 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000938
Georg Brandl8a1caa22010-07-29 16:01:11 +0000939 the_exception = cm.exception
940 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000941
Ezio Melotti49008232010-02-08 21:57:48 +0000942 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000943 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000944
Ezio Melotti49008232010-02-08 21:57:48 +0000945 .. versionchanged:: 3.2
946 Added the :attr:`exception` attribute.
947
Benjamin Peterson52baa292009-03-24 00:56:30 +0000948
Ezio Melotti327433f2010-11-03 20:51:17 +0000949 .. method:: assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
950 assertRaisesRegexp(exception, regexp)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000951
952 Like :meth:`assertRaises` but also tests that *regexp* matches
953 on the string representation of the raised exception. *regexp* may be
954 a regular expression object or a string containing a regular expression
955 suitable for use by :func:`re.search`. Examples::
956
957 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
958 int, 'XYZ')
959
960 or::
961
962 with self.assertRaisesRegexp(ValueError, 'literal'):
963 int('XYZ')
964
Raymond Hettinger35a88362009-04-09 00:08:24 +0000965 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000966
967
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000968 .. method:: assertWarns(warning, callable, *args, **kwds)
969 assertWarns(warning)
970
971 Test that a warning is triggered when *callable* is called with any
972 positional or keyword arguments that are also passed to
973 :meth:`assertWarns`. The test passes if *warning* is triggered and
974 fails if it isn't. Also, any unexpected exception is an error.
975 To catch any of a group of warnings, a tuple containing the warning
976 classes may be passed as *warnings*.
977
978 If only the *warning* argument is given, returns a context manager so
979 that the code under test can be written inline rather than as a function::
980
981 with self.assertWarns(SomeWarning):
982 do_something()
983
984 The context manager will store the caught warning object in its
985 :attr:`warning` attribute, and the source line which triggered the
986 warnings in the :attr:`filename` and :attr:`lineno` attributes.
987 This can be useful if the intention is to perform additional checks
988 on the exception raised::
989
990 with self.assertWarns(SomeWarning) as cm:
991 do_something()
992
993 self.assertIn('myfile.py', cm.filename)
994 self.assertEqual(320, cm.lineno)
995
996 This method works regardless of the warning filters in place when it
997 is called.
998
999 .. versionadded:: 3.2
1000
1001
Ezio Melotti327433f2010-11-03 20:51:17 +00001002 .. method:: assertWarnsRegexp(warning, regexp, callable, *args, **kwds)
1003 assertWarnsRegexp(warning, regexp)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001004
1005 Like :meth:`assertWarns` but also tests that *regexp* matches on the
1006 message of the triggered warning. *regexp* may be a regular expression
1007 object or a string containing a regular expression suitable for use
1008 by :func:`re.search`. Example::
1009
1010 self.assertWarnsRegexp(DeprecationWarning,
1011 r'legacy_function\(\) is deprecated',
1012 legacy_function, 'XYZ')
1013
1014 or::
1015
1016 with self.assertWarnsRegexp(RuntimeWarning, 'unsafe frobnicating'):
1017 frobnicate('/etc/passwd')
1018
1019 .. versionadded:: 3.2
1020
1021
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001022
Ezio Melotti4370b302010-11-03 20:39:14 +00001023 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001024
Ezio Melotti4370b302010-11-03 20:39:14 +00001025 +---------------------------------------+--------------------------------+--------------+
1026 | Method | Checks that | New in |
1027 +=======================================+================================+==============+
1028 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1029 | <TestCase.assertAlmostEqual>` | | |
1030 +---------------------------------------+--------------------------------+--------------+
1031 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1032 | <TestCase.assertNotAlmostEqual>` | | |
1033 +---------------------------------------+--------------------------------+--------------+
1034 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1035 | <TestCase.assertGreater>` | | |
1036 +---------------------------------------+--------------------------------+--------------+
1037 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1038 | <TestCase.assertGreaterEqual>` | | |
1039 +---------------------------------------+--------------------------------+--------------+
1040 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1041 | <TestCase.assertLess>` | | |
1042 +---------------------------------------+--------------------------------+--------------+
1043 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1044 | <TestCase.assertLessEqual>` | | |
1045 +---------------------------------------+--------------------------------+--------------+
1046 | :meth:`assertRegexpMatches(s, re) | ``regex.search(s)`` | 3.1 |
1047 | <TestCase.assertRegexpMatches>` | | |
1048 +---------------------------------------+--------------------------------+--------------+
1049 | :meth:`assertNotRegexpMatches(s, re) | ``not regex.search(s)`` | 3.2 |
1050 | <TestCase.assertNotRegexpMatches>` | | |
1051 +---------------------------------------+--------------------------------+--------------+
1052 | :meth:`assertDictContainsSubset(a, b) | all the key/value pairs | 3.1 |
1053 | <TestCase.assertDictContainsSubset>` | in `a` exist in `b` | |
1054 +---------------------------------------+--------------------------------+--------------+
1055 | :meth:`assertItemsEqual(a, b) | `a` and `b` have the same | 3.2 |
1056 | <TestCase.assertItemsEqual>` | elements in the same number, | |
1057 | | regardless of their order | |
1058 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001059
1060
Ezio Melotti4370b302010-11-03 20:39:14 +00001061 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001062 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001063
Ezio Melotti4841fd62010-11-05 15:43:40 +00001064 Test that *first* and *second* are approximately (or not approximately)
1065 equal by computing the difference, rounding to the given number of
1066 decimal *places* (default 7), and comparing to zero. Note that these
1067 methods round the values to the given number of *decimal places* (i.e.
1068 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001069
Ezio Melotti4370b302010-11-03 20:39:14 +00001070 If *delta* is supplied instead of *places* then the difference
Ezio Melotti4841fd62010-11-05 15:43:40 +00001071 between *first* and *second* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001072
Ezio Melotti4370b302010-11-03 20:39:14 +00001073 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001074
Ezio Melotti4370b302010-11-03 20:39:14 +00001075 .. versionchanged:: 3.2
Ezio Melotti4841fd62010-11-05 15:43:40 +00001076 assertAlmostEqual automatically considers almost equal objects that compare equal.
1077 assertNotAlmostEqual automatically fails if the objects compare equal.
Ezio Melotti4370b302010-11-03 20:39:14 +00001078 Added the ``delta`` keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001079
Ezio Melotti4370b302010-11-03 20:39:14 +00001080
Ezio Melotti4370b302010-11-03 20:39:14 +00001081 .. method:: assertGreater(first, second, msg=None)
1082 assertGreaterEqual(first, second, msg=None)
1083 assertLess(first, second, msg=None)
1084 assertLessEqual(first, second, msg=None)
1085
1086 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001087 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001088
1089 >>> self.assertGreaterEqual(3, 4)
1090 AssertionError: "3" unexpectedly not greater than or equal to "4"
1091
1092 .. versionadded:: 3.1
1093
1094
1095 .. method:: assertRegexpMatches(text, regexp, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001096 assertNotRegexpMatches(text, regexp, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001097
Ezio Melotti4841fd62010-11-05 15:43:40 +00001098 Test that a *regexp* search matches (or does not match) *text*. In case
1099 of failure, the error message will include the pattern and the *text* (or
1100 the pattern and the part of *text* that unexpectedly matched). *regexp*
Ezio Melotti4370b302010-11-03 20:39:14 +00001101 may be a regular expression object or a string containing a regular
1102 expression suitable for use by :func:`re.search`.
1103
Ezio Melotti4841fd62010-11-05 15:43:40 +00001104 .. versionadded:: 3.1 :meth:`~TestCase.assertRegexpMatches`
1105 .. versionadded:: 3.2 :meth:`~TestCase.assertNotRegexpMatches`
Ezio Melotti4370b302010-11-03 20:39:14 +00001106
1107
1108 .. method:: assertDictContainsSubset(expected, actual, msg=None)
1109
1110 Tests whether the key/value pairs in dictionary *actual* are a
1111 superset of those in *expected*. If not, an error message listing
1112 the missing keys and mismatched values is generated.
1113
Ezio Melotti4370b302010-11-03 20:39:14 +00001114 .. versionadded:: 3.1
1115
1116
1117 .. method:: assertItemsEqual(actual, expected, msg=None)
1118
1119 Test that sequence *expected* contains the same elements as *actual*,
1120 regardless of their order. When they don't, an error message listing the
1121 differences between the sequences will be generated.
1122
1123 Duplicate elements are *not* ignored when comparing *actual* and
1124 *expected*. It verifies if each element has the same count in both
1125 sequences. It is the equivalent of ``assertEqual(sorted(expected),
1126 sorted(actual))`` but it works with sequences of unhashable objects as
1127 well.
1128
Ezio Melotti4370b302010-11-03 20:39:14 +00001129 .. versionadded:: 3.2
1130
1131
1132 .. method:: assertSameElements(actual, expected, msg=None)
1133
1134 Test that sequence *expected* contains the same elements as *actual*,
1135 regardless of their order. When they don't, an error message listing
1136 the differences between the sequences will be generated.
1137
1138 Duplicate elements are ignored when comparing *actual* and *expected*.
1139 It is the equivalent of ``assertEqual(set(expected), set(actual))``
1140 but it works with sequences of unhashable objects as well. Because
1141 duplicates are ignored, this method has been deprecated in favour of
1142 :meth:`assertItemsEqual`.
1143
Ezio Melotti4370b302010-11-03 20:39:14 +00001144 .. versionadded:: 3.1
1145 .. deprecated:: 3.2
1146
1147
1148
1149 The following methods are used automatically by :meth:`~TestCase.assertEqual`
1150 and usually is not necessary to invoke them directly:
1151
1152 +-----------------------------------------+-----------------------------+--------------+
1153 | Method | Used to compare | New in |
1154 +=========================================+=============================+==============+
1155 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1156 | <TestCase.assertMultiLineEqual>` | | |
1157 +-----------------------------------------+-----------------------------+--------------+
1158 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1159 | <TestCase.assertSequenceEqual>` | | |
1160 +-----------------------------------------+-----------------------------+--------------+
1161 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1162 | <TestCase.assertListEqual>` | | |
1163 +-----------------------------------------+-----------------------------+--------------+
1164 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1165 | <TestCase.assertTupleEqual>` | | |
1166 +-----------------------------------------+-----------------------------+--------------+
1167 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1168 | <TestCase.assertSetEqual>` | | |
1169 +-----------------------------------------+-----------------------------+--------------+
1170 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1171 | <TestCase.assertDictEqual>` | | |
1172 +-----------------------------------------+-----------------------------+--------------+
1173
1174
1175
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001176 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001177
1178 Test that the multiline string *first* is equal to the string *second*.
1179 When not equal a diff of the two strings highlighting the differences
1180 will be included in the error message. This method is used by default
1181 when comparing strings with :meth:`assertEqual`.
1182
Ezio Melotti4370b302010-11-03 20:39:14 +00001183 .. versionadded:: 3.1
1184
1185
1186 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
1187
1188 Tests that two sequences are equal. If a *seq_type* is supplied, both
1189 *seq1* and *seq2* must be instances of *seq_type* or a failure will
1190 be raised. If the sequences are different an error message is
1191 constructed that shows the difference between the two.
1192
Ezio Melotti4370b302010-11-03 20:39:14 +00001193 This method is used to implement :meth:`assertListEqual` and
1194 :meth:`assertTupleEqual`.
1195
1196 .. versionadded:: 3.1
1197
1198
1199 .. method:: assertListEqual(list1, list2, msg=None)
1200 assertTupleEqual(tuple1, tuple2, msg=None)
1201
1202 Tests that two lists or tuples are equal. If not an error message is
1203 constructed that shows only the differences between the two. An error
1204 is also raised if either of the parameters are of the wrong type.
1205 These methods are used by default when comparing lists or tuples with
1206 :meth:`assertEqual`.
1207
Ezio Melotti4370b302010-11-03 20:39:14 +00001208 .. versionadded:: 3.1
1209
1210
1211 .. method:: assertSetEqual(set1, set2, msg=None)
1212
1213 Tests that two sets are equal. If not, an error message is constructed
1214 that lists the differences between the sets. This method is used by
1215 default when comparing sets or frozensets with :meth:`assertEqual`.
1216
1217 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
1218 method.
1219
Ezio Melotti4370b302010-11-03 20:39:14 +00001220 .. versionadded:: 3.1
1221
1222
1223 .. method:: assertDictEqual(expected, actual, msg=None)
1224
1225 Test that two dictionaries are equal. If not, an error message is
1226 constructed that shows the differences in the dictionaries. This
1227 method will be used by default to compare dictionaries in
1228 calls to :meth:`assertEqual`.
1229
Ezio Melotti4370b302010-11-03 20:39:14 +00001230 .. versionadded:: 3.1
1231
1232
1233
1234 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001235
Benjamin Peterson52baa292009-03-24 00:56:30 +00001236
Georg Brandl7f01a132009-09-16 15:58:14 +00001237 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001238
1239 Signals a test failure unconditionally, with *msg* or :const:`None` for
1240 the error message.
1241
1242
1243 .. attribute:: failureException
1244
1245 This class attribute gives the exception raised by the test method. If a
1246 test framework needs to use a specialized exception, possibly to carry
1247 additional information, it must subclass this exception in order to "play
1248 fair" with the framework. The initial value of this attribute is
1249 :exc:`AssertionError`.
1250
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001251
1252 .. attribute:: longMessage
1253
1254 If set to True then any explicit failure message you pass in to the
1255 assert methods will be appended to the end of the normal failure message.
1256 The normal messages contain useful information about the objects involved,
1257 for example the message from assertEqual shows you the repr of the two
1258 unequal objects. Setting this attribute to True allows you to have a
1259 custom error message in addition to the normal one.
1260
1261 This attribute defaults to False, meaning that a custom message passed
1262 to an assert method will silence the normal message.
1263
1264 The class setting can be overridden in individual tests by assigning an
1265 instance attribute to True or False before calling the assert methods.
1266
Raymond Hettinger35a88362009-04-09 00:08:24 +00001267 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001268
1269
Michael Foord98b3e762010-06-05 21:59:55 +00001270 .. attribute:: maxDiff
1271
1272 This attribute controls the maximum length of diffs output by assert
1273 methods that report diffs on failure. It defaults to 80*8 characters.
1274 Assert methods affected by this attribute are
1275 :meth:`assertSequenceEqual` (including all the sequence comparison
1276 methods that delegate to it), :meth:`assertDictEqual` and
1277 :meth:`assertMultiLineEqual`.
1278
1279 Setting ``maxDiff`` to None means that there is no maximum length of
1280 diffs.
1281
1282 .. versionadded:: 3.2
1283
1284
Benjamin Peterson52baa292009-03-24 00:56:30 +00001285 Testing frameworks can use the following methods to collect information on
1286 the test:
1287
1288
1289 .. method:: countTestCases()
1290
1291 Return the number of tests represented by this test object. For
1292 :class:`TestCase` instances, this will always be ``1``.
1293
1294
1295 .. method:: defaultTestResult()
1296
1297 Return an instance of the test result class that should be used for this
1298 test case class (if no other result instance is provided to the
1299 :meth:`run` method).
1300
1301 For :class:`TestCase` instances, this will always be an instance of
1302 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1303 as necessary.
1304
1305
1306 .. method:: id()
1307
1308 Return a string identifying the specific test case. This is usually the
1309 full name of the test method, including the module and class name.
1310
1311
1312 .. method:: shortDescription()
1313
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001314 Returns a description of the test, or :const:`None` if no description
1315 has been provided. The default implementation of this method
1316 returns the first line of the test method's docstring, if available,
Michael Foord34c94622010-02-10 15:51:42 +00001317 or :const:`None`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001318
Michael Foord34c94622010-02-10 15:51:42 +00001319 .. versionchanged:: 3.1,3.2
1320 In 3.1 this was changed to add the test name to the short description
1321 even in the presence of a docstring. This caused compatibility issues
1322 with unittest extensions and adding the test name was moved to the
1323 :class:`TextTestResult`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001324
1325 .. method:: addTypeEqualityFunc(typeobj, function)
1326
1327 Registers a type specific :meth:`assertEqual` equality checking
1328 function to be called by :meth:`assertEqual` when both objects it has
1329 been asked to compare are exactly *typeobj* (not subclasses).
1330 *function* must take two positional arguments and a third msg=None
1331 keyword argument just as :meth:`assertEqual` does. It must raise
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001332 ``self.failureException`` when inequality between the first two
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001333 parameters is detected.
1334
1335 One good use of custom equality checking functions for a type
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001336 is to raise ``self.failureException`` with an error message useful
1337 for debugging the problem by explaining the inequalities in detail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001338
Raymond Hettinger35a88362009-04-09 00:08:24 +00001339 .. versionadded:: 3.1
Georg Brandl116aa622007-08-15 14:28:22 +00001340
1341
Georg Brandl7f01a132009-09-16 15:58:14 +00001342 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001343
1344 Add a function to be called after :meth:`tearDown` to cleanup resources
1345 used during the test. Functions will be called in reverse order to the
1346 order they are added (LIFO). They are called with any arguments and
1347 keyword arguments passed into :meth:`addCleanup` when they are
1348 added.
1349
1350 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1351 then any cleanup functions added will still be called.
1352
Georg Brandl853947a2010-01-31 18:53:23 +00001353 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001354
1355
1356 .. method:: doCleanups()
1357
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001358 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001359 after :meth:`setUp` if :meth:`setUp` raises an exception.
1360
1361 It is responsible for calling all the cleanup functions added by
1362 :meth:`addCleanup`. If you need cleanup functions to be called
1363 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1364 yourself.
1365
1366 :meth:`doCleanups` pops methods off the stack of cleanup
1367 functions one at a time, so it can be called at any time.
1368
Georg Brandl853947a2010-01-31 18:53:23 +00001369 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001370
1371
Georg Brandl7f01a132009-09-16 15:58:14 +00001372.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001373
1374 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001375 allows the test runner to drive the test, but does not provide the methods
1376 which test code can use to check and report errors. This is used to create
1377 test cases using legacy test code, allowing it to be integrated into a
1378 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001379
1380
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001381Deprecated aliases
1382##################
1383
1384For historical reasons, some of the :class:`TestCase` methods had one or more
1385aliases that are now deprecated. The following table lists the correct names
1386along with their deprecated aliases:
1387
1388 ============================== ===============================
1389 Method Name Deprecated alias(es)
1390 ============================== ===============================
1391 :meth:`.assertEqual` failUnlessEqual, assertEquals
1392 :meth:`.assertNotEqual` failIfEqual
1393 :meth:`.assertTrue` failUnless, assert\_
1394 :meth:`.assertFalse` failIf
1395 :meth:`.assertRaises` failUnlessRaises
1396 :meth:`.assertAlmostEqual` failUnlessAlmostEqual
1397 :meth:`.assertNotAlmostEqual` failIfAlmostEqual
1398 ============================== ===============================
1399
1400 .. deprecated:: 3.1
1401 the aliases listed in the second column
1402
1403
1404
Benjamin Peterson52baa292009-03-24 00:56:30 +00001405.. _testsuite-objects:
1406
Benjamin Peterson52baa292009-03-24 00:56:30 +00001407Grouping tests
1408~~~~~~~~~~~~~~
1409
Georg Brandl7f01a132009-09-16 15:58:14 +00001410.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001411
1412 This class represents an aggregation of individual tests cases and test suites.
1413 The class presents the interface needed by the test runner to allow it to be run
1414 as any other test case. Running a :class:`TestSuite` instance is the same as
1415 iterating over the suite, running each test individually.
1416
1417 If *tests* is given, it must be an iterable of individual test cases or other
1418 test suites that will be used to build the suite initially. Additional methods
1419 are provided to add test cases and suites to the collection later on.
1420
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001421 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1422 they do not actually implement a test. Instead, they are used to aggregate
1423 tests into groups of tests that should be run together. Some additional
1424 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001425
1426
1427 .. method:: TestSuite.addTest(test)
1428
1429 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1430
1431
1432 .. method:: TestSuite.addTests(tests)
1433
1434 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1435 instances to this test suite.
1436
Benjamin Petersond2397752009-06-27 23:45:02 +00001437 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1438 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001439
1440 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1441
1442
1443 .. method:: run(result)
1444
1445 Run the tests associated with this suite, collecting the result into the
1446 test result object passed as *result*. Note that unlike
1447 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1448 be passed in.
1449
1450
1451 .. method:: debug()
1452
1453 Run the tests associated with this suite without collecting the
1454 result. This allows exceptions raised by the test to be propagated to the
1455 caller and can be used to support running tests under a debugger.
1456
1457
1458 .. method:: countTestCases()
1459
1460 Return the number of tests represented by this test object, including all
1461 individual tests and sub-suites.
1462
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001463
1464 .. method:: __iter__()
1465
1466 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1467 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1468 that this method maybe called several times on a single suite
1469 (for example when counting tests or comparing for equality)
1470 so the tests returned must be the same for repeated iterations.
1471
Georg Brandl853947a2010-01-31 18:53:23 +00001472 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001473 In earlier versions the :class:`TestSuite` accessed tests directly rather
1474 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1475 for providing tests.
1476
Benjamin Peterson52baa292009-03-24 00:56:30 +00001477 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1478 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1479
1480
Benjamin Peterson52baa292009-03-24 00:56:30 +00001481Loading and running tests
1482~~~~~~~~~~~~~~~~~~~~~~~~~
1483
Georg Brandl116aa622007-08-15 14:28:22 +00001484.. class:: TestLoader()
1485
Benjamin Peterson52baa292009-03-24 00:56:30 +00001486 The :class:`TestLoader` class is used to create test suites from classes and
1487 modules. Normally, there is no need to create an instance of this class; the
1488 :mod:`unittest` module provides an instance that can be shared as
1489 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1490 customization of some configurable properties.
1491
1492 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001493
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001494
Benjamin Peterson52baa292009-03-24 00:56:30 +00001495 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001496
Benjamin Peterson52baa292009-03-24 00:56:30 +00001497 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1498 :class:`testCaseClass`.
1499
1500
1501 .. method:: loadTestsFromModule(module)
1502
1503 Return a suite of all tests cases contained in the given module. This
1504 method searches *module* for classes derived from :class:`TestCase` and
1505 creates an instance of the class for each test method defined for the
1506 class.
1507
Georg Brandle720c0a2009-04-27 16:20:50 +00001508 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001509
1510 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1511 convenient in sharing fixtures and helper functions, defining test
1512 methods on base classes that are not intended to be instantiated
1513 directly does not play well with this method. Doing so, however, can
1514 be useful when the fixtures are different and defined in subclasses.
1515
Benjamin Petersond2397752009-06-27 23:45:02 +00001516 If a module provides a ``load_tests`` function it will be called to
1517 load the tests. This allows modules to customize test loading.
1518 This is the `load_tests protocol`_.
1519
Georg Brandl853947a2010-01-31 18:53:23 +00001520 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001521 Support for ``load_tests`` added.
1522
Benjamin Peterson52baa292009-03-24 00:56:30 +00001523
Georg Brandl7f01a132009-09-16 15:58:14 +00001524 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001525
1526 Return a suite of all tests cases given a string specifier.
1527
1528 The specifier *name* is a "dotted name" that may resolve either to a
1529 module, a test case class, a test method within a test case class, a
1530 :class:`TestSuite` instance, or a callable object which returns a
1531 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1532 applied in the order listed here; that is, a method on a possible test
1533 case class will be picked up as "a test method within a test case class",
1534 rather than "a callable object".
1535
1536 For example, if you have a module :mod:`SampleTests` containing a
1537 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1538 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001539 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1540 return a suite which will run all three test methods. Using the specifier
1541 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1542 suite which will run only the :meth:`test_two` test method. The specifier
1543 can refer to modules and packages which have not been imported; they will
1544 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001545
1546 The method optionally resolves *name* relative to the given *module*.
1547
1548
Georg Brandl7f01a132009-09-16 15:58:14 +00001549 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001550
1551 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1552 than a single name. The return value is a test suite which supports all
1553 the tests defined for each name.
1554
1555
1556 .. method:: getTestCaseNames(testCaseClass)
1557
1558 Return a sorted sequence of method names found within *testCaseClass*;
1559 this should be a subclass of :class:`TestCase`.
1560
Benjamin Petersond2397752009-06-27 23:45:02 +00001561
1562 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1563
1564 Find and return all test modules from the specified start directory,
1565 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001566 *pattern* will be loaded. (Using shell style pattern matching.) Only
1567 module names that are importable (i.e. are valid Python identifiers) will
1568 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001569
1570 All test modules must be importable from the top level of the project. If
1571 the start directory is not the top level directory then the top level
1572 directory must be specified separately.
1573
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001574 If importing a module fails, for example due to a syntax error, then this
1575 will be recorded as a single error and discovery will continue.
1576
Benjamin Petersond2397752009-06-27 23:45:02 +00001577 If a test package name (directory with :file:`__init__.py`) matches the
1578 pattern then the package will be checked for a ``load_tests``
1579 function. If this exists then it will be called with *loader*, *tests*,
1580 *pattern*.
1581
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001582 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001583 ``load_tests`` is responsible for loading all tests in the package.
1584
1585 The pattern is deliberately not stored as a loader attribute so that
1586 packages can continue discovery themselves. *top_level_dir* is stored so
1587 ``load_tests`` does not need to pass this argument in to
1588 ``loader.discover()``.
1589
Benjamin Petersonb48af542010-04-11 20:43:16 +00001590 *start_dir* can be a dotted module name as well as a directory.
1591
Georg Brandl853947a2010-01-31 18:53:23 +00001592 .. versionadded:: 3.2
1593
Benjamin Petersond2397752009-06-27 23:45:02 +00001594
Benjamin Peterson52baa292009-03-24 00:56:30 +00001595 The following attributes of a :class:`TestLoader` can be configured either by
1596 subclassing or assignment on an instance:
1597
1598
1599 .. attribute:: testMethodPrefix
1600
1601 String giving the prefix of method names which will be interpreted as test
1602 methods. The default value is ``'test'``.
1603
1604 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1605 methods.
1606
1607
1608 .. attribute:: sortTestMethodsUsing
1609
1610 Function to be used to compare method names when sorting them in
1611 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1612
1613
1614 .. attribute:: suiteClass
1615
1616 Callable object that constructs a test suite from a list of tests. No
1617 methods on the resulting object are needed. The default value is the
1618 :class:`TestSuite` class.
1619
1620 This affects all the :meth:`loadTestsFrom\*` methods.
1621
1622
Benjamin Peterson52baa292009-03-24 00:56:30 +00001623.. class:: TestResult
1624
1625 This class is used to compile information about which tests have succeeded
1626 and which have failed.
1627
1628 A :class:`TestResult` object stores the results of a set of tests. The
1629 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1630 properly recorded; test authors do not need to worry about recording the
1631 outcome of tests.
1632
1633 Testing frameworks built on top of :mod:`unittest` may want access to the
1634 :class:`TestResult` object generated by running a set of tests for reporting
1635 purposes; a :class:`TestResult` instance is returned by the
1636 :meth:`TestRunner.run` method for this purpose.
1637
1638 :class:`TestResult` instances have the following attributes that will be of
1639 interest when inspecting the results of running a set of tests:
1640
1641
1642 .. attribute:: errors
1643
1644 A list containing 2-tuples of :class:`TestCase` instances and strings
1645 holding formatted tracebacks. Each tuple represents a test which raised an
1646 unexpected exception.
1647
Benjamin Peterson52baa292009-03-24 00:56:30 +00001648 .. attribute:: failures
1649
1650 A list containing 2-tuples of :class:`TestCase` instances and strings
1651 holding formatted tracebacks. Each tuple represents a test where a failure
1652 was explicitly signalled using the :meth:`TestCase.fail\*` or
1653 :meth:`TestCase.assert\*` methods.
1654
Benjamin Peterson52baa292009-03-24 00:56:30 +00001655 .. attribute:: skipped
1656
1657 A list containing 2-tuples of :class:`TestCase` instances and strings
1658 holding the reason for skipping the test.
1659
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001660 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001661
1662 .. attribute:: expectedFailures
1663
Georg Brandl6faee4e2010-09-21 14:48:28 +00001664 A list containing 2-tuples of :class:`TestCase` instances and strings
1665 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001666 of the test case.
1667
1668 .. attribute:: unexpectedSuccesses
1669
1670 A list containing :class:`TestCase` instances that were marked as expected
1671 failures, but succeeded.
1672
1673 .. attribute:: shouldStop
1674
1675 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1676
1677
1678 .. attribute:: testsRun
1679
1680 The total number of tests run so far.
1681
1682
Benjamin Petersonb48af542010-04-11 20:43:16 +00001683 .. attribute:: buffer
1684
1685 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1686 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1687 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1688 fails or errors. Any output is also attached to the failure / error message.
1689
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001690 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001691
1692
1693 .. attribute:: failfast
1694
1695 If set to true :meth:`stop` will be called on the first failure or error,
1696 halting the test run.
1697
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001698 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001699
1700
Benjamin Peterson52baa292009-03-24 00:56:30 +00001701 .. method:: wasSuccessful()
1702
1703 Return :const:`True` if all tests run so far have passed, otherwise returns
1704 :const:`False`.
1705
1706
1707 .. method:: stop()
1708
1709 This method can be called to signal that the set of tests being run should
1710 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1711 :class:`TestRunner` objects should respect this flag and return without
1712 running any additional tests.
1713
1714 For example, this feature is used by the :class:`TextTestRunner` class to
1715 stop the test framework when the user signals an interrupt from the
1716 keyboard. Interactive tools which provide :class:`TestRunner`
1717 implementations can use this in a similar manner.
1718
1719 The following methods of the :class:`TestResult` class are used to maintain
1720 the internal data structures, and may be extended in subclasses to support
1721 additional reporting requirements. This is particularly useful in building
1722 tools which support interactive reporting while tests are being run.
1723
1724
1725 .. method:: startTest(test)
1726
1727 Called when the test case *test* is about to be run.
1728
Benjamin Peterson52baa292009-03-24 00:56:30 +00001729 .. method:: stopTest(test)
1730
1731 Called after the test case *test* has been executed, regardless of the
1732 outcome.
1733
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001734 .. method:: startTestRun(test)
1735
1736 Called once before any tests are executed.
1737
Georg Brandl853947a2010-01-31 18:53:23 +00001738 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001739
1740
1741 .. method:: stopTestRun(test)
1742
Ezio Melotti176d6c42010-01-27 20:58:07 +00001743 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001744
Georg Brandl853947a2010-01-31 18:53:23 +00001745 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001746
1747
Benjamin Peterson52baa292009-03-24 00:56:30 +00001748 .. method:: addError(test, err)
1749
1750 Called when the test case *test* raises an unexpected exception *err* is a
1751 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1752 traceback)``.
1753
1754 The default implementation appends a tuple ``(test, formatted_err)`` to
1755 the instance's :attr:`errors` attribute, where *formatted_err* is a
1756 formatted traceback derived from *err*.
1757
1758
1759 .. method:: addFailure(test, err)
1760
Benjamin Petersond2397752009-06-27 23:45:02 +00001761 Called when the test case *test* signals a failure. *err* is a tuple of
1762 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001763
1764 The default implementation appends a tuple ``(test, formatted_err)`` to
1765 the instance's :attr:`failures` attribute, where *formatted_err* is a
1766 formatted traceback derived from *err*.
1767
1768
1769 .. method:: addSuccess(test)
1770
1771 Called when the test case *test* succeeds.
1772
1773 The default implementation does nothing.
1774
1775
1776 .. method:: addSkip(test, reason)
1777
1778 Called when the test case *test* is skipped. *reason* is the reason the
1779 test gave for skipping.
1780
1781 The default implementation appends a tuple ``(test, reason)`` to the
1782 instance's :attr:`skipped` attribute.
1783
1784
1785 .. method:: addExpectedFailure(test, err)
1786
1787 Called when the test case *test* fails, but was marked with the
1788 :func:`expectedFailure` decorator.
1789
1790 The default implementation appends a tuple ``(test, formatted_err)`` to
1791 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1792 is a formatted traceback derived from *err*.
1793
1794
1795 .. method:: addUnexpectedSuccess(test)
1796
1797 Called when the test case *test* was marked with the
1798 :func:`expectedFailure` decorator, but succeeded.
1799
1800 The default implementation appends the test to the instance's
1801 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001802
Georg Brandl67b21b72010-08-17 15:07:14 +00001803
Michael Foord34c94622010-02-10 15:51:42 +00001804.. class:: TextTestResult(stream, descriptions, verbosity)
1805
Georg Brandl67b21b72010-08-17 15:07:14 +00001806 A concrete implementation of :class:`TestResult` used by the
1807 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001808
Georg Brandl67b21b72010-08-17 15:07:14 +00001809 .. versionadded:: 3.2
1810 This class was previously named ``_TextTestResult``. The old name still
1811 exists as an alias but is deprecated.
1812
Georg Brandl116aa622007-08-15 14:28:22 +00001813
1814.. data:: defaultTestLoader
1815
1816 Instance of the :class:`TestLoader` class intended to be shared. If no
1817 customization of the :class:`TestLoader` is needed, this instance can be used
1818 instead of repeatedly creating new instances.
1819
1820
Michael Foord34c94622010-02-10 15:51:42 +00001821.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001822
1823 A basic test runner implementation which prints results on standard error. It
1824 has a few configurable parameters, but is essentially very simple. Graphical
1825 applications which run test suites should provide alternate implementations.
1826
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001827 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001828
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001829 This method returns the instance of ``TestResult`` used by :meth:`run`.
1830 It is not intended to be called directly, but can be overridden in
1831 subclasses to provide a custom ``TestResult``.
1832
Michael Foord34c94622010-02-10 15:51:42 +00001833 ``_makeResult()`` instantiates the class or callable passed in the
1834 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001835 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001836 The result class is instantiated with the following arguments::
1837
1838 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001839
Benjamin Petersonb48af542010-04-11 20:43:16 +00001840.. 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 +00001841
1842 A command-line program that runs a set of tests; this is primarily for making
1843 test modules conveniently executable. The simplest use for this function is to
1844 include the following line at the end of a test script::
1845
1846 if __name__ == '__main__':
1847 unittest.main()
1848
Benjamin Petersond2397752009-06-27 23:45:02 +00001849 You can run tests with more detailed information by passing in the verbosity
1850 argument::
1851
1852 if __name__ == '__main__':
1853 unittest.main(verbosity=2)
1854
Georg Brandl116aa622007-08-15 14:28:22 +00001855 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001856 created instance of it. By default ``main`` calls :func:`sys.exit` with
1857 an exit code indicating success or failure of the tests run.
1858
1859 ``main`` supports being used from the interactive interpreter by passing in the
1860 argument ``exit=False``. This displays the result on standard output without
1861 calling :func:`sys.exit`::
1862
1863 >>> from unittest import main
1864 >>> main(module='test_module', exit=False)
1865
Benjamin Petersonb48af542010-04-11 20:43:16 +00001866 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
Éric Araujo713d3032010-11-18 16:38:46 +00001867 effect as the `failfast, catch and buffer command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001868
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001869 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1870 This stores the result of the tests run as the ``result`` attribute.
1871
Georg Brandl853947a2010-01-31 18:53:23 +00001872 .. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001873 The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
1874 parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001875
1876
1877load_tests Protocol
1878###################
1879
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001880
Georg Brandl853947a2010-01-31 18:53:23 +00001881.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001882
1883
Benjamin Petersond2397752009-06-27 23:45:02 +00001884Modules or packages can customize how tests are loaded from them during normal
1885test runs or test discovery by implementing a function called ``load_tests``.
1886
1887If a test module defines ``load_tests`` it will be called by
1888:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1889
1890 load_tests(loader, standard_tests, None)
1891
1892It should return a :class:`TestSuite`.
1893
1894*loader* is the instance of :class:`TestLoader` doing the loading.
1895*standard_tests* are the tests that would be loaded by default from the
1896module. It is common for test modules to only want to add or remove tests
1897from the standard set of tests.
1898The third argument is used when loading packages as part of test discovery.
1899
1900A typical ``load_tests`` function that loads tests from a specific set of
1901:class:`TestCase` classes may look like::
1902
1903 test_cases = (TestCase1, TestCase2, TestCase3)
1904
1905 def load_tests(loader, tests, pattern):
1906 suite = TestSuite()
1907 for test_class in test_cases:
1908 tests = loader.loadTestsFromTestCase(test_class)
1909 suite.addTests(tests)
1910 return suite
1911
1912If discovery is started, either from the command line or by calling
1913:meth:`TestLoader.discover`, with a pattern that matches a package
1914name then the package :file:`__init__.py` will be checked for ``load_tests``.
1915
1916.. note::
1917
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001918 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00001919 that start with 'test' but *won't* match any test directories.
1920
1921 A pattern like 'test*' will match test packages as well as
1922 modules.
1923
1924If the package :file:`__init__.py` defines ``load_tests`` then it will be
1925called and discovery not continued into the package. ``load_tests``
1926is called with the following arguments::
1927
1928 load_tests(loader, standard_tests, pattern)
1929
1930This should return a :class:`TestSuite` representing all the tests
1931from the package. (``standard_tests`` will only contain tests
1932collected from :file:`__init__.py`.)
1933
1934Because the pattern is passed into ``load_tests`` the package is free to
1935continue (and potentially modify) test discovery. A 'do nothing'
1936``load_tests`` function for a test package would look like::
1937
1938 def load_tests(loader, standard_tests, pattern):
1939 # top level directory cached on loader instance
1940 this_dir = os.path.dirname(__file__)
1941 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1942 standard_tests.addTests(package_tests)
1943 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00001944
1945
1946Class and Module Fixtures
1947-------------------------
1948
1949Class and module level fixtures are implemented in :class:`TestSuite`. When
1950the test suite encounters a test from a new class then :meth:`tearDownClass`
1951from the previous class (if there is one) is called, followed by
1952:meth:`setUpClass` from the new class.
1953
1954Similarly if a test is from a different module from the previous test then
1955``tearDownModule`` from the previous module is run, followed by
1956``setUpModule`` from the new module.
1957
1958After all the tests have run the final ``tearDownClass`` and
1959``tearDownModule`` are run.
1960
1961Note that shared fixtures do not play well with [potential] features like test
1962parallelization and they break test isolation. They should be used with care.
1963
1964The default ordering of tests created by the unittest test loaders is to group
1965all tests from the same modules and classes together. This will lead to
1966``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
1967module. If you randomize the order, so that tests from different modules and
1968classes are adjacent to each other, then these shared fixture functions may be
1969called multiple times in a single test run.
1970
1971Shared fixtures are not intended to work with suites with non-standard
1972ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
1973support shared fixtures.
1974
1975If there are any exceptions raised during one of the shared fixture functions
1976the test is reported as an error. Because there is no corresponding test
1977instance an ``_ErrorHolder`` object (that has the same interface as a
1978:class:`TestCase`) is created to represent the error. If you are just using
1979the standard unittest test runner then this detail doesn't matter, but if you
1980are a framework author it may be relevant.
1981
1982
1983setUpClass and tearDownClass
1984~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1985
1986These must be implemented as class methods::
1987
1988 import unittest
1989
1990 class Test(unittest.TestCase):
1991 @classmethod
1992 def setUpClass(cls):
1993 cls._connection = createExpensiveConnectionObject()
1994
1995 @classmethod
1996 def tearDownClass(cls):
1997 cls._connection.destroy()
1998
1999If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2000then you must call up to them yourself. The implementations in
2001:class:`TestCase` are empty.
2002
2003If an exception is raised during a ``setUpClass`` then the tests in the class
2004are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002005have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
2006``SkipTest`` exception then the class will be reported as having been skipped
2007instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002008
2009
2010setUpModule and tearDownModule
2011~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2012
2013These should be implemented as functions::
2014
2015 def setUpModule():
2016 createConnection()
2017
2018 def tearDownModule():
2019 closeConnection()
2020
2021If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002022module will be run and the ``tearDownModule`` will not be run. If the exception is a
2023``SkipTest`` exception then the module will be reported as having been skipped
2024instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002025
2026
2027Signal Handling
2028---------------
2029
Éric Araujo713d3032010-11-18 16:38:46 +00002030The :option:`-c` command-line option to unittest, along with the ``catchbreak``
Benjamin Petersonb48af542010-04-11 20:43:16 +00002031parameter to :func:`unittest.main()`, provide more friendly handling of
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002032control-C during a test run. With catch break behavior enabled control-C will
Benjamin Petersonb48af542010-04-11 20:43:16 +00002033allow the currently running test to complete, and the test run will then end
2034and report all the results so far. A second control-c will raise a
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002035:exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002036
Michael Foordde4ceab2010-04-25 19:53:49 +00002037The control-c handling signal handler attempts to remain compatible with code or
2038tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2039handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2040i.e. it has been replaced by the system under test and delegated to, then it
2041calls the default handler. This will normally be the expected behavior by code
2042that replaces an installed handler and delegates to it. For individual tests
2043that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2044decorator can be used.
2045
2046There are a few utility functions for framework authors to enable control-c
2047handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002048
2049.. function:: installHandler()
2050
2051 Install the control-c handler. When a :const:`signal.SIGINT` is received
2052 (usually in response to the user pressing control-c) all registered results
2053 have :meth:`~TestResult.stop` called.
2054
Michael Foord469b1f02010-04-26 23:41:26 +00002055 .. versionadded:: 3.2
2056
Benjamin Petersonb48af542010-04-11 20:43:16 +00002057.. function:: registerResult(result)
2058
2059 Register a :class:`TestResult` object for control-c handling. Registering a
2060 result stores a weak reference to it, so it doesn't prevent the result from
2061 being garbage collected.
2062
Michael Foordde4ceab2010-04-25 19:53:49 +00002063 Registering a :class:`TestResult` object has no side-effects if control-c
2064 handling is not enabled, so test frameworks can unconditionally register
2065 all results they create independently of whether or not handling is enabled.
2066
Michael Foord469b1f02010-04-26 23:41:26 +00002067 .. versionadded:: 3.2
2068
Benjamin Petersonb48af542010-04-11 20:43:16 +00002069.. function:: removeResult(result)
2070
2071 Remove a registered result. Once a result has been removed then
2072 :meth:`~TestResult.stop` will no longer be called on that result object in
2073 response to a control-c.
2074
Michael Foord469b1f02010-04-26 23:41:26 +00002075 .. versionadded:: 3.2
2076
Michael Foordde4ceab2010-04-25 19:53:49 +00002077.. function:: removeHandler(function=None)
2078
2079 When called without arguments this function removes the control-c handler
2080 if it has been installed. This function can also be used as a test decorator
2081 to temporarily remove the handler whilst the test is being executed::
2082
2083 @unittest.removeHandler
2084 def test_signal_handling(self):
2085 ...
2086
Michael Foord469b1f02010-04-26 23:41:26 +00002087 .. versionadded:: 3.2
2088