blob: aa3adc144b48c21ff4f8ac71afc3630d7789f36a [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
98.. _unittest-test-discovery:
99
100Test Discovery
101--------------
102
Georg Brandl853947a2010-01-31 18:53:23 +0000103.. versionadded:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +0000104
105unittest supports simple test discovery. For a project's tests to be
106compatible with test discovery they must all be importable from the top level
107directory of the project; i.e. they must all be in Python packages.
108
109Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
110used from the command line. The basic command line usage is::
111
112 cd project_directory
113 python -m unittest discover
114
115The ``discover`` sub-command has the following options:
116
117 -v, --verbose Verbose output
118 -s directory Directory to start discovery ('.' default)
119 -p pattern Pattern to match test files ('test*.py' default)
120 -t directory Top level directory of project (default to
121 start directory)
122
123The -s, -p, & -t options can be passsed in as positional arguments. The
124following two command lines are equivalent::
125
Ezio Melotti176d6c42010-01-27 20:58:07 +0000126 python -m unittest discover -s project_directory -p '*_test.py'
127 python -m unittest discover project_directory '*_test.py'
Benjamin Petersond2397752009-06-27 23:45:02 +0000128
129Test modules and packages can customize test loading and discovery by through
130the `load_tests protocol`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132.. _unittest-minimal-example:
133
134Basic example
135-------------
136
137The :mod:`unittest` module provides a rich set of tools for constructing and
138running tests. This section demonstrates that a small subset of the tools
139suffice to meet the needs of most users.
140
141Here is a short script to test three functions from the :mod:`random` module::
142
143 import random
144 import unittest
145
146 class TestSequenceFunctions(unittest.TestCase):
147
148 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000149 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Benjamin Peterson52baa292009-03-24 00:56:30 +0000151 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000152 # make sure the shuffled sequence does not lose any elements
153 random.shuffle(self.seq)
154 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000155 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Benjamin Peterson847a4112010-03-14 15:04:17 +0000157 # should raise an exception for an immutable sequence
158 self.assertRaises(TypeError, random.shuffle, (1,2,3))
159
Benjamin Peterson52baa292009-03-24 00:56:30 +0000160 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000161 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000162 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000163
Benjamin Peterson52baa292009-03-24 00:56:30 +0000164 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000165 with self.assertRaises(ValueError):
166 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000167 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000168 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170 if __name__ == '__main__':
171 unittest.main()
172
Benjamin Peterson52baa292009-03-24 00:56:30 +0000173A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000174individual tests are defined with methods whose names start with the letters
175``test``. This naming convention informs the test runner about which methods
176represent tests.
177
Benjamin Peterson52baa292009-03-24 00:56:30 +0000178The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000179expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000180:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
181These methods are used instead of the :keyword:`assert` statement so the test
182runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Benjamin Peterson52baa292009-03-24 00:56:30 +0000184When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
185method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
186defined, the test runner will invoke that method after each test. In the
187example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
188test.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190The final block shows a simple way to run the tests. :func:`unittest.main`
191provides a command line interface to the test script. When run from the command
192line, the above script produces an output that looks like this::
193
194 ...
195 ----------------------------------------------------------------------
196 Ran 3 tests in 0.000s
197
198 OK
199
200Instead of :func:`unittest.main`, there are other ways to run the tests with a
201finer level of control, less terse output, and no requirement to be run from the
202command line. For example, the last two lines may be replaced with::
203
204 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
205 unittest.TextTestRunner(verbosity=2).run(suite)
206
207Running the revised script from the interpreter or another script produces the
208following output::
209
Ezio Melottid59e44a2010-02-28 03:46:13 +0000210 test_choice (__main__.TestSequenceFunctions) ... ok
211 test_sample (__main__.TestSequenceFunctions) ... ok
212 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214 ----------------------------------------------------------------------
215 Ran 3 tests in 0.110s
216
217 OK
218
219The above examples show the most commonly used :mod:`unittest` features which
220are sufficient to meet many everyday testing needs. The remainder of the
221documentation explores the full feature set from first principles.
222
Benjamin Petersonb48af542010-04-11 20:43:16 +0000223
224.. _unittest-command-line-interface:
225
226Command Line Interface
227----------------------
228
229The unittest module can be used from the command line to run tests from
230modules, classes or even individual test methods::
231
232 python -m unittest test_module1 test_module2
233 python -m unittest test_module.TestClass
234 python -m unittest test_module.TestClass.test_method
235
236You can pass in a list with any combination of module names, and fully
237qualified class or method names.
238
239You can run tests with more detail (higher verbosity) by passing in the -v flag::
240
241 python -m unittest -v test_module
242
243For a list of all the command line options::
244
245 python -m unittest -h
246
247.. versionchanged:: 3.2
248 In earlier versions it was only possible to run individual test methods and
249 not modules or classes.
250
251
252failfast, catch and buffer command line options
253~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
254
255unittest supports three command options.
256
257* -f / --failfast
258
259 Stop the test run on the first error or failure.
260
261* -c / --catch
262
263 Control-c during the test run waits for the current test to end and then
264 reports all the results so far. A second control-c raises the normal
265 ``KeyboardInterrupt`` exception.
266
267 See `Signal Handling`_ for the functions that provide this functionality.
268
269* -b / --buffer
270
271 The standard out and standard error streams are buffered during the test
272 run. Output during a passing test is discarded. Output is echoed normally
273 on test fail or error and is added to the failure messages.
274
275.. versionadded:: 2.7
276 The command line options ``-c``, ``-b`` and ``-f`` where added.
277
278The command line can also be used for test discovery, for running all of the
279tests in a project or just a subset.
280
281
282.. _unittest-test-discovery:
283
284Test Discovery
285--------------
286
287.. versionadded:: 2.7
288
289Unittest supports simple test discovery. For a project's tests to be
290compatible with test discovery they must all be importable from the top level
291directory of the project (in other words, they must all be in Python packages).
292
293Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
294used from the command line. The basic command line usage is::
295
296 cd project_directory
297 python -m unittest discover
298
299The ``discover`` sub-command has the following options:
300
301 -v, --verbose Verbose output
302 -s directory Directory to start discovery ('.' default)
303 -p pattern Pattern to match test files ('test*.py' default)
304 -t directory Top level directory of project (default to
305 start directory)
306
307The -s, -p, & -t options can be passsed in as positional arguments. The
308following two command lines are equivalent::
309
310 python -m unittest discover -s project_directory -p '*_test.py'
311 python -m unittest discover project_directory '*_test.py'
312
313Test modules and packages can customize test loading and discovery by through
314the `load_tests protocol`_.
315
316
Georg Brandl116aa622007-08-15 14:28:22 +0000317.. _organizing-tests:
318
319Organizing test code
320--------------------
321
322The basic building blocks of unit testing are :dfn:`test cases` --- single
323scenarios that must be set up and checked for correctness. In :mod:`unittest`,
324test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
325class. To make your own test cases you must write subclasses of
326:class:`TestCase`, or use :class:`FunctionTestCase`.
327
328An instance of a :class:`TestCase`\ -derived class is an object that can
329completely run a single test method, together with optional set-up and tidy-up
330code.
331
332The testing code of a :class:`TestCase` instance should be entirely self
333contained, such that it can be run either in isolation or in arbitrary
334combination with any number of other test cases.
335
Benjamin Peterson52baa292009-03-24 00:56:30 +0000336The simplest :class:`TestCase` subclass will simply override the
337:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339 import unittest
340
341 class DefaultWidgetSizeTestCase(unittest.TestCase):
342 def runTest(self):
343 widget = Widget('The widget')
344 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
345
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000346Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000347methods provided by the :class:`TestCase` base class. If the test fails, an
348exception will be raised, and :mod:`unittest` will identify the test case as a
349:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
350helps you identify where the problem is: :dfn:`failures` are caused by incorrect
351results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
352code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354The way to run a test case will be described later. For now, note that to
355construct an instance of such a test case, we call its constructor without
356arguments::
357
358 testCase = DefaultWidgetSizeTestCase()
359
360Now, such test cases can be numerous, and their set-up can be repetitive. In
361the above case, constructing a :class:`Widget` in each of 100 Widget test case
362subclasses would mean unsightly duplication.
363
364Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000365:meth:`~TestCase.setUp`, which the testing framework will automatically call for
366us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368 import unittest
369
370 class SimpleWidgetTestCase(unittest.TestCase):
371 def setUp(self):
372 self.widget = Widget('The widget')
373
374 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
375 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000376 self.assertEqual(self.widget.size(), (50,50),
377 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379 class WidgetResizeTestCase(SimpleWidgetTestCase):
380 def runTest(self):
381 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000382 self.assertEqual(self.widget.size(), (100,150),
383 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000384
Benjamin Peterson52baa292009-03-24 00:56:30 +0000385If the :meth:`~TestCase.setUp` method raises an exception while the test is
386running, the framework will consider the test to have suffered an error, and the
387:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Benjamin Peterson52baa292009-03-24 00:56:30 +0000389Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
390after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000391
392 import unittest
393
394 class SimpleWidgetTestCase(unittest.TestCase):
395 def setUp(self):
396 self.widget = Widget('The widget')
397
398 def tearDown(self):
399 self.widget.dispose()
400 self.widget = None
401
Benjamin Peterson52baa292009-03-24 00:56:30 +0000402If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
403be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000404
405Such a working environment for the testing code is called a :dfn:`fixture`.
406
407Often, many small test cases will use the same fixture. In this case, we would
408end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
409classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000410discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
411mechanism::
412
413 import unittest
414
415 class WidgetTestCase(unittest.TestCase):
416 def setUp(self):
417 self.widget = Widget('The widget')
418
419 def tearDown(self):
420 self.widget.dispose()
421 self.widget = None
422
Ezio Melottid59e44a2010-02-28 03:46:13 +0000423 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000424 self.assertEqual(self.widget.size(), (50,50),
425 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Ezio Melottid59e44a2010-02-28 03:46:13 +0000427 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000428 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000429 self.assertEqual(self.widget.size(), (100,150),
430 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000431
Benjamin Peterson52baa292009-03-24 00:56:30 +0000432Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
433provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000434the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000435separately for each instance. When creating an instance we must specify the
436test method it is to run. We do this by passing the method name in the
437constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000438
Ezio Melottid59e44a2010-02-28 03:46:13 +0000439 defaultSizeTestCase = WidgetTestCase('test_default_size')
440 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000441
442Test case instances are grouped together according to the features they test.
443:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
444represented by :mod:`unittest`'s :class:`TestSuite` class::
445
446 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000447 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
448 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450For the ease of running tests, as we will see later, it is a good idea to
451provide in each test module a callable object that returns a pre-built test
452suite::
453
454 def suite():
455 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000456 suite.addTest(WidgetTestCase('test_default_size'))
457 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000458 return suite
459
460or even::
461
462 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000463 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000464
465 return unittest.TestSuite(map(WidgetTestCase, tests))
466
467Since it is a common pattern to create a :class:`TestCase` subclass with many
468similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
469class that can be used to automate the process of creating a test suite and
470populating it with individual tests. For example, ::
471
472 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
473
Ezio Melottid59e44a2010-02-28 03:46:13 +0000474will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
475``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000476name prefix to identify test methods automatically.
477
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000478Note that the order in which the various test cases will be run is
479determined by sorting the test function names with respect to the
480built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482Often it is desirable to group suites of test cases together, so as to run tests
483for the whole system at once. This is easy, since :class:`TestSuite` instances
484can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
485added to a :class:`TestSuite`::
486
487 suite1 = module1.TheTestSuite()
488 suite2 = module2.TheTestSuite()
489 alltests = unittest.TestSuite([suite1, suite2])
490
491You can place the definitions of test cases and test suites in the same modules
492as the code they are to test (such as :file:`widget.py`), but there are several
493advantages to placing the test code in a separate module, such as
494:file:`test_widget.py`:
495
496* The test module can be run standalone from the command line.
497
498* The test code can more easily be separated from shipped code.
499
500* There is less temptation to change test code to fit the code it tests without
501 a good reason.
502
503* Test code should be modified much less frequently than the code it tests.
504
505* Tested code can be refactored more easily.
506
507* Tests for modules written in C must be in separate modules anyway, so why not
508 be consistent?
509
510* If the testing strategy changes, there is no need to change the source code.
511
512
513.. _legacy-unit-tests:
514
515Re-using old test code
516----------------------
517
518Some users will find that they have existing test code that they would like to
519run from :mod:`unittest`, without converting every old test function to a
520:class:`TestCase` subclass.
521
522For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
523This subclass of :class:`TestCase` can be used to wrap an existing test
524function. Set-up and tear-down functions can also be provided.
525
526Given the following test function::
527
528 def testSomething():
529 something = makeSomething()
530 assert something.name is not None
531 # ...
532
533one can create an equivalent test case instance as follows::
534
535 testcase = unittest.FunctionTestCase(testSomething)
536
537If there are additional set-up and tear-down methods that should be called as
538part of the test case's operation, they can also be provided like so::
539
540 testcase = unittest.FunctionTestCase(testSomething,
541 setUp=makeSomethingDB,
542 tearDown=deleteSomethingDB)
543
544To make migrating existing test suites easier, :mod:`unittest` supports tests
545raising :exc:`AssertionError` to indicate test failure. However, it is
546recommended that you use the explicit :meth:`TestCase.fail\*` and
547:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
548may treat :exc:`AssertionError` differently.
549
550.. note::
551
Benjamin Petersond2397752009-06-27 23:45:02 +0000552 Even though :class:`FunctionTestCase` can be used to quickly convert an
553 existing test base over to a :mod:`unittest`\ -based system, this approach is
554 not recommended. Taking the time to set up proper :class:`TestCase`
555 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000556
Benjamin Peterson52baa292009-03-24 00:56:30 +0000557In some cases, the existing tests may have been written using the :mod:`doctest`
558module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
559automatically build :class:`unittest.TestSuite` instances from the existing
560:mod:`doctest`\ -based tests.
561
Georg Brandl116aa622007-08-15 14:28:22 +0000562
Benjamin Peterson5254c042009-03-23 22:25:03 +0000563.. _unittest-skipping:
564
565Skipping tests and expected failures
566------------------------------------
567
Michael Foordf5c851a2010-02-05 21:48:03 +0000568.. versionadded:: 3.1
569
Benjamin Peterson5254c042009-03-23 22:25:03 +0000570Unittest supports skipping individual test methods and even whole classes of
571tests. In addition, it supports marking a test as a "expected failure," a test
572that is broken and will fail, but shouldn't be counted as a failure on a
573:class:`TestResult`.
574
575Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
576or one of its conditional variants.
577
578Basic skipping looks like this: ::
579
580 class MyTestCase(unittest.TestCase):
581
582 @unittest.skip("demonstrating skipping")
583 def test_nothing(self):
584 self.fail("shouldn't happen")
585
Benjamin Petersond2397752009-06-27 23:45:02 +0000586 @unittest.skipIf(mylib.__version__ < (1, 3),
587 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000588 def test_format(self):
589 # Tests that work for only a certain version of the library.
590 pass
591
592 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
593 def test_windows_support(self):
594 # windows specific testing code
595 pass
596
Benjamin Peterson5254c042009-03-23 22:25:03 +0000597This is the output of running the example above in verbose mode: ::
598
Benjamin Petersonded31c42009-03-30 15:04:16 +0000599 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000600 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000601 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000602
603 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000604 Ran 3 tests in 0.005s
605
606 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000607
608Classes can be skipped just like methods: ::
609
610 @skip("showing class skipping")
611 class MySkippedTestCase(unittest.TestCase):
612 def test_not_run(self):
613 pass
614
Benjamin Peterson52baa292009-03-24 00:56:30 +0000615:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
616that needs to be set up is not available.
617
Benjamin Peterson5254c042009-03-23 22:25:03 +0000618Expected failures use the :func:`expectedFailure` decorator. ::
619
620 class ExpectedFailureTestCase(unittest.TestCase):
621 @unittest.expectedFailure
622 def test_fail(self):
623 self.assertEqual(1, 0, "broken")
624
625It's easy to roll your own skipping decorators by making a decorator that calls
626:func:`skip` on the test when it wants it to be skipped. This decorator skips
627the test unless the passed object has a certain attribute: ::
628
629 def skipUnlessHasattr(obj, attr):
630 if hasattr(obj, attr):
631 return lambda func: func
632 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
633
634The following decorators implement test skipping and expected failures:
635
636.. function:: skip(reason)
637
638 Unconditionally skip the decorated test. *reason* should describe why the
639 test is being skipped.
640
641.. function:: skipIf(condition, reason)
642
643 Skip the decorated test if *condition* is true.
644
645.. function:: skipUnless(condition, reason)
646
647 Skip the decoratored test unless *condition* is true.
648
649.. function:: expectedFailure
650
651 Mark the test as an expected failure. If the test fails when run, the test
652 is not counted as a failure.
653
Benjamin Petersonb48af542010-04-11 20:43:16 +0000654Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
655Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
656
Benjamin Peterson5254c042009-03-23 22:25:03 +0000657
Georg Brandl116aa622007-08-15 14:28:22 +0000658.. _unittest-contents:
659
660Classes and functions
661---------------------
662
Benjamin Peterson52baa292009-03-24 00:56:30 +0000663This section describes in depth the API of :mod:`unittest`.
664
665
666.. _testcase-objects:
667
668Test cases
669~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000670
Georg Brandl7f01a132009-09-16 15:58:14 +0000671.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000672
673 Instances of the :class:`TestCase` class represent the smallest testable units
674 in the :mod:`unittest` universe. This class is intended to be used as a base
675 class, with specific tests being implemented by concrete subclasses. This class
676 implements the interface needed by the test runner to allow it to drive the
677 test, and methods that the test code can use to check for and report various
678 kinds of failure.
679
680 Each instance of :class:`TestCase` will run a single test method: the method
681 named *methodName*. If you remember, we had an earlier example that went
682 something like this::
683
684 def suite():
685 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000686 suite.addTest(WidgetTestCase('test_default_size'))
687 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000688 return suite
689
690 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
691 single test.
692
Benjamin Peterson52baa292009-03-24 00:56:30 +0000693 *methodName* defaults to :meth:`runTest`.
694
695 :class:`TestCase` instances provide three groups of methods: one group used
696 to run the test, another used by the test implementation to check conditions
697 and report failures, and some inquiry methods allowing information about the
698 test itself to be gathered.
699
700 Methods in the first group (running the test) are:
701
702
703 .. method:: setUp()
704
705 Method called to prepare the test fixture. This is called immediately
706 before calling the test method; any exception raised by this method will
707 be considered an error rather than a test failure. The default
708 implementation does nothing.
709
710
711 .. method:: tearDown()
712
713 Method called immediately after the test method has been called and the
714 result recorded. This is called even if the test method raised an
715 exception, so the implementation in subclasses may need to be particularly
716 careful about checking internal state. Any exception raised by this
717 method will be considered an error rather than a test failure. This
718 method will only be called if the :meth:`setUp` succeeds, regardless of
719 the outcome of the test method. The default implementation does nothing.
720
721
Benjamin Petersonb48af542010-04-11 20:43:16 +0000722 .. method:: setUpClass()
723
724 A class method called before tests in an individual class run.
725 ``setUpClass`` is called with the class as the only argument
726 and must be decorated as a :func:`classmethod`::
727
728 @classmethod
729 def setUpClass(cls):
730 ...
731
732 See `Class and Module Fixtures`_ for more details.
733
734 .. versionadded:: 3.2
735
736
737 .. method:: tearDownClass()
738
739 A class method called after tests in an individual class have run.
740 ``tearDownClass`` is called with the class as the only argument
741 and must be decorated as a :meth:`classmethod`::
742
743 @classmethod
744 def tearDownClass(cls):
745 ...
746
747 See `Class and Module Fixtures`_ for more details.
748
749 .. versionadded:: 3.2
750
751
Georg Brandl7f01a132009-09-16 15:58:14 +0000752 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000753
754 Run the test, collecting the result into the test result object passed as
755 *result*. If *result* is omitted or :const:`None`, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000756 object is created (by calling the :meth:`defaultTestResult` method) and
757 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000758
759 The same effect may be had by simply calling the :class:`TestCase`
760 instance.
761
762
Benjamin Petersone549ead2009-03-28 21:42:05 +0000763 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000764
765 Calling this during the a test method or :meth:`setUp` skips the current
766 test. See :ref:`unittest-skipping` for more information.
767
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000768 .. versionadded:: 2.7
769
Benjamin Peterson52baa292009-03-24 00:56:30 +0000770
771 .. method:: debug()
772
773 Run the test without collecting the result. This allows exceptions raised
774 by the test to be propagated to the caller, and can be used to support
775 running tests under a debugger.
776
777 The test code can use any of the following methods to check for and report
778 failures.
779
780
Georg Brandl7f01a132009-09-16 15:58:14 +0000781 .. method:: assertTrue(expr, msg=None)
782 assert_(expr, msg=None)
783 failUnless(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000784
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000785 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson52baa292009-03-24 00:56:30 +0000786 will be *msg* if given, otherwise it will be :const:`None`.
787
Raymond Hettinger35a88362009-04-09 00:08:24 +0000788 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000789 :meth:`failUnless`; use one of the ``assert`` variants.
Michael Foord34c94622010-02-10 15:51:42 +0000790 :meth:`assert_`; use :meth:`assertTrue`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000791
Benjamin Peterson52baa292009-03-24 00:56:30 +0000792
Georg Brandl7f01a132009-09-16 15:58:14 +0000793 .. method:: assertEqual(first, second, msg=None)
794 failUnlessEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000795
796 Test that *first* and *second* are equal. If the values do not compare
797 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000798 :const:`None`. Note that using :meth:`assertEqual` improves upon
799 doing the comparison as the first parameter to :meth:`assertTrue`: the
800 default value for *msg* include representations of both *first* and
801 *second*.
802
803 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000804 list, tuple, dict, set, frozenset or str or any type that a subclass
805 registers with :meth:`addTypeEqualityFunc` the type specific equality
806 function will be called in order to generate a more useful default
807 error message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000808
Raymond Hettinger35a88362009-04-09 00:08:24 +0000809 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000810 Added the automatic calling of type specific equality function.
811
Michael Foord28a817e2010-02-09 00:03:57 +0000812 .. versionchanged:: 3.2
813 :meth:`assertMultiLineEqual` added as the default type equality
814 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000815
Raymond Hettinger35a88362009-04-09 00:08:24 +0000816 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000817 :meth:`failUnlessEqual`; use :meth:`assertEqual`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000818
819
Georg Brandl7f01a132009-09-16 15:58:14 +0000820 .. method:: assertNotEqual(first, second, msg=None)
821 failIfEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000822
823 Test that *first* and *second* are not equal. If the values do compare
824 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000825 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
826 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson52baa292009-03-24 00:56:30 +0000827 default value for *msg* can be computed to include representations of both
828 *first* and *second*.
829
Raymond Hettinger35a88362009-04-09 00:08:24 +0000830 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000831 :meth:`failIfEqual`; use :meth:`assertNotEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000832
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000833
Benjamin Petersonb48af542010-04-11 20:43:16 +0000834 .. method:: assertAlmostEqual(first, second, *, places=7, msg=None, delta=None)
835 failUnlessAlmostEqual(first, second, *, places=7, msg=None, delta=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000836
837 Test that *first* and *second* are approximately equal by computing the
838 difference, rounding to the given number of decimal *places* (default 7),
839 and comparing to zero.
840
841 Note that comparing a given number of decimal places is not the same as
842 comparing a given number of significant digits. If the values do not
843 compare equal, the test will fail with the explanation given by *msg*, or
844 :const:`None`.
845
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000846 .. versionchanged:: 3.2
847 Objects that compare equal are automatically almost equal.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000848 Added the ``delta`` keyword argument.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000849
Raymond Hettinger35a88362009-04-09 00:08:24 +0000850 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000851 :meth:`failUnlessAlmostEqual`; use :meth:`assertAlmostEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000852
Benjamin Peterson52baa292009-03-24 00:56:30 +0000853
Benjamin Petersonb48af542010-04-11 20:43:16 +0000854 .. method:: assertNotAlmostEqual(first, second, *, places=7, msg=None, delta=None)
855 failIfAlmostEqual(first, second, *, places=7, msg=None, delta=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000856
857 Test that *first* and *second* are not approximately equal by computing
858 the difference, rounding to the given number of decimal *places* (default
859 7), and comparing to zero.
860
861 Note that comparing a given number of decimal places is not the same as
862 comparing a given number of significant digits. If the values do not
863 compare equal, the test will fail with the explanation given by *msg*, or
864 :const:`None`.
865
Benjamin Petersonb48af542010-04-11 20:43:16 +0000866 If *delta* is supplied instead of *places* then the the difference
867 between *first* and *second* must be more than *delta*.
868
869 Supplying both *delta* and *places* raises a ``TypeError``.
870
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000871 .. versionchanged:: 3.2
872 Objects that compare equal automatically fail.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000873 Added the ``delta`` keyword argument.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000874
Raymond Hettinger35a88362009-04-09 00:08:24 +0000875 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +0000876 :meth:`failIfAlmostEqual`; use :meth:`assertNotAlmostEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000877
878
879 .. method:: assertGreater(first, second, msg=None)
880 assertGreaterEqual(first, second, msg=None)
881 assertLess(first, second, msg=None)
882 assertLessEqual(first, second, msg=None)
883
884 Test that *first* is respectively >, >=, < or <= than *second* depending
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000885 on the method name. If not, the test will fail with an explanation
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000886 or with the explanation given by *msg*::
887
888 >>> self.assertGreaterEqual(3, 4)
889 AssertionError: "3" unexpectedly not greater than or equal to "4"
890
Raymond Hettinger35a88362009-04-09 00:08:24 +0000891 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000892
893
894 .. method:: assertMultiLineEqual(self, first, second, msg=None)
895
896 Test that the multiline string *first* is equal to the string *second*.
897 When not equal a diff of the two strings highlighting the differences
Michael Foord02834952010-02-08 23:10:39 +0000898 will be included in the error message. This method is used by default
899 when comparing strings with :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000900
Michael Foordabd91d52010-03-20 18:09:14 +0000901 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000902
Raymond Hettinger35a88362009-04-09 00:08:24 +0000903 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000904
905
Ezio Melotti732b6822010-01-16 19:40:06 +0000906 .. method:: assertRegexpMatches(text, regexp, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000907
908 Verifies that a *regexp* search matches *text*. Fails with an error
909 message including the pattern and the *text*. *regexp* may be
910 a regular expression object or a string containing a regular expression
911 suitable for use by :func:`re.search`.
912
Raymond Hettinger35a88362009-04-09 00:08:24 +0000913 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000914
915
Benjamin Petersonb48af542010-04-11 20:43:16 +0000916 .. method:: assertNotRegexpMatches(text, regexp, msg=None)
917
918 Verifies that a *regexp* search does not match *text*. Fails with an error
919 message including the pattern and the *text*. *regexp* may be
920 a regular expression object or a string containing a regular expression
921 suitable for use by :func:`re.search`.
922
923 .. versionadded:: 2.7
924
925
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000926 .. method:: assertIn(first, second, msg=None)
927 assertNotIn(first, second, msg=None)
928
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000929 Tests that *first* is or is not in *second* with an explanatory error
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000930 message as appropriate.
931
Michael Foordabd91d52010-03-20 18:09:14 +0000932 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000933
Raymond Hettinger35a88362009-04-09 00:08:24 +0000934 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000935
936
Michael Foorde9abbee2010-02-05 20:54:27 +0000937 .. method:: assertSameElements(actual, expected, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000938
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000939 Test that sequence *expected* contains the same elements as *actual*,
940 regardless of their order. When they don't, an error message listing
941 the differences between the sequences will be generated.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000942
Michael Foorde9abbee2010-02-05 20:54:27 +0000943 Duplicate elements are ignored when comparing *actual* and *expected*.
944 It is the equivalent of ``assertEqual(set(expected), set(actual))``
Michael Foordabd91d52010-03-20 18:09:14 +0000945 but it works with sequences of unhashable objects as well. Because
946 duplicates are ignored, this method has been deprecated in favour of
947 :meth:`assertItemsEqual`.
Michael Foorde9abbee2010-02-05 20:54:27 +0000948
Michael Foordabd91d52010-03-20 18:09:14 +0000949 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000950
Raymond Hettinger35a88362009-04-09 00:08:24 +0000951 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000952
Michael Foordabd91d52010-03-20 18:09:14 +0000953 .. deprecated:: 3.2
954
955 .. method:: assertItemsEqual(actual, expected, msg=None)
956
957 Test that sequence *expected* contains the same elements as *actual*,
958 regardless of their order. When they don't, an error message listing the
959 differences between the sequences will be generated.
960
961 Duplicate elements are *not* ignored when comparing *actual* and
962 *expected*. It verifies if each element has the same count in both
963 sequences. It is the equivalent of ``assertEqual(sorted(expected),
964 sorted(actual))`` but it works with sequences of unhashable objects as
965 well.
966
967 If specified, *msg* will be used as the error message on failure.
968
969 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000970
971 .. method:: assertSetEqual(set1, set2, msg=None)
972
973 Tests that two sets are equal. If not, an error message is constructed
Michael Foord02834952010-02-08 23:10:39 +0000974 that lists the differences between the sets. This method is used by
975 default when comparing sets or frozensets with :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000976
977 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
978 method.
979
Michael Foordabd91d52010-03-20 18:09:14 +0000980 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000981
Raymond Hettinger35a88362009-04-09 00:08:24 +0000982 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000983
984
985 .. method:: assertDictEqual(expected, actual, msg=None)
986
987 Test that two dictionaries are equal. If not, an error message is
Michael Foord02834952010-02-08 23:10:39 +0000988 constructed that shows the differences in the dictionaries. This
989 method will be used by default to compare dictionaries in
990 calls to :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000991
Michael Foordabd91d52010-03-20 18:09:14 +0000992 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000993
Raymond Hettinger35a88362009-04-09 00:08:24 +0000994 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000995
996
997 .. method:: assertDictContainsSubset(expected, actual, msg=None)
998
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000999 Tests whether the key/value pairs in dictionary *actual* are a
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001000 superset of those in *expected*. If not, an error message listing
1001 the missing keys and mismatched values is generated.
1002
Michael Foordabd91d52010-03-20 18:09:14 +00001003 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001004
Raymond Hettinger35a88362009-04-09 00:08:24 +00001005 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001006
1007
1008 .. method:: assertListEqual(list1, list2, msg=None)
1009 assertTupleEqual(tuple1, tuple2, msg=None)
1010
1011 Tests that two lists or tuples are equal. If not an error message is
1012 constructed that shows only the differences between the two. An error
1013 is also raised if either of the parameters are of the wrong type.
Michael Foord02834952010-02-08 23:10:39 +00001014 These methods are used by default when comparing lists or tuples with
1015 :meth:`assertEqual`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001016
Michael Foordabd91d52010-03-20 18:09:14 +00001017 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001018
Raymond Hettinger35a88362009-04-09 00:08:24 +00001019 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001020
1021
1022 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
1023
1024 Tests that two sequences are equal. If a *seq_type* is supplied, both
1025 *seq1* and *seq2* must be instances of *seq_type* or a failure will
1026 be raised. If the sequences are different an error message is
1027 constructed that shows the difference between the two.
1028
Michael Foordabd91d52010-03-20 18:09:14 +00001029 If specified, *msg* will be used as the error message on failure.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001030
1031 This method is used to implement :meth:`assertListEqual` and
1032 :meth:`assertTupleEqual`.
1033
Raymond Hettinger35a88362009-04-09 00:08:24 +00001034 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001035
Benjamin Peterson52baa292009-03-24 00:56:30 +00001036
Georg Brandl7f01a132009-09-16 15:58:14 +00001037 .. method:: assertRaises(exception, callable, *args, **kwds)
1038 failUnlessRaises(exception, callable, *args, **kwds)
1039 assertRaises(exception)
1040 failUnlessRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001041
1042 Test that an exception is raised when *callable* is called with any
1043 positional or keyword arguments that are also passed to
1044 :meth:`assertRaises`. The test passes if *exception* is raised, is an
1045 error if another exception is raised, or fails if no exception is raised.
1046 To catch any of a group of exceptions, a tuple containing the exception
1047 classes may be passed as *exception*.
1048
Georg Brandl7f01a132009-09-16 15:58:14 +00001049 If only the *exception* argument is given, returns a context manager so
1050 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +00001051
Michael Foord41531f22010-02-05 21:13:40 +00001052 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +00001053 do_something()
1054
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00001055 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +00001056 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +00001057 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00001058
Michael Foord41531f22010-02-05 21:13:40 +00001059 with self.assertRaises(SomeException) as cm:
1060 do_something()
1061
Ezio Melotti49008232010-02-08 21:57:48 +00001062 the_exception = cm.exception
Michael Foordb112a412010-02-05 23:32:33 +00001063 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +00001064
Ezio Melotti49008232010-02-08 21:57:48 +00001065 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +00001066 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001067
Ezio Melotti49008232010-02-08 21:57:48 +00001068 .. versionchanged:: 3.2
1069 Added the :attr:`exception` attribute.
1070
Raymond Hettinger35a88362009-04-09 00:08:24 +00001071 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +00001072 :meth:`failUnlessRaises`; use :meth:`assertRaises`.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001073
Benjamin Peterson52baa292009-03-24 00:56:30 +00001074
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001075 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
1076
1077 Like :meth:`assertRaises` but also tests that *regexp* matches
1078 on the string representation of the raised exception. *regexp* may be
1079 a regular expression object or a string containing a regular expression
1080 suitable for use by :func:`re.search`. Examples::
1081
1082 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
1083 int, 'XYZ')
1084
1085 or::
1086
1087 with self.assertRaisesRegexp(ValueError, 'literal'):
1088 int('XYZ')
1089
Raymond Hettinger35a88362009-04-09 00:08:24 +00001090 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001091
1092
Georg Brandl7f01a132009-09-16 15:58:14 +00001093 .. method:: assertIsNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001094
1095 This signals a test failure if *expr* is not None.
1096
Raymond Hettinger35a88362009-04-09 00:08:24 +00001097 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001098
1099
Georg Brandl7f01a132009-09-16 15:58:14 +00001100 .. method:: assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001101
1102 The inverse of the :meth:`assertIsNone` method.
1103 This signals a test failure if *expr* is None.
1104
Raymond Hettinger35a88362009-04-09 00:08:24 +00001105 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001106
1107
Georg Brandl7f01a132009-09-16 15:58:14 +00001108 .. method:: assertIs(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001109
1110 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
1111 object.
1112
Georg Brandl705d9d52009-05-05 09:29:50 +00001113 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001114
1115
Georg Brandl7f01a132009-09-16 15:58:14 +00001116 .. method:: assertIsNot(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001117
1118 The inverse of the :meth:`assertIs` method.
1119 This signals a test failure if *expr1* and *expr2* evaluate to the same
1120 object.
1121
Georg Brandl705d9d52009-05-05 09:29:50 +00001122 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001123
1124
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001125 .. method:: assertIsInstance(obj, cls[, msg])
1126
1127 This signals a test failure if *obj* is not an instance of *cls* (which
1128 can be a class or a tuple of classes, as supported by :func:`isinstance`).
1129
1130 .. versionadded:: 3.2
1131
1132
1133 .. method:: assertNotIsInstance(obj, cls[, msg])
1134
1135 The inverse of the :meth:`assertIsInstance` method. This signals a test
1136 failure if *obj* is an instance of *cls*.
1137
1138 .. versionadded:: 3.2
1139
1140
Georg Brandl7f01a132009-09-16 15:58:14 +00001141 .. method:: assertFalse(expr, msg=None)
1142 failIf(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001143
1144 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001145 This signals a test failure if *expr* is true, with *msg* or :const:`None`
1146 for the error message.
1147
Raymond Hettinger35a88362009-04-09 00:08:24 +00001148 .. deprecated:: 3.1
Georg Brandl89fad142010-03-14 10:23:39 +00001149 :meth:`failIf`; use :meth:`assertFalse`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001150
Benjamin Peterson52baa292009-03-24 00:56:30 +00001151
Georg Brandl7f01a132009-09-16 15:58:14 +00001152 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001153
1154 Signals a test failure unconditionally, with *msg* or :const:`None` for
1155 the error message.
1156
1157
1158 .. attribute:: failureException
1159
1160 This class attribute gives the exception raised by the test method. If a
1161 test framework needs to use a specialized exception, possibly to carry
1162 additional information, it must subclass this exception in order to "play
1163 fair" with the framework. The initial value of this attribute is
1164 :exc:`AssertionError`.
1165
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001166
1167 .. attribute:: longMessage
1168
1169 If set to True then any explicit failure message you pass in to the
1170 assert methods will be appended to the end of the normal failure message.
1171 The normal messages contain useful information about the objects involved,
1172 for example the message from assertEqual shows you the repr of the two
1173 unequal objects. Setting this attribute to True allows you to have a
1174 custom error message in addition to the normal one.
1175
1176 This attribute defaults to False, meaning that a custom message passed
1177 to an assert method will silence the normal message.
1178
1179 The class setting can be overridden in individual tests by assigning an
1180 instance attribute to True or False before calling the assert methods.
1181
Raymond Hettinger35a88362009-04-09 00:08:24 +00001182 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001183
1184
Benjamin Peterson52baa292009-03-24 00:56:30 +00001185 Testing frameworks can use the following methods to collect information on
1186 the test:
1187
1188
1189 .. method:: countTestCases()
1190
1191 Return the number of tests represented by this test object. For
1192 :class:`TestCase` instances, this will always be ``1``.
1193
1194
1195 .. method:: defaultTestResult()
1196
1197 Return an instance of the test result class that should be used for this
1198 test case class (if no other result instance is provided to the
1199 :meth:`run` method).
1200
1201 For :class:`TestCase` instances, this will always be an instance of
1202 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1203 as necessary.
1204
1205
1206 .. method:: id()
1207
1208 Return a string identifying the specific test case. This is usually the
1209 full name of the test method, including the module and class name.
1210
1211
1212 .. method:: shortDescription()
1213
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001214 Returns a description of the test, or :const:`None` if no description
1215 has been provided. The default implementation of this method
1216 returns the first line of the test method's docstring, if available,
Michael Foord34c94622010-02-10 15:51:42 +00001217 or :const:`None`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001218
Michael Foord34c94622010-02-10 15:51:42 +00001219 .. versionchanged:: 3.1,3.2
1220 In 3.1 this was changed to add the test name to the short description
1221 even in the presence of a docstring. This caused compatibility issues
1222 with unittest extensions and adding the test name was moved to the
1223 :class:`TextTestResult`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001224
1225 .. method:: addTypeEqualityFunc(typeobj, function)
1226
1227 Registers a type specific :meth:`assertEqual` equality checking
1228 function to be called by :meth:`assertEqual` when both objects it has
1229 been asked to compare are exactly *typeobj* (not subclasses).
1230 *function* must take two positional arguments and a third msg=None
1231 keyword argument just as :meth:`assertEqual` does. It must raise
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001232 ``self.failureException`` when inequality between the first two
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001233 parameters is detected.
1234
1235 One good use of custom equality checking functions for a type
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001236 is to raise ``self.failureException`` with an error message useful
1237 for debugging the problem by explaining the inequalities in detail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001238
Raymond Hettinger35a88362009-04-09 00:08:24 +00001239 .. versionadded:: 3.1
Georg Brandl116aa622007-08-15 14:28:22 +00001240
1241
Georg Brandl7f01a132009-09-16 15:58:14 +00001242 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001243
1244 Add a function to be called after :meth:`tearDown` to cleanup resources
1245 used during the test. Functions will be called in reverse order to the
1246 order they are added (LIFO). They are called with any arguments and
1247 keyword arguments passed into :meth:`addCleanup` when they are
1248 added.
1249
1250 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1251 then any cleanup functions added will still be called.
1252
Georg Brandl853947a2010-01-31 18:53:23 +00001253 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001254
1255
1256 .. method:: doCleanups()
1257
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001258 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001259 after :meth:`setUp` if :meth:`setUp` raises an exception.
1260
1261 It is responsible for calling all the cleanup functions added by
1262 :meth:`addCleanup`. If you need cleanup functions to be called
1263 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1264 yourself.
1265
1266 :meth:`doCleanups` pops methods off the stack of cleanup
1267 functions one at a time, so it can be called at any time.
1268
Georg Brandl853947a2010-01-31 18:53:23 +00001269 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001270
1271
Georg Brandl7f01a132009-09-16 15:58:14 +00001272.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001273
1274 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001275 allows the test runner to drive the test, but does not provide the methods
1276 which test code can use to check and report errors. This is used to create
1277 test cases using legacy test code, allowing it to be integrated into a
1278 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001279
1280
Benjamin Peterson52baa292009-03-24 00:56:30 +00001281.. _testsuite-objects:
1282
Benjamin Peterson52baa292009-03-24 00:56:30 +00001283Grouping tests
1284~~~~~~~~~~~~~~
1285
Georg Brandl7f01a132009-09-16 15:58:14 +00001286.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001287
1288 This class represents an aggregation of individual tests cases and test suites.
1289 The class presents the interface needed by the test runner to allow it to be run
1290 as any other test case. Running a :class:`TestSuite` instance is the same as
1291 iterating over the suite, running each test individually.
1292
1293 If *tests* is given, it must be an iterable of individual test cases or other
1294 test suites that will be used to build the suite initially. Additional methods
1295 are provided to add test cases and suites to the collection later on.
1296
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001297 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1298 they do not actually implement a test. Instead, they are used to aggregate
1299 tests into groups of tests that should be run together. Some additional
1300 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001301
1302
1303 .. method:: TestSuite.addTest(test)
1304
1305 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1306
1307
1308 .. method:: TestSuite.addTests(tests)
1309
1310 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1311 instances to this test suite.
1312
Benjamin Petersond2397752009-06-27 23:45:02 +00001313 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1314 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001315
1316 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1317
1318
1319 .. method:: run(result)
1320
1321 Run the tests associated with this suite, collecting the result into the
1322 test result object passed as *result*. Note that unlike
1323 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1324 be passed in.
1325
1326
1327 .. method:: debug()
1328
1329 Run the tests associated with this suite without collecting the
1330 result. This allows exceptions raised by the test to be propagated to the
1331 caller and can be used to support running tests under a debugger.
1332
1333
1334 .. method:: countTestCases()
1335
1336 Return the number of tests represented by this test object, including all
1337 individual tests and sub-suites.
1338
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001339
1340 .. method:: __iter__()
1341
1342 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1343 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1344 that this method maybe called several times on a single suite
1345 (for example when counting tests or comparing for equality)
1346 so the tests returned must be the same for repeated iterations.
1347
Georg Brandl853947a2010-01-31 18:53:23 +00001348 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001349 In earlier versions the :class:`TestSuite` accessed tests directly rather
1350 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1351 for providing tests.
1352
Benjamin Peterson52baa292009-03-24 00:56:30 +00001353 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1354 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1355
1356
Benjamin Peterson52baa292009-03-24 00:56:30 +00001357Loading and running tests
1358~~~~~~~~~~~~~~~~~~~~~~~~~
1359
Georg Brandl116aa622007-08-15 14:28:22 +00001360.. class:: TestLoader()
1361
Benjamin Peterson52baa292009-03-24 00:56:30 +00001362 The :class:`TestLoader` class is used to create test suites from classes and
1363 modules. Normally, there is no need to create an instance of this class; the
1364 :mod:`unittest` module provides an instance that can be shared as
1365 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1366 customization of some configurable properties.
1367
1368 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001369
Michael Foordabd91d52010-03-20 18:09:14 +00001370a
Benjamin Peterson52baa292009-03-24 00:56:30 +00001371 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001372
Benjamin Peterson52baa292009-03-24 00:56:30 +00001373 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1374 :class:`testCaseClass`.
1375
1376
1377 .. method:: loadTestsFromModule(module)
1378
1379 Return a suite of all tests cases contained in the given module. This
1380 method searches *module* for classes derived from :class:`TestCase` and
1381 creates an instance of the class for each test method defined for the
1382 class.
1383
Georg Brandle720c0a2009-04-27 16:20:50 +00001384 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001385
1386 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1387 convenient in sharing fixtures and helper functions, defining test
1388 methods on base classes that are not intended to be instantiated
1389 directly does not play well with this method. Doing so, however, can
1390 be useful when the fixtures are different and defined in subclasses.
1391
Benjamin Petersond2397752009-06-27 23:45:02 +00001392 If a module provides a ``load_tests`` function it will be called to
1393 load the tests. This allows modules to customize test loading.
1394 This is the `load_tests protocol`_.
1395
Georg Brandl853947a2010-01-31 18:53:23 +00001396 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001397 Support for ``load_tests`` added.
1398
Benjamin Peterson52baa292009-03-24 00:56:30 +00001399
Georg Brandl7f01a132009-09-16 15:58:14 +00001400 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001401
1402 Return a suite of all tests cases given a string specifier.
1403
1404 The specifier *name* is a "dotted name" that may resolve either to a
1405 module, a test case class, a test method within a test case class, a
1406 :class:`TestSuite` instance, or a callable object which returns a
1407 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1408 applied in the order listed here; that is, a method on a possible test
1409 case class will be picked up as "a test method within a test case class",
1410 rather than "a callable object".
1411
1412 For example, if you have a module :mod:`SampleTests` containing a
1413 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1414 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001415 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1416 return a suite which will run all three test methods. Using the specifier
1417 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1418 suite which will run only the :meth:`test_two` test method. The specifier
1419 can refer to modules and packages which have not been imported; they will
1420 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001421
1422 The method optionally resolves *name* relative to the given *module*.
1423
1424
Georg Brandl7f01a132009-09-16 15:58:14 +00001425 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001426
1427 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1428 than a single name. The return value is a test suite which supports all
1429 the tests defined for each name.
1430
1431
1432 .. method:: getTestCaseNames(testCaseClass)
1433
1434 Return a sorted sequence of method names found within *testCaseClass*;
1435 this should be a subclass of :class:`TestCase`.
1436
Benjamin Petersond2397752009-06-27 23:45:02 +00001437
1438 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1439
1440 Find and return all test modules from the specified start directory,
1441 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001442 *pattern* will be loaded. (Using shell style pattern matching.) Only
1443 module names that are importable (i.e. are valid Python identifiers) will
1444 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001445
1446 All test modules must be importable from the top level of the project. If
1447 the start directory is not the top level directory then the top level
1448 directory must be specified separately.
1449
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001450 If importing a module fails, for example due to a syntax error, then this
1451 will be recorded as a single error and discovery will continue.
1452
Benjamin Petersond2397752009-06-27 23:45:02 +00001453 If a test package name (directory with :file:`__init__.py`) matches the
1454 pattern then the package will be checked for a ``load_tests``
1455 function. If this exists then it will be called with *loader*, *tests*,
1456 *pattern*.
1457
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001458 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001459 ``load_tests`` is responsible for loading all tests in the package.
1460
1461 The pattern is deliberately not stored as a loader attribute so that
1462 packages can continue discovery themselves. *top_level_dir* is stored so
1463 ``load_tests`` does not need to pass this argument in to
1464 ``loader.discover()``.
1465
Benjamin Petersonb48af542010-04-11 20:43:16 +00001466 *start_dir* can be a dotted module name as well as a directory.
1467
Georg Brandl853947a2010-01-31 18:53:23 +00001468 .. versionadded:: 3.2
1469
Benjamin Petersond2397752009-06-27 23:45:02 +00001470
Benjamin Peterson52baa292009-03-24 00:56:30 +00001471 The following attributes of a :class:`TestLoader` can be configured either by
1472 subclassing or assignment on an instance:
1473
1474
1475 .. attribute:: testMethodPrefix
1476
1477 String giving the prefix of method names which will be interpreted as test
1478 methods. The default value is ``'test'``.
1479
1480 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1481 methods.
1482
1483
1484 .. attribute:: sortTestMethodsUsing
1485
1486 Function to be used to compare method names when sorting them in
1487 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1488
1489
1490 .. attribute:: suiteClass
1491
1492 Callable object that constructs a test suite from a list of tests. No
1493 methods on the resulting object are needed. The default value is the
1494 :class:`TestSuite` class.
1495
1496 This affects all the :meth:`loadTestsFrom\*` methods.
1497
1498
Benjamin Peterson52baa292009-03-24 00:56:30 +00001499.. class:: TestResult
1500
1501 This class is used to compile information about which tests have succeeded
1502 and which have failed.
1503
1504 A :class:`TestResult` object stores the results of a set of tests. The
1505 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1506 properly recorded; test authors do not need to worry about recording the
1507 outcome of tests.
1508
1509 Testing frameworks built on top of :mod:`unittest` may want access to the
1510 :class:`TestResult` object generated by running a set of tests for reporting
1511 purposes; a :class:`TestResult` instance is returned by the
1512 :meth:`TestRunner.run` method for this purpose.
1513
1514 :class:`TestResult` instances have the following attributes that will be of
1515 interest when inspecting the results of running a set of tests:
1516
1517
1518 .. attribute:: errors
1519
1520 A list containing 2-tuples of :class:`TestCase` instances and strings
1521 holding formatted tracebacks. Each tuple represents a test which raised an
1522 unexpected exception.
1523
Benjamin Peterson52baa292009-03-24 00:56:30 +00001524 .. attribute:: failures
1525
1526 A list containing 2-tuples of :class:`TestCase` instances and strings
1527 holding formatted tracebacks. Each tuple represents a test where a failure
1528 was explicitly signalled using the :meth:`TestCase.fail\*` or
1529 :meth:`TestCase.assert\*` methods.
1530
Benjamin Peterson52baa292009-03-24 00:56:30 +00001531 .. attribute:: skipped
1532
1533 A list containing 2-tuples of :class:`TestCase` instances and strings
1534 holding the reason for skipping the test.
1535
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001536 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001537
1538 .. attribute:: expectedFailures
1539
1540 A list contaning 2-tuples of :class:`TestCase` instances and strings
1541 holding formatted tracebacks. Each tuple represents a expected failures
1542 of the test case.
1543
1544 .. attribute:: unexpectedSuccesses
1545
1546 A list containing :class:`TestCase` instances that were marked as expected
1547 failures, but succeeded.
1548
1549 .. attribute:: shouldStop
1550
1551 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1552
1553
1554 .. attribute:: testsRun
1555
1556 The total number of tests run so far.
1557
1558
Benjamin Petersonb48af542010-04-11 20:43:16 +00001559 .. attribute:: buffer
1560
1561 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1562 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1563 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1564 fails or errors. Any output is also attached to the failure / error message.
1565
1566 .. versionadded:: 2.7
1567
1568
1569 .. attribute:: failfast
1570
1571 If set to true :meth:`stop` will be called on the first failure or error,
1572 halting the test run.
1573
1574 .. versionadded:: 2.7
1575
1576
Benjamin Peterson52baa292009-03-24 00:56:30 +00001577 .. method:: wasSuccessful()
1578
1579 Return :const:`True` if all tests run so far have passed, otherwise returns
1580 :const:`False`.
1581
1582
1583 .. method:: stop()
1584
1585 This method can be called to signal that the set of tests being run should
1586 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1587 :class:`TestRunner` objects should respect this flag and return without
1588 running any additional tests.
1589
1590 For example, this feature is used by the :class:`TextTestRunner` class to
1591 stop the test framework when the user signals an interrupt from the
1592 keyboard. Interactive tools which provide :class:`TestRunner`
1593 implementations can use this in a similar manner.
1594
1595 The following methods of the :class:`TestResult` class are used to maintain
1596 the internal data structures, and may be extended in subclasses to support
1597 additional reporting requirements. This is particularly useful in building
1598 tools which support interactive reporting while tests are being run.
1599
1600
1601 .. method:: startTest(test)
1602
1603 Called when the test case *test* is about to be run.
1604
Benjamin Peterson52baa292009-03-24 00:56:30 +00001605 .. method:: stopTest(test)
1606
1607 Called after the test case *test* has been executed, regardless of the
1608 outcome.
1609
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001610 .. method:: startTestRun(test)
1611
1612 Called once before any tests are executed.
1613
Georg Brandl853947a2010-01-31 18:53:23 +00001614 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001615
1616
1617 .. method:: stopTestRun(test)
1618
Ezio Melotti176d6c42010-01-27 20:58:07 +00001619 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001620
Georg Brandl853947a2010-01-31 18:53:23 +00001621 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001622
1623
Benjamin Peterson52baa292009-03-24 00:56:30 +00001624 .. method:: addError(test, err)
1625
1626 Called when the test case *test* raises an unexpected exception *err* is a
1627 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1628 traceback)``.
1629
1630 The default implementation appends a tuple ``(test, formatted_err)`` to
1631 the instance's :attr:`errors` attribute, where *formatted_err* is a
1632 formatted traceback derived from *err*.
1633
1634
1635 .. method:: addFailure(test, err)
1636
Benjamin Petersond2397752009-06-27 23:45:02 +00001637 Called when the test case *test* signals a failure. *err* is a tuple of
1638 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001639
1640 The default implementation appends a tuple ``(test, formatted_err)`` to
1641 the instance's :attr:`failures` attribute, where *formatted_err* is a
1642 formatted traceback derived from *err*.
1643
1644
1645 .. method:: addSuccess(test)
1646
1647 Called when the test case *test* succeeds.
1648
1649 The default implementation does nothing.
1650
1651
1652 .. method:: addSkip(test, reason)
1653
1654 Called when the test case *test* is skipped. *reason* is the reason the
1655 test gave for skipping.
1656
1657 The default implementation appends a tuple ``(test, reason)`` to the
1658 instance's :attr:`skipped` attribute.
1659
1660
1661 .. method:: addExpectedFailure(test, err)
1662
1663 Called when the test case *test* fails, but was marked with the
1664 :func:`expectedFailure` decorator.
1665
1666 The default implementation appends a tuple ``(test, formatted_err)`` to
1667 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1668 is a formatted traceback derived from *err*.
1669
1670
1671 .. method:: addUnexpectedSuccess(test)
1672
1673 Called when the test case *test* was marked with the
1674 :func:`expectedFailure` decorator, but succeeded.
1675
1676 The default implementation appends the test to the instance's
1677 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001678
Michael Foord34c94622010-02-10 15:51:42 +00001679.. class:: TextTestResult(stream, descriptions, verbosity)
1680
1681 A concrete implementation of :class:`TestResult` used by the
1682 :class:`TextTestRunner`.
1683
1684 .. versionadded:: 3.2
1685 This class was previously named ``_TextTestResult``. The old name still
1686 exists as an alias but is deprecated.
Georg Brandl116aa622007-08-15 14:28:22 +00001687
1688.. data:: defaultTestLoader
1689
1690 Instance of the :class:`TestLoader` class intended to be shared. If no
1691 customization of the :class:`TestLoader` is needed, this instance can be used
1692 instead of repeatedly creating new instances.
1693
1694
Michael Foord34c94622010-02-10 15:51:42 +00001695.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001696
1697 A basic test runner implementation which prints results on standard error. It
1698 has a few configurable parameters, but is essentially very simple. Graphical
1699 applications which run test suites should provide alternate implementations.
1700
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001701 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001702
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001703 This method returns the instance of ``TestResult`` used by :meth:`run`.
1704 It is not intended to be called directly, but can be overridden in
1705 subclasses to provide a custom ``TestResult``.
1706
Michael Foord34c94622010-02-10 15:51:42 +00001707 ``_makeResult()`` instantiates the class or callable passed in the
1708 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001709 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001710 The result class is instantiated with the following arguments::
1711
1712 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001713
Benjamin Petersonb48af542010-04-11 20:43:16 +00001714.. 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 +00001715
1716 A command-line program that runs a set of tests; this is primarily for making
1717 test modules conveniently executable. The simplest use for this function is to
1718 include the following line at the end of a test script::
1719
1720 if __name__ == '__main__':
1721 unittest.main()
1722
Benjamin Petersond2397752009-06-27 23:45:02 +00001723 You can run tests with more detailed information by passing in the verbosity
1724 argument::
1725
1726 if __name__ == '__main__':
1727 unittest.main(verbosity=2)
1728
Georg Brandl116aa622007-08-15 14:28:22 +00001729 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001730 created instance of it. By default ``main`` calls :func:`sys.exit` with
1731 an exit code indicating success or failure of the tests run.
1732
1733 ``main`` supports being used from the interactive interpreter by passing in the
1734 argument ``exit=False``. This displays the result on standard output without
1735 calling :func:`sys.exit`::
1736
1737 >>> from unittest import main
1738 >>> main(module='test_module', exit=False)
1739
Benjamin Petersonb48af542010-04-11 20:43:16 +00001740 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
1741 effect as the `failfast, catch and buffer command line options`_.
1742
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001743 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1744 This stores the result of the tests run as the ``result`` attribute.
1745
Georg Brandl853947a2010-01-31 18:53:23 +00001746 .. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001747 The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
1748 parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001749
1750
1751load_tests Protocol
1752###################
1753
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001754
Georg Brandl853947a2010-01-31 18:53:23 +00001755.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001756
1757
Benjamin Petersond2397752009-06-27 23:45:02 +00001758Modules or packages can customize how tests are loaded from them during normal
1759test runs or test discovery by implementing a function called ``load_tests``.
1760
1761If a test module defines ``load_tests`` it will be called by
1762:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1763
1764 load_tests(loader, standard_tests, None)
1765
1766It should return a :class:`TestSuite`.
1767
1768*loader* is the instance of :class:`TestLoader` doing the loading.
1769*standard_tests* are the tests that would be loaded by default from the
1770module. It is common for test modules to only want to add or remove tests
1771from the standard set of tests.
1772The third argument is used when loading packages as part of test discovery.
1773
1774A typical ``load_tests`` function that loads tests from a specific set of
1775:class:`TestCase` classes may look like::
1776
1777 test_cases = (TestCase1, TestCase2, TestCase3)
1778
1779 def load_tests(loader, tests, pattern):
1780 suite = TestSuite()
1781 for test_class in test_cases:
1782 tests = loader.loadTestsFromTestCase(test_class)
1783 suite.addTests(tests)
1784 return suite
1785
1786If discovery is started, either from the command line or by calling
1787:meth:`TestLoader.discover`, with a pattern that matches a package
1788name then the package :file:`__init__.py` will be checked for ``load_tests``.
1789
1790.. note::
1791
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001792 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00001793 that start with 'test' but *won't* match any test directories.
1794
1795 A pattern like 'test*' will match test packages as well as
1796 modules.
1797
1798If the package :file:`__init__.py` defines ``load_tests`` then it will be
1799called and discovery not continued into the package. ``load_tests``
1800is called with the following arguments::
1801
1802 load_tests(loader, standard_tests, pattern)
1803
1804This should return a :class:`TestSuite` representing all the tests
1805from the package. (``standard_tests`` will only contain tests
1806collected from :file:`__init__.py`.)
1807
1808Because the pattern is passed into ``load_tests`` the package is free to
1809continue (and potentially modify) test discovery. A 'do nothing'
1810``load_tests`` function for a test package would look like::
1811
1812 def load_tests(loader, standard_tests, pattern):
1813 # top level directory cached on loader instance
1814 this_dir = os.path.dirname(__file__)
1815 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1816 standard_tests.addTests(package_tests)
1817 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00001818
1819
1820Class and Module Fixtures
1821-------------------------
1822
1823Class and module level fixtures are implemented in :class:`TestSuite`. When
1824the test suite encounters a test from a new class then :meth:`tearDownClass`
1825from the previous class (if there is one) is called, followed by
1826:meth:`setUpClass` from the new class.
1827
1828Similarly if a test is from a different module from the previous test then
1829``tearDownModule`` from the previous module is run, followed by
1830``setUpModule`` from the new module.
1831
1832After all the tests have run the final ``tearDownClass`` and
1833``tearDownModule`` are run.
1834
1835Note that shared fixtures do not play well with [potential] features like test
1836parallelization and they break test isolation. They should be used with care.
1837
1838The default ordering of tests created by the unittest test loaders is to group
1839all tests from the same modules and classes together. This will lead to
1840``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
1841module. If you randomize the order, so that tests from different modules and
1842classes are adjacent to each other, then these shared fixture functions may be
1843called multiple times in a single test run.
1844
1845Shared fixtures are not intended to work with suites with non-standard
1846ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
1847support shared fixtures.
1848
1849If there are any exceptions raised during one of the shared fixture functions
1850the test is reported as an error. Because there is no corresponding test
1851instance an ``_ErrorHolder`` object (that has the same interface as a
1852:class:`TestCase`) is created to represent the error. If you are just using
1853the standard unittest test runner then this detail doesn't matter, but if you
1854are a framework author it may be relevant.
1855
1856
1857setUpClass and tearDownClass
1858~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1859
1860These must be implemented as class methods::
1861
1862 import unittest
1863
1864 class Test(unittest.TestCase):
1865 @classmethod
1866 def setUpClass(cls):
1867 cls._connection = createExpensiveConnectionObject()
1868
1869 @classmethod
1870 def tearDownClass(cls):
1871 cls._connection.destroy()
1872
1873If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
1874then you must call up to them yourself. The implementations in
1875:class:`TestCase` are empty.
1876
1877If an exception is raised during a ``setUpClass`` then the tests in the class
1878are not run and the ``tearDownClass`` is not run. Skipped classes will not
1879have ``setUpClass`` or ``tearDownClass`` run.
1880
1881
1882setUpModule and tearDownModule
1883~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1884
1885These should be implemented as functions::
1886
1887 def setUpModule():
1888 createConnection()
1889
1890 def tearDownModule():
1891 closeConnection()
1892
1893If an exception is raised in a ``setUpModule`` then none of the tests in the
1894module will be run and the ``tearDownModule`` will not be run.
1895
1896
1897Signal Handling
1898---------------
1899
1900The -c / --catch command line option to unittest, along with the ``catchbreak``
1901parameter to :func:`unittest.main()`, provide more friendly handling of
1902control-c during a test run. With catch break behavior enabled control-c will
1903allow the currently running test to complete, and the test run will then end
1904and report all the results so far. A second control-c will raise a
1905``KeyboardInterrupt`` in the usual way.
1906
1907There are a few utility functions for framework authors to enable this
1908functionality within test frameworks.
1909
1910.. function:: installHandler()
1911
1912 Install the control-c handler. When a :const:`signal.SIGINT` is received
1913 (usually in response to the user pressing control-c) all registered results
1914 have :meth:`~TestResult.stop` called.
1915
1916.. function:: registerResult(result)
1917
1918 Register a :class:`TestResult` object for control-c handling. Registering a
1919 result stores a weak reference to it, so it doesn't prevent the result from
1920 being garbage collected.
1921
1922.. function:: removeResult(result)
1923
1924 Remove a registered result. Once a result has been removed then
1925 :meth:`~TestResult.stop` will no longer be called on that result object in
1926 response to a control-c.
1927