blob: f28e73fdb4f2b979a62a3d1cea3848aa023abcce [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
12.. versionadded:: 2.1
Benjamin Peterson692428e2009-03-23 21:50:21 +000013
Georg Brandl8ec7f652007-08-15 14:28:01 +000014The Python unit testing framework, sometimes referred to as "PyUnit," is a
15Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
16turn, a Java version of Kent's Smalltalk testing framework. Each is the de
17facto standard unit testing framework for its respective language.
18
19:mod:`unittest` supports test automation, sharing of setup and shutdown code for
20tests, aggregation of tests into collections, and independence of the tests from
21the reporting framework. The :mod:`unittest` module provides classes that make
22it easy to support these qualities for a set of tests.
23
24To achieve this, :mod:`unittest` supports some important concepts:
25
26test fixture
27 A :dfn:`test fixture` represents the preparation needed to perform one or more
28 tests, and any associate cleanup actions. This may involve, for example,
29 creating temporary or proxy databases, directories, or starting a server
30 process.
31
32test case
33 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
34 response to a particular set of inputs. :mod:`unittest` provides a base class,
35 :class:`TestCase`, which may be used to create new test cases.
36
37test suite
38 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
39 used to aggregate tests that should be executed together.
40
41test runner
42 A :dfn:`test runner` is a component which orchestrates the execution of tests
43 and provides the outcome to the user. The runner may use a graphical interface,
44 a textual interface, or return a special value to indicate the results of
45 executing the tests.
46
47The test case and test fixture concepts are supported through the
48:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
49used when creating new tests, and the latter can be used when integrating
50existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson99721e02009-03-23 23:10:14 +000051fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
52:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
53and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
54can be passed to the constructor for these purposes. When the test is run, the
55fixture initialization is run first; if it succeeds, the cleanup method is run
56after the test has been executed, regardless of the outcome of the test. Each
57instance of the :class:`TestCase` will only be used to run a single test method,
58so a new fixture is created for each test.
Georg Brandl8ec7f652007-08-15 14:28:01 +000059
60Test suites are implemented by the :class:`TestSuite` class. This class allows
61individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson176a56c2009-05-25 00:48:58 +000062all tests added directly to the suite and in "child" test suites are run.
Georg Brandl8ec7f652007-08-15 14:28:01 +000063
Benjamin Peterson99721e02009-03-23 23:10:14 +000064A test runner is an object that provides a single method,
65:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
66object as a parameter, and returns a result object. The class
67:class:`TestResult` is provided for use as the result object. :mod:`unittest`
68provides the :class:`TextTestRunner` as an example test runner which reports
69test results on the standard error stream by default. Alternate runners can be
70implemented for other environments (such as graphical environments) without any
71need to derive from a specific class.
Georg Brandl8ec7f652007-08-15 14:28:01 +000072
73
74.. seealso::
75
76 Module :mod:`doctest`
77 Another test-support module with a very different flavor.
78
Michael Foordba097ec2010-04-03 17:03:11 +000079 `unittest2: A backport of new unittest features for Python 2.4-2.6 <http://pypi.python.org/pypi/unittest2>`_
80 Many new features were added to unittest in Python 2.7, including test
81 discovery. unittest2 allows you to use these features with earlier
82 versions of Python.
83
Georg Brandld198b762009-05-31 14:15:25 +000084 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
Georg Brandl2fcd1732009-05-30 10:45:40 +000085 Kent Beck's original paper on testing frameworks using the pattern shared
86 by :mod:`unittest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000087
Georg Brandld198b762009-05-31 14:15:25 +000088 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Georg Brandl2fcd1732009-05-30 10:45:40 +000089 Third-party unittest frameworks with a lighter-weight syntax for writing
90 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger21b617b2009-03-24 00:17:11 +000091
Michael Foordba097ec2010-04-03 17:03:11 +000092 `The Python Testing Tools Taxonomy <http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy>`_
93 An extensive list of Python testing tools including functional testing
94 frameworks and mock object libraries.
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
Michael Foordba097ec2010-04-03 17:03:11 +000096 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
97 A special-interest-group for discussion of testing, and testing tools,
98 in Python.
Michael Foordb4a81c82009-05-29 20:33:46 +000099
Michael Foord5d31e052009-05-11 17:59:43 +0000100
Georg Brandl8ec7f652007-08-15 14:28:01 +0000101.. _unittest-minimal-example:
102
103Basic example
104-------------
105
106The :mod:`unittest` module provides a rich set of tools for constructing and
107running tests. This section demonstrates that a small subset of the tools
108suffice to meet the needs of most users.
109
110Here is a short script to test three functions from the :mod:`random` module::
111
112 import random
113 import unittest
114
115 class TestSequenceFunctions(unittest.TestCase):
116
117 def setUp(self):
118 self.seq = range(10)
119
Benjamin Peterson99721e02009-03-23 23:10:14 +0000120 def test_shuffle(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000121 # make sure the shuffled sequence does not lose any elements
122 random.shuffle(self.seq)
123 self.seq.sort()
124 self.assertEqual(self.seq, range(10))
125
Raymond Hettinger08090bf2010-03-09 08:44:18 +0000126 # should raise an exception for an immutable sequence
127 self.assertRaises(TypeError, random.shuffle, (1,2,3))
128
Benjamin Peterson99721e02009-03-23 23:10:14 +0000129 def test_choice(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000130 element = random.choice(self.seq)
Raymond Hettinger08090bf2010-03-09 08:44:18 +0000131 self.assertTrue(element in self.seq)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000132
Benjamin Peterson99721e02009-03-23 23:10:14 +0000133 def test_sample(self):
Raymond Hettinger08090bf2010-03-09 08:44:18 +0000134 with self.assertRaises(ValueError):
135 random.sample(self.seq, 20)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000136 for element in random.sample(self.seq, 5):
Raymond Hettinger08090bf2010-03-09 08:44:18 +0000137 self.assertTrue(element in self.seq)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000138
139 if __name__ == '__main__':
140 unittest.main()
141
Benjamin Peterson99721e02009-03-23 23:10:14 +0000142A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143individual tests are defined with methods whose names start with the letters
144``test``. This naming convention informs the test runner about which methods
145represent tests.
146
Benjamin Peterson99721e02009-03-23 23:10:14 +0000147The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foorddb43b5a2010-02-10 14:25:12 +0000148expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson99721e02009-03-23 23:10:14 +0000149:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
150These methods are used instead of the :keyword:`assert` statement so the test
151runner can accumulate all test results and produce a report.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152
Benjamin Peterson99721e02009-03-23 23:10:14 +0000153When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
154method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
155defined, the test runner will invoke that method after each test. In the
156example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
157test.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000158
159The final block shows a simple way to run the tests. :func:`unittest.main`
160provides a command line interface to the test script. When run from the command
161line, the above script produces an output that looks like this::
162
163 ...
164 ----------------------------------------------------------------------
165 Ran 3 tests in 0.000s
166
167 OK
168
169Instead of :func:`unittest.main`, there are other ways to run the tests with a
170finer level of control, less terse output, and no requirement to be run from the
171command line. For example, the last two lines may be replaced with::
172
173 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
174 unittest.TextTestRunner(verbosity=2).run(suite)
175
176Running the revised script from the interpreter or another script produces the
177following output::
178
Ezio Melotti68beef62010-02-28 03:11:07 +0000179 test_choice (__main__.TestSequenceFunctions) ... ok
180 test_sample (__main__.TestSequenceFunctions) ... ok
181 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
183 ----------------------------------------------------------------------
184 Ran 3 tests in 0.110s
185
186 OK
187
188The above examples show the most commonly used :mod:`unittest` features which
189are sufficient to meet many everyday testing needs. The remainder of the
190documentation explores the full feature set from first principles.
191
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000192
193.. _unittest-command-line-interface:
194
195Command Line Interface
196----------------------
197
198The unittest module can be used from the command line to run tests from
199modules, classes or even individual test methods::
200
201 python -m unittest test_module1 test_module2
202 python -m unittest test_module.TestClass
203 python -m unittest test_module.TestClass.test_method
204
205You can pass in a list with any combination of module names, and fully
206qualified class or method names.
207
208You can run tests with more detail (higher verbosity) by passing in the -v flag::
209
Ezio Melotti062d2b52009-12-19 22:41:49 +0000210 python -m unittest -v test_module
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000211
212For a list of all the command line options::
213
214 python -m unittest -h
215
216.. versionchanged:: 2.7
217 In earlier versions it was only possible to run individual test methods and
218 not modules or classes.
219
Michael Foordba097ec2010-04-03 17:03:11 +0000220
221failfast, catch and buffer command line options
222~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
223
224unittest supports three command options.
225
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000226* :option:`-b` / :option:`--buffer`
Michael Foordba097ec2010-04-03 17:03:11 +0000227
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000228 The standard output and standard error streams are buffered during the test
Michael Foordba097ec2010-04-03 17:03:11 +0000229 run. Output during a passing test is discarded. Output is echoed normally
230 on test fail or error and is added to the failure messages.
231
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000232* :option:`-c` / :option:`--catch`
233
234 Control-C during the test run waits for the current test to end and then
235 reports all the results so far. A second control-C raises the normal
236 :exc:`KeyboardInterrupt` exception.
237
238 See `Signal Handling`_ for the functions that provide this functionality.
239
240* :option:`-f` / :option:`--failfast`
241
242 Stop the test run on the first error or failure.
243
Michael Foordba097ec2010-04-03 17:03:11 +0000244.. versionadded:: 2.7
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000245 The command line options ``-c``, ``-b`` and ``-f`` were added.
Michael Foordba097ec2010-04-03 17:03:11 +0000246
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000247The command line can also be used for test discovery, for running all of the
248tests in a project or just a subset.
249
250
251.. _unittest-test-discovery:
252
253Test Discovery
254--------------
255
256.. versionadded:: 2.7
257
258Unittest supports simple test discovery. For a project's tests to be
259compatible with test discovery they must all be importable from the top level
260directory of the project (in other words, they must all be in Python packages).
261
262Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
263used from the command line. The basic command line usage is::
264
265 cd project_directory
266 python -m unittest discover
267
268The ``discover`` sub-command has the following options:
269
270 -v, --verbose Verbose output
271 -s directory Directory to start discovery ('.' default)
272 -p pattern Pattern to match test files ('test*.py' default)
273 -t directory Top level directory of project (default to
274 start directory)
275
Andrew M. Kuchling60383182010-04-30 01:32:47 +0000276The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
277as positional arguments in that order. The following two command lines
278are equivalent::
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000279
Ezio Melotti7b4e02c2010-01-27 20:25:11 +0000280 python -m unittest discover -s project_directory -p '*_test.py'
281 python -m unittest discover project_directory '*_test.py'
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000282
283Test modules and packages can customize test loading and discovery by through
284the `load_tests protocol`_.
285
286
Georg Brandl8ec7f652007-08-15 14:28:01 +0000287.. _organizing-tests:
288
289Organizing test code
290--------------------
291
292The basic building blocks of unit testing are :dfn:`test cases` --- single
293scenarios that must be set up and checked for correctness. In :mod:`unittest`,
294test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
295class. To make your own test cases you must write subclasses of
296:class:`TestCase`, or use :class:`FunctionTestCase`.
297
298An instance of a :class:`TestCase`\ -derived class is an object that can
299completely run a single test method, together with optional set-up and tidy-up
300code.
301
302The testing code of a :class:`TestCase` instance should be entirely self
303contained, such that it can be run either in isolation or in arbitrary
304combination with any number of other test cases.
305
Benjamin Peterson99721e02009-03-23 23:10:14 +0000306The simplest :class:`TestCase` subclass will simply override the
307:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000308
309 import unittest
310
311 class DefaultWidgetSizeTestCase(unittest.TestCase):
312 def runTest(self):
313 widget = Widget('The widget')
314 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
315
Gregory P. Smith28399852009-03-31 16:54:10 +0000316Note that in order to test something, we use the one of the :meth:`assert\*`
Georg Brandl2fcd1732009-05-30 10:45:40 +0000317methods provided by the :class:`TestCase` base class. If the test fails, an
318exception will be raised, and :mod:`unittest` will identify the test case as a
319:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
320helps you identify where the problem is: :dfn:`failures` are caused by incorrect
321results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
322code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000323
324The way to run a test case will be described later. For now, note that to
325construct an instance of such a test case, we call its constructor without
326arguments::
327
328 testCase = DefaultWidgetSizeTestCase()
329
330Now, such test cases can be numerous, and their set-up can be repetitive. In
331the above case, constructing a :class:`Widget` in each of 100 Widget test case
332subclasses would mean unsightly duplication.
333
334Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson99721e02009-03-23 23:10:14 +0000335:meth:`~TestCase.setUp`, which the testing framework will automatically call for
336us when we run the test::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000337
338 import unittest
339
340 class SimpleWidgetTestCase(unittest.TestCase):
341 def setUp(self):
342 self.widget = Widget('The widget')
343
344 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
345 def runTest(self):
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000346 self.assertEqual(self.widget.size(), (50,50),
347 'incorrect default size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000348
349 class WidgetResizeTestCase(SimpleWidgetTestCase):
350 def runTest(self):
351 self.widget.resize(100,150)
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000352 self.assertEqual(self.widget.size(), (100,150),
353 'wrong size after resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000354
Benjamin Peterson99721e02009-03-23 23:10:14 +0000355If the :meth:`~TestCase.setUp` method raises an exception while the test is
356running, the framework will consider the test to have suffered an error, and the
357:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000358
Benjamin Peterson99721e02009-03-23 23:10:14 +0000359Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
360after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000361
362 import unittest
363
364 class SimpleWidgetTestCase(unittest.TestCase):
365 def setUp(self):
366 self.widget = Widget('The widget')
367
368 def tearDown(self):
369 self.widget.dispose()
370 self.widget = None
371
Benjamin Peterson99721e02009-03-23 23:10:14 +0000372If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
373be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000374
375Such a working environment for the testing code is called a :dfn:`fixture`.
376
377Often, many small test cases will use the same fixture. In this case, we would
378end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
379classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
381mechanism::
382
383 import unittest
384
385 class WidgetTestCase(unittest.TestCase):
386 def setUp(self):
387 self.widget = Widget('The widget')
388
389 def tearDown(self):
390 self.widget.dispose()
391 self.widget = None
392
Ezio Melotti68beef62010-02-28 03:11:07 +0000393 def test_default_size(self):
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000394 self.assertEqual(self.widget.size(), (50,50),
395 'incorrect default size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000396
Ezio Melotti68beef62010-02-28 03:11:07 +0000397 def test_resize(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000398 self.widget.resize(100,150)
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000399 self.assertEqual(self.widget.size(), (100,150),
400 'wrong size after resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000401
Benjamin Peterson99721e02009-03-23 23:10:14 +0000402Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
403provided two different test methods. Class instances will now each run one of
Ezio Melotti68beef62010-02-28 03:11:07 +0000404the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson99721e02009-03-23 23:10:14 +0000405separately for each instance. When creating an instance we must specify the
406test method it is to run. We do this by passing the method name in the
407constructor::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000408
Ezio Melotti68beef62010-02-28 03:11:07 +0000409 defaultSizeTestCase = WidgetTestCase('test_default_size')
410 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000411
412Test case instances are grouped together according to the features they test.
413:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
414represented by :mod:`unittest`'s :class:`TestSuite` class::
415
416 widgetTestSuite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000417 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
418 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000419
420For the ease of running tests, as we will see later, it is a good idea to
421provide in each test module a callable object that returns a pre-built test
422suite::
423
424 def suite():
425 suite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000426 suite.addTest(WidgetTestCase('test_default_size'))
427 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000428 return suite
429
430or even::
431
432 def suite():
Ezio Melotti68beef62010-02-28 03:11:07 +0000433 tests = ['test_default_size', 'test_resize']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000434
435 return unittest.TestSuite(map(WidgetTestCase, tests))
436
437Since it is a common pattern to create a :class:`TestCase` subclass with many
438similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
439class that can be used to automate the process of creating a test suite and
440populating it with individual tests. For example, ::
441
442 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
443
Ezio Melotti68beef62010-02-28 03:11:07 +0000444will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
445``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl8ec7f652007-08-15 14:28:01 +0000446name prefix to identify test methods automatically.
447
448Note that the order in which the various test cases will be run is determined by
449sorting the test function names with the built-in :func:`cmp` function.
450
451Often it is desirable to group suites of test cases together, so as to run tests
452for the whole system at once. This is easy, since :class:`TestSuite` instances
453can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
454added to a :class:`TestSuite`::
455
456 suite1 = module1.TheTestSuite()
457 suite2 = module2.TheTestSuite()
458 alltests = unittest.TestSuite([suite1, suite2])
459
460You can place the definitions of test cases and test suites in the same modules
461as the code they are to test (such as :file:`widget.py`), but there are several
462advantages to placing the test code in a separate module, such as
463:file:`test_widget.py`:
464
465* The test module can be run standalone from the command line.
466
467* The test code can more easily be separated from shipped code.
468
469* There is less temptation to change test code to fit the code it tests without
470 a good reason.
471
472* Test code should be modified much less frequently than the code it tests.
473
474* Tested code can be refactored more easily.
475
476* Tests for modules written in C must be in separate modules anyway, so why not
477 be consistent?
478
479* If the testing strategy changes, there is no need to change the source code.
480
481
482.. _legacy-unit-tests:
483
484Re-using old test code
485----------------------
486
487Some users will find that they have existing test code that they would like to
488run from :mod:`unittest`, without converting every old test function to a
489:class:`TestCase` subclass.
490
491For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
492This subclass of :class:`TestCase` can be used to wrap an existing test
493function. Set-up and tear-down functions can also be provided.
494
495Given the following test function::
496
497 def testSomething():
498 something = makeSomething()
499 assert something.name is not None
500 # ...
501
502one can create an equivalent test case instance as follows::
503
504 testcase = unittest.FunctionTestCase(testSomething)
505
506If there are additional set-up and tear-down methods that should be called as
507part of the test case's operation, they can also be provided like so::
508
509 testcase = unittest.FunctionTestCase(testSomething,
510 setUp=makeSomethingDB,
511 tearDown=deleteSomethingDB)
512
513To make migrating existing test suites easier, :mod:`unittest` supports tests
514raising :exc:`AssertionError` to indicate test failure. However, it is
515recommended that you use the explicit :meth:`TestCase.fail\*` and
516:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
517may treat :exc:`AssertionError` differently.
518
519.. note::
520
Georg Brandl2fcd1732009-05-30 10:45:40 +0000521 Even though :class:`FunctionTestCase` can be used to quickly convert an
522 existing test base over to a :mod:`unittest`\ -based system, this approach is
523 not recommended. Taking the time to set up proper :class:`TestCase`
524 subclasses will make future test refactorings infinitely easier.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000525
Benjamin Peterson99721e02009-03-23 23:10:14 +0000526In some cases, the existing tests may have been written using the :mod:`doctest`
527module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
528automatically build :class:`unittest.TestSuite` instances from the existing
529:mod:`doctest`\ -based tests.
530
Georg Brandl8ec7f652007-08-15 14:28:01 +0000531
Benjamin Peterson692428e2009-03-23 21:50:21 +0000532.. _unittest-skipping:
533
534Skipping tests and expected failures
535------------------------------------
536
Michael Foordfb0844b2010-02-05 21:45:12 +0000537.. versionadded:: 2.7
538
Benjamin Peterson692428e2009-03-23 21:50:21 +0000539Unittest supports skipping individual test methods and even whole classes of
540tests. In addition, it supports marking a test as a "expected failure," a test
541that is broken and will fail, but shouldn't be counted as a failure on a
542:class:`TestResult`.
543
544Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
545or one of its conditional variants.
546
547Basic skipping looks like this: ::
548
549 class MyTestCase(unittest.TestCase):
550
551 @unittest.skip("demonstrating skipping")
552 def test_nothing(self):
553 self.fail("shouldn't happen")
554
Georg Brandl2fcd1732009-05-30 10:45:40 +0000555 @unittest.skipIf(mylib.__version__ < (1, 3),
556 "not supported in this library version")
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000557 def test_format(self):
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000558 # Tests that work for only a certain version of the library.
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000559 pass
560
561 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
562 def test_windows_support(self):
563 # windows specific testing code
564 pass
565
Benjamin Peterson692428e2009-03-23 21:50:21 +0000566This is the output of running the example above in verbose mode: ::
567
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000568 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000569 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000570 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000571
572 ----------------------------------------------------------------------
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000573 Ran 3 tests in 0.005s
574
575 OK (skipped=3)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000576
577Classes can be skipped just like methods: ::
578
579 @skip("showing class skipping")
580 class MySkippedTestCase(unittest.TestCase):
581 def test_not_run(self):
582 pass
583
Benjamin Peterson31b78062009-03-23 23:13:36 +0000584:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
585that needs to be set up is not available.
586
Benjamin Peterson692428e2009-03-23 21:50:21 +0000587Expected failures use the :func:`expectedFailure` decorator. ::
588
589 class ExpectedFailureTestCase(unittest.TestCase):
590 @unittest.expectedFailure
591 def test_fail(self):
592 self.assertEqual(1, 0, "broken")
593
594It's easy to roll your own skipping decorators by making a decorator that calls
595:func:`skip` on the test when it wants it to be skipped. This decorator skips
596the test unless the passed object has a certain attribute: ::
597
598 def skipUnlessHasattr(obj, attr):
599 if hasattr(obj, attr):
600 return lambda func: func
601 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
602
603The following decorators implement test skipping and expected failures:
604
605.. function:: skip(reason)
606
607 Unconditionally skip the decorated test. *reason* should describe why the
608 test is being skipped.
609
610.. function:: skipIf(condition, reason)
611
612 Skip the decorated test if *condition* is true.
613
614.. function:: skipUnless(condition, reason)
615
616 Skip the decoratored test unless *condition* is true.
617
618.. function:: expectedFailure
619
620 Mark the test as an expected failure. If the test fails when run, the test
621 is not counted as a failure.
622
Michael Foord09e29802010-04-04 22:41:54 +0000623Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
624Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
Michael Foordba097ec2010-04-03 17:03:11 +0000625
Benjamin Peterson692428e2009-03-23 21:50:21 +0000626
Georg Brandl8ec7f652007-08-15 14:28:01 +0000627.. _unittest-contents:
628
629Classes and functions
630---------------------
631
Benjamin Peterson99721e02009-03-23 23:10:14 +0000632This section describes in depth the API of :mod:`unittest`.
633
634
635.. _testcase-objects:
636
637Test cases
638~~~~~~~~~~
Georg Brandl8ec7f652007-08-15 14:28:01 +0000639
640.. class:: TestCase([methodName])
641
642 Instances of the :class:`TestCase` class represent the smallest testable units
643 in the :mod:`unittest` universe. This class is intended to be used as a base
644 class, with specific tests being implemented by concrete subclasses. This class
645 implements the interface needed by the test runner to allow it to drive the
646 test, and methods that the test code can use to check for and report various
647 kinds of failure.
648
649 Each instance of :class:`TestCase` will run a single test method: the method
650 named *methodName*. If you remember, we had an earlier example that went
651 something like this::
652
653 def suite():
654 suite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000655 suite.addTest(WidgetTestCase('test_default_size'))
656 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000657 return suite
658
659 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
660 single test.
661
Benjamin Peterson99721e02009-03-23 23:10:14 +0000662 *methodName* defaults to :meth:`runTest`.
663
664 :class:`TestCase` instances provide three groups of methods: one group used
665 to run the test, another used by the test implementation to check conditions
666 and report failures, and some inquiry methods allowing information about the
667 test itself to be gathered.
668
669 Methods in the first group (running the test) are:
670
671
672 .. method:: setUp()
673
674 Method called to prepare the test fixture. This is called immediately
675 before calling the test method; any exception raised by this method will
676 be considered an error rather than a test failure. The default
677 implementation does nothing.
678
679
680 .. method:: tearDown()
681
682 Method called immediately after the test method has been called and the
683 result recorded. This is called even if the test method raised an
684 exception, so the implementation in subclasses may need to be particularly
685 careful about checking internal state. Any exception raised by this
686 method will be considered an error rather than a test failure. This
687 method will only be called if the :meth:`setUp` succeeds, regardless of
688 the outcome of the test method. The default implementation does nothing.
689
690
Michael Foordba097ec2010-04-03 17:03:11 +0000691 .. method:: setUpClass()
692
693 A class method called before tests in an individual class run.
694 ``setUpClass`` is called with the class as the only argument
Michael Foord09e29802010-04-04 22:41:54 +0000695 and must be decorated as a :func:`classmethod`::
Michael Foordba097ec2010-04-03 17:03:11 +0000696
697 @classmethod
698 def setUpClass(cls):
699 ...
700
701 See `Class and Module Fixtures`_ for more details.
702
703 .. versionadded:: 2.7
704
705
706 .. method:: tearDownClass()
707
708 A class method called after tests in an individual class have run.
709 ``tearDownClass`` is called with the class as the only argument
710 and must be decorated as a :meth:`classmethod`::
711
712 @classmethod
713 def tearDownClass(cls):
714 ...
715
716 See `Class and Module Fixtures`_ for more details.
717
718 .. versionadded:: 2.7
719
720
Benjamin Peterson99721e02009-03-23 23:10:14 +0000721 .. method:: run([result])
722
723 Run the test, collecting the result into the test result object passed as
724 *result*. If *result* is omitted or :const:`None`, a temporary result
Ezio Melottic2f5a592009-06-30 22:51:06 +0000725 object is created (by calling the :meth:`defaultTestResult` method) and
726 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000727
728 The same effect may be had by simply calling the :class:`TestCase`
729 instance.
730
731
Benjamin Peterson47d97382009-03-26 20:05:50 +0000732 .. method:: skipTest(reason)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000733
Benjamin Peterson31b78062009-03-23 23:13:36 +0000734 Calling this during the a test method or :meth:`setUp` skips the current
735 test. See :ref:`unittest-skipping` for more information.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000736
Georg Brandl90aae552010-04-10 11:15:24 +0000737 .. versionadded:: 2.7
738
Benjamin Peterson99721e02009-03-23 23:10:14 +0000739
740 .. method:: debug()
741
742 Run the test without collecting the result. This allows exceptions raised
743 by the test to be propagated to the caller, and can be used to support
744 running tests under a debugger.
745
746 The test code can use any of the following methods to check for and report
747 failures.
748
749
Gregory P. Smith28399852009-03-31 16:54:10 +0000750 .. method:: assertTrue(expr[, msg])
751 assert_(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000752 failUnless(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000753
Georg Brandl64034bb2009-04-25 14:51:31 +0000754 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson99721e02009-03-23 23:10:14 +0000755 will be *msg* if given, otherwise it will be :const:`None`.
756
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000757 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000758 :meth:`failUnless`; use one of the ``assert`` variants.
Michael Foorddb43b5a2010-02-10 14:25:12 +0000759 :meth:`assert_`; use :meth:`assertTrue`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000760
Benjamin Peterson99721e02009-03-23 23:10:14 +0000761
762 .. method:: assertEqual(first, second[, msg])
763 failUnlessEqual(first, second[, msg])
764
765 Test that *first* and *second* are equal. If the values do not compare
766 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000767 :const:`None`. Note that using :meth:`assertEqual` improves upon
768 doing the comparison as the first parameter to :meth:`assertTrue`: the
769 default value for *msg* include representations of both *first* and
770 *second*.
771
772 In addition, if *first* and *second* are the exact same type and one of
Michael Foordfe6349c2010-02-08 22:41:16 +0000773 list, tuple, dict, set, frozenset or unicode or any type that a subclass
Michael Foord7b5aa462010-02-08 23:15:22 +0000774 registers with :meth:`addTypeEqualityFunc` the type specific equality
775 function will be called in order to generate a more useful default error
776 message.
Gregory P. Smith28399852009-03-31 16:54:10 +0000777
778 .. versionchanged:: 2.7
779 Added the automatic calling of type specific equality function.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000780
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000781 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000782 :meth:`failUnlessEqual`; use :meth:`assertEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000783
Benjamin Peterson99721e02009-03-23 23:10:14 +0000784
785 .. method:: assertNotEqual(first, second[, msg])
786 failIfEqual(first, second[, msg])
787
788 Test that *first* and *second* are not equal. If the values do compare
789 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000790 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
791 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson99721e02009-03-23 23:10:14 +0000792 default value for *msg* can be computed to include representations of both
793 *first* and *second*.
794
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000795 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000796 :meth:`failIfEqual`; use :meth:`assertNotEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000797
Benjamin Peterson99721e02009-03-23 23:10:14 +0000798
Michael Foordba097ec2010-04-03 17:03:11 +0000799 .. method:: assertAlmostEqual(first, second[, places[, msg[, delta]]])
Michael Foordefc2f492010-04-08 04:33:20 +0000800 failUnlessAlmostEqual(first, second[, places[, msg[, delta]]])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000801
802 Test that *first* and *second* are approximately equal by computing the
803 difference, rounding to the given number of decimal *places* (default 7),
804 and comparing to zero.
805
806 Note that comparing a given number of decimal places is not the same as
807 comparing a given number of significant digits. If the values do not
808 compare equal, the test will fail with the explanation given by *msg*, or
809 :const:`None`.
810
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000811 If *delta* is supplied instead of *places* then the difference
Michael Foordba097ec2010-04-03 17:03:11 +0000812 between *first* and *second* must be less than *delta*.
813
814 Supplying both *delta* and *places* raises a ``TypeError``.
815
Michael Foordc3f79372009-09-13 16:40:02 +0000816 .. versionchanged:: 2.7
817 Objects that compare equal are automatically almost equal.
Michael Foordba097ec2010-04-03 17:03:11 +0000818 Added the ``delta`` keyword argument.
Michael Foordc3f79372009-09-13 16:40:02 +0000819
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000820 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000821 :meth:`failUnlessAlmostEqual`; use :meth:`assertAlmostEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000822
Benjamin Peterson99721e02009-03-23 23:10:14 +0000823
Michael Foordba097ec2010-04-03 17:03:11 +0000824 .. method:: assertNotAlmostEqual(first, second[, places[, msg[, delta]]])
Michael Foordefc2f492010-04-08 04:33:20 +0000825 failIfAlmostEqual(first, second[, places[, msg[, delta]]])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000826
827 Test that *first* and *second* are not approximately equal by computing
828 the difference, rounding to the given number of decimal *places* (default
829 7), and comparing to zero.
830
831 Note that comparing a given number of decimal places is not the same as
832 comparing a given number of significant digits. If the values do not
833 compare equal, the test will fail with the explanation given by *msg*, or
834 :const:`None`.
835
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000836 If *delta* is supplied instead of *places* then the difference
Michael Foordba097ec2010-04-03 17:03:11 +0000837 between *first* and *second* must be more than *delta*.
838
839 Supplying both *delta* and *places* raises a ``TypeError``.
840
Michael Foordc3f79372009-09-13 16:40:02 +0000841 .. versionchanged:: 2.7
842 Objects that compare equal automatically fail.
Michael Foordba097ec2010-04-03 17:03:11 +0000843 Added the ``delta`` keyword argument.
Michael Foordc3f79372009-09-13 16:40:02 +0000844
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000845 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000846 :meth:`failIfAlmostEqual`; use :meth:`assertNotAlmostEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000847
Benjamin Peterson99721e02009-03-23 23:10:14 +0000848
Gregory P. Smith28399852009-03-31 16:54:10 +0000849 .. method:: assertGreater(first, second, msg=None)
850 assertGreaterEqual(first, second, msg=None)
851 assertLess(first, second, msg=None)
852 assertLessEqual(first, second, msg=None)
853
854 Test that *first* is respectively >, >=, < or <= than *second* depending
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000855 on the method name. If not, the test will fail with an explanation
Gregory P. Smith28399852009-03-31 16:54:10 +0000856 or with the explanation given by *msg*::
857
858 >>> self.assertGreaterEqual(3, 4)
859 AssertionError: "3" unexpectedly not greater than or equal to "4"
860
861 .. versionadded:: 2.7
862
863
864 .. method:: assertMultiLineEqual(self, first, second, msg=None)
865
866 Test that the multiline string *first* is equal to the string *second*.
867 When not equal a diff of the two strings highlighting the differences
Michael Foordfe6349c2010-02-08 22:41:16 +0000868 will be included in the error message. This method is used by default
869 when comparing Unicode strings with :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000870
Michael Foord98e7b762010-03-20 03:00:34 +0000871 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000872
873 .. versionadded:: 2.7
874
875
Ezio Melotti5afe42b2010-01-16 19:36:42 +0000876 .. method:: assertRegexpMatches(text, regexp, msg=None)
Gregory P. Smith28399852009-03-31 16:54:10 +0000877
878 Verifies that a *regexp* search matches *text*. Fails with an error
879 message including the pattern and the *text*. *regexp* may be
880 a regular expression object or a string containing a regular expression
881 suitable for use by :func:`re.search`.
882
883 .. versionadded:: 2.7
884
885
Michael Foordba097ec2010-04-03 17:03:11 +0000886 .. method:: assertNotRegexpMatches(text, regexp, msg=None)
887
888 Verifies that a *regexp* search does not match *text*. Fails with an error
889 message including the pattern and the *text*. *regexp* may be
890 a regular expression object or a string containing a regular expression
891 suitable for use by :func:`re.search`.
892
893 .. versionadded:: 2.7
894
895
Gregory P. Smith28399852009-03-31 16:54:10 +0000896 .. method:: assertIn(first, second, msg=None)
897 assertNotIn(first, second, msg=None)
898
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000899 Tests that *first* is or is not in *second* with an explanatory error
Gregory P. Smith28399852009-03-31 16:54:10 +0000900 message as appropriate.
901
Michael Foord98e7b762010-03-20 03:00:34 +0000902 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000903
904 .. versionadded:: 2.7
905
906
Michael Foord98e7b762010-03-20 03:00:34 +0000907 .. method:: assertItemsEqual(actual, expected, msg=None)
Gregory P. Smith28399852009-03-31 16:54:10 +0000908
Michael Foorde70c72c2010-01-31 19:59:26 +0000909 Test that sequence *expected* contains the same elements as *actual*,
Michael Foord98e7b762010-03-20 03:00:34 +0000910 regardless of their order. When they don't, an error message listing the
911 differences between the sequences will be generated.
Gregory P. Smith28399852009-03-31 16:54:10 +0000912
Michael Foord98e7b762010-03-20 03:00:34 +0000913 Duplicate elements are *not* ignored when comparing *actual* and
914 *expected*. It verifies if each element has the same count in both
915 sequences. It is the equivalent of ``assertEqual(sorted(expected),
916 sorted(actual))`` but it works with sequences of unhashable objects as
917 well.
Michael Foord1c430012010-02-05 20:52:14 +0000918
Michael Foord98e7b762010-03-20 03:00:34 +0000919 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000920
921 .. versionadded:: 2.7
922
923
924 .. method:: assertSetEqual(set1, set2, msg=None)
925
926 Tests that two sets are equal. If not, an error message is constructed
Michael Foordfe6349c2010-02-08 22:41:16 +0000927 that lists the differences between the sets. This method is used by
928 default when comparing sets or frozensets with :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000929
930 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
931 method.
932
Michael Foord98e7b762010-03-20 03:00:34 +0000933 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000934
935 .. versionadded:: 2.7
936
937
938 .. method:: assertDictEqual(expected, actual, msg=None)
939
940 Test that two dictionaries are equal. If not, an error message is
Michael Foordfe6349c2010-02-08 22:41:16 +0000941 constructed that shows the differences in the dictionaries. This
942 method will be used by default to compare dictionaries in
943 calls to :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000944
Michael Foord98e7b762010-03-20 03:00:34 +0000945 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000946
947 .. versionadded:: 2.7
948
949
950 .. method:: assertDictContainsSubset(expected, actual, msg=None)
951
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000952 Tests whether the key/value pairs in dictionary *actual* are a
Gregory P. Smith28399852009-03-31 16:54:10 +0000953 superset of those in *expected*. If not, an error message listing
954 the missing keys and mismatched values is generated.
955
Michael Foord98e7b762010-03-20 03:00:34 +0000956 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000957
958 .. versionadded:: 2.7
959
960
961 .. method:: assertListEqual(list1, list2, msg=None)
962 assertTupleEqual(tuple1, tuple2, msg=None)
963
964 Tests that two lists or tuples are equal. If not an error message is
965 constructed that shows only the differences between the two. An error
966 is also raised if either of the parameters are of the wrong type.
Michael Foordfe6349c2010-02-08 22:41:16 +0000967 These methods are used by default when comparing lists or tuples with
968 :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000969
Michael Foord98e7b762010-03-20 03:00:34 +0000970 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000971
972 .. versionadded:: 2.7
973
974
975 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
976
977 Tests that two sequences are equal. If a *seq_type* is supplied, both
978 *seq1* and *seq2* must be instances of *seq_type* or a failure will
979 be raised. If the sequences are different an error message is
980 constructed that shows the difference between the two.
981
Michael Foord98e7b762010-03-20 03:00:34 +0000982 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000983
984 This method is used to implement :meth:`assertListEqual` and
985 :meth:`assertTupleEqual`.
986
987 .. versionadded:: 2.7
988
989
Benjamin Peterson99721e02009-03-23 23:10:14 +0000990 .. method:: assertRaises(exception[, callable, ...])
991 failUnlessRaises(exception[, callable, ...])
992
993 Test that an exception is raised when *callable* is called with any
994 positional or keyword arguments that are also passed to
995 :meth:`assertRaises`. The test passes if *exception* is raised, is an
996 error if another exception is raised, or fails if no exception is raised.
997 To catch any of a group of exceptions, a tuple containing the exception
998 classes may be passed as *exception*.
999
Benjamin Peterson7233acc2009-03-29 03:31:40 +00001000 If *callable* is omitted or None, returns a context manager so that the
1001 code under test can be written inline rather than as a function::
1002
Michael Foord1f3fa8a2010-02-05 21:07:38 +00001003 with self.assertRaises(SomeException):
Benjamin Peterson7233acc2009-03-29 03:31:40 +00001004 do_something()
1005
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00001006 The context manager will store the caught exception object in its
Georg Brandldc3694b2010-02-07 17:02:22 +00001007 :attr:`exception` attribute. This can be useful if the intention
Michael Foord1f3fa8a2010-02-05 21:07:38 +00001008 is to perform additional checks on the exception raised::
1009
1010 with self.assertRaises(SomeException) as cm:
1011 do_something()
1012
Georg Brandldc3694b2010-02-07 17:02:22 +00001013 the_exception = cm.exception
Michael Foordba7732e2010-02-05 23:28:12 +00001014 self.assertEqual(the_exception.error_code, 3)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00001015
Benjamin Peterson99721e02009-03-23 23:10:14 +00001016 .. versionchanged:: 2.7
Benjamin Peterson7233acc2009-03-29 03:31:40 +00001017 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001018
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001019 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +00001020 :meth:`failUnlessRaises`; use :meth:`assertRaises`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001021
Benjamin Peterson99721e02009-03-23 23:10:14 +00001022
Gregory P. Smith28399852009-03-31 16:54:10 +00001023 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
Benjamin Peterson99721e02009-03-23 23:10:14 +00001024
Gregory P. Smith28399852009-03-31 16:54:10 +00001025 Like :meth:`assertRaises` but also tests that *regexp* matches
1026 on the string representation of the raised exception. *regexp* may be
1027 a regular expression object or a string containing a regular expression
1028 suitable for use by :func:`re.search`. Examples::
1029
1030 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
1031 int, 'XYZ')
1032
1033 or::
1034
1035 with self.assertRaisesRegexp(ValueError, 'literal'):
1036 int('XYZ')
1037
1038 .. versionadded:: 2.7
1039
1040
1041 .. method:: assertIsNone(expr[, msg])
1042
1043 This signals a test failure if *expr* is not None.
1044
1045 .. versionadded:: 2.7
1046
1047
1048 .. method:: assertIsNotNone(expr[, msg])
1049
1050 The inverse of the :meth:`assertIsNone` method.
1051 This signals a test failure if *expr* is None.
1052
1053 .. versionadded:: 2.7
1054
1055
Michael Foordf2dfef12009-04-05 19:19:28 +00001056 .. method:: assertIs(expr1, expr2[, msg])
1057
1058 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
1059 object.
1060
1061 .. versionadded:: 2.7
1062
1063
1064 .. method:: assertIsNot(expr1, expr2[, msg])
1065
1066 The inverse of the :meth:`assertIs` method.
1067 This signals a test failure if *expr1* and *expr2* evaluate to the same
1068 object.
1069
1070 .. versionadded:: 2.7
1071
1072
Georg Brandlf895cf52009-10-01 20:59:31 +00001073 .. method:: assertIsInstance(obj, cls[, msg])
1074
1075 This signals a test failure if *obj* is not an instance of *cls* (which
1076 can be a class or a tuple of classes, as supported by :func:`isinstance`).
1077
1078 .. versionadded:: 2.7
1079
1080
1081 .. method:: assertNotIsInstance(obj, cls[, msg])
1082
1083 The inverse of the :meth:`assertIsInstance` method. This signals a test
1084 failure if *obj* is an instance of *cls*.
1085
1086 .. versionadded:: 2.7
1087
1088
Gregory P. Smith28399852009-03-31 16:54:10 +00001089 .. method:: assertFalse(expr[, msg])
1090 failIf(expr[, msg])
1091
1092 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001093 This signals a test failure if *expr* is true, with *msg* or :const:`None`
1094 for the error message.
1095
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001096 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +00001097 :meth:`failIf`; use :meth:`assertFalse`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001098
Benjamin Peterson99721e02009-03-23 23:10:14 +00001099
1100 .. method:: fail([msg])
1101
1102 Signals a test failure unconditionally, with *msg* or :const:`None` for
1103 the error message.
1104
1105
1106 .. attribute:: failureException
1107
1108 This class attribute gives the exception raised by the test method. If a
1109 test framework needs to use a specialized exception, possibly to carry
1110 additional information, it must subclass this exception in order to "play
1111 fair" with the framework. The initial value of this attribute is
1112 :exc:`AssertionError`.
1113
Michael Foord345b2fe2009-04-02 03:20:38 +00001114
1115 .. attribute:: longMessage
1116
1117 If set to True then any explicit failure message you pass in to the
1118 assert methods will be appended to the end of the normal failure message.
1119 The normal messages contain useful information about the objects involved,
1120 for example the message from assertEqual shows you the repr of the two
1121 unequal objects. Setting this attribute to True allows you to have a
1122 custom error message in addition to the normal one.
1123
1124 This attribute defaults to False, meaning that a custom message passed
1125 to an assert method will silence the normal message.
1126
1127 The class setting can be overridden in individual tests by assigning an
1128 instance attribute to True or False before calling the assert methods.
1129
1130 .. versionadded:: 2.7
1131
1132
Benjamin Peterson99721e02009-03-23 23:10:14 +00001133 Testing frameworks can use the following methods to collect information on
1134 the test:
1135
1136
1137 .. method:: countTestCases()
1138
1139 Return the number of tests represented by this test object. For
1140 :class:`TestCase` instances, this will always be ``1``.
1141
1142
1143 .. method:: defaultTestResult()
1144
1145 Return an instance of the test result class that should be used for this
1146 test case class (if no other result instance is provided to the
1147 :meth:`run` method).
1148
1149 For :class:`TestCase` instances, this will always be an instance of
1150 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1151 as necessary.
1152
1153
1154 .. method:: id()
1155
1156 Return a string identifying the specific test case. This is usually the
1157 full name of the test method, including the module and class name.
1158
1159
1160 .. method:: shortDescription()
1161
Gregory P. Smith28399852009-03-31 16:54:10 +00001162 Returns a description of the test, or :const:`None` if no description
1163 has been provided. The default implementation of this method
1164 returns the first line of the test method's docstring, if available,
Michael Foorddb43b5a2010-02-10 14:25:12 +00001165 or :const:`None`.
Gregory P. Smith28399852009-03-31 16:54:10 +00001166
1167
1168 .. method:: addTypeEqualityFunc(typeobj, function)
1169
1170 Registers a type specific :meth:`assertEqual` equality checking
1171 function to be called by :meth:`assertEqual` when both objects it has
1172 been asked to compare are exactly *typeobj* (not subclasses).
1173 *function* must take two positional arguments and a third msg=None
1174 keyword argument just as :meth:`assertEqual` does. It must raise
Andrew M. Kuchling59631852009-04-09 11:23:36 +00001175 ``self.failureException`` when inequality between the first two
Gregory P. Smith28399852009-03-31 16:54:10 +00001176 parameters is detected.
1177
1178 One good use of custom equality checking functions for a type
Andrew M. Kuchling59631852009-04-09 11:23:36 +00001179 is to raise ``self.failureException`` with an error message useful
1180 for debugging the problem by explaining the inequalities in detail.
Gregory P. Smith28399852009-03-31 16:54:10 +00001181
1182 .. versionadded:: 2.7
Georg Brandl8ec7f652007-08-15 14:28:01 +00001183
1184
Michael Foorde2fb98f2009-05-02 20:15:05 +00001185 .. method:: addCleanup(function[, *args[, **kwargs]])
1186
1187 Add a function to be called after :meth:`tearDown` to cleanup resources
1188 used during the test. Functions will be called in reverse order to the
1189 order they are added (LIFO). They are called with any arguments and
1190 keyword arguments passed into :meth:`addCleanup` when they are
1191 added.
1192
1193 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1194 then any cleanup functions added will still be called.
1195
1196 .. versionadded:: 2.7
1197
1198
1199 .. method:: doCleanups()
1200
Barry Warsawfa900d42010-04-12 14:40:49 +00001201 This method is called unconditionally after :meth:`tearDown`, or
Michael Foorde2fb98f2009-05-02 20:15:05 +00001202 after :meth:`setUp` if :meth:`setUp` raises an exception.
1203
1204 It is responsible for calling all the cleanup functions added by
1205 :meth:`addCleanup`. If you need cleanup functions to be called
1206 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1207 yourself.
1208
1209 :meth:`doCleanups` pops methods off the stack of cleanup
1210 functions one at a time, so it can be called at any time.
1211
1212 .. versionadded:: 2.7
1213
1214
Georg Brandl8ec7f652007-08-15 14:28:01 +00001215.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
1216
1217 This class implements the portion of the :class:`TestCase` interface which
Georg Brandl2fcd1732009-05-30 10:45:40 +00001218 allows the test runner to drive the test, but does not provide the methods
1219 which test code can use to check and report errors. This is used to create
1220 test cases using legacy test code, allowing it to be integrated into a
1221 :mod:`unittest`-based test framework.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001222
1223
Benjamin Peterson99721e02009-03-23 23:10:14 +00001224.. _testsuite-objects:
1225
1226Grouping tests
1227~~~~~~~~~~~~~~
1228
Georg Brandl8ec7f652007-08-15 14:28:01 +00001229.. class:: TestSuite([tests])
1230
1231 This class represents an aggregation of individual tests cases and test suites.
1232 The class presents the interface needed by the test runner to allow it to be run
1233 as any other test case. Running a :class:`TestSuite` instance is the same as
1234 iterating over the suite, running each test individually.
1235
1236 If *tests* is given, it must be an iterable of individual test cases or other
1237 test suites that will be used to build the suite initially. Additional methods
1238 are provided to add test cases and suites to the collection later on.
1239
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001240 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1241 they do not actually implement a test. Instead, they are used to aggregate
1242 tests into groups of tests that should be run together. Some additional
1243 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson99721e02009-03-23 23:10:14 +00001244
1245
1246 .. method:: TestSuite.addTest(test)
1247
1248 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1249
1250
1251 .. method:: TestSuite.addTests(tests)
1252
1253 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1254 instances to this test suite.
1255
Georg Brandl2fcd1732009-05-30 10:45:40 +00001256 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1257 each element.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001258
1259 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1260
1261
1262 .. method:: run(result)
1263
1264 Run the tests associated with this suite, collecting the result into the
1265 test result object passed as *result*. Note that unlike
1266 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1267 be passed in.
1268
1269
1270 .. method:: debug()
1271
1272 Run the tests associated with this suite without collecting the
1273 result. This allows exceptions raised by the test to be propagated to the
1274 caller and can be used to support running tests under a debugger.
1275
1276
1277 .. method:: countTestCases()
1278
1279 Return the number of tests represented by this test object, including all
1280 individual tests and sub-suites.
1281
Georg Brandl9bc66822009-04-27 17:04:23 +00001282
1283 .. method:: __iter__()
1284
1285 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1286 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1287 that this method maybe called several times on a single suite
1288 (for example when counting tests or comparing for equality)
1289 so the tests returned must be the same for repeated iterations.
1290
1291 .. versionchanged:: 2.7
1292 In earlier versions the :class:`TestSuite` accessed tests directly rather
1293 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1294 for providing tests.
1295
Benjamin Peterson99721e02009-03-23 23:10:14 +00001296 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1297 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1298
1299
Benjamin Peterson99721e02009-03-23 23:10:14 +00001300Loading and running tests
1301~~~~~~~~~~~~~~~~~~~~~~~~~
1302
Georg Brandl8ec7f652007-08-15 14:28:01 +00001303.. class:: TestLoader()
1304
Benjamin Peterson99721e02009-03-23 23:10:14 +00001305 The :class:`TestLoader` class is used to create test suites from classes and
1306 modules. Normally, there is no need to create an instance of this class; the
1307 :mod:`unittest` module provides an instance that can be shared as
1308 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1309 customization of some configurable properties.
1310
1311 :class:`TestLoader` objects have the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001312
1313
Benjamin Peterson99721e02009-03-23 23:10:14 +00001314 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001315
Benjamin Peterson99721e02009-03-23 23:10:14 +00001316 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1317 :class:`testCaseClass`.
1318
1319
1320 .. method:: loadTestsFromModule(module)
1321
1322 Return a suite of all tests cases contained in the given module. This
1323 method searches *module* for classes derived from :class:`TestCase` and
1324 creates an instance of the class for each test method defined for the
1325 class.
1326
Georg Brandl16a57f62009-04-27 15:29:09 +00001327 .. note::
Benjamin Peterson99721e02009-03-23 23:10:14 +00001328
1329 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1330 convenient in sharing fixtures and helper functions, defining test
1331 methods on base classes that are not intended to be instantiated
1332 directly does not play well with this method. Doing so, however, can
1333 be useful when the fixtures are different and defined in subclasses.
1334
Michael Foordb4a81c82009-05-29 20:33:46 +00001335 If a module provides a ``load_tests`` function it will be called to
1336 load the tests. This allows modules to customize test loading.
1337 This is the `load_tests protocol`_.
1338
1339 .. versionchanged:: 2.7
1340 Support for ``load_tests`` added.
1341
Benjamin Peterson99721e02009-03-23 23:10:14 +00001342
1343 .. method:: loadTestsFromName(name[, module])
1344
1345 Return a suite of all tests cases given a string specifier.
1346
1347 The specifier *name* is a "dotted name" that may resolve either to a
1348 module, a test case class, a test method within a test case class, a
1349 :class:`TestSuite` instance, or a callable object which returns a
1350 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1351 applied in the order listed here; that is, a method on a possible test
1352 case class will be picked up as "a test method within a test case class",
1353 rather than "a callable object".
1354
1355 For example, if you have a module :mod:`SampleTests` containing a
Georg Brandl2fcd1732009-05-30 10:45:40 +00001356 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1357 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1358 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1359 return a suite which will run all three test methods. Using the specifier
1360 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1361 suite which will run only the :meth:`test_two` test method. The specifier
1362 can refer to modules and packages which have not been imported; they will
1363 be imported as a side-effect.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001364
1365 The method optionally resolves *name* relative to the given *module*.
1366
1367
1368 .. method:: loadTestsFromNames(names[, module])
1369
1370 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1371 than a single name. The return value is a test suite which supports all
1372 the tests defined for each name.
1373
1374
1375 .. method:: getTestCaseNames(testCaseClass)
1376
1377 Return a sorted sequence of method names found within *testCaseClass*;
1378 this should be a subclass of :class:`TestCase`.
1379
Michael Foordb4a81c82009-05-29 20:33:46 +00001380
1381 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1382
1383 Find and return all test modules from the specified start directory,
1384 recursing into subdirectories to find them. Only test files that match
Michael Foorde91ea562009-09-13 19:07:03 +00001385 *pattern* will be loaded. (Using shell style pattern matching.) Only
1386 module names that are importable (i.e. are valid Python identifiers) will
1387 be loaded.
Michael Foordb4a81c82009-05-29 20:33:46 +00001388
1389 All test modules must be importable from the top level of the project. If
1390 the start directory is not the top level directory then the top level
1391 directory must be specified separately.
1392
Michael Foorde91ea562009-09-13 19:07:03 +00001393 If importing a module fails, for example due to a syntax error, then this
1394 will be recorded as a single error and discovery will continue.
1395
Michael Foordb4a81c82009-05-29 20:33:46 +00001396 If a test package name (directory with :file:`__init__.py`) matches the
1397 pattern then the package will be checked for a ``load_tests``
1398 function. If this exists then it will be called with *loader*, *tests*,
1399 *pattern*.
1400
Michael Foorddc0460a2009-09-13 19:08:18 +00001401 If load_tests exists then discovery does *not* recurse into the package,
Michael Foordb4a81c82009-05-29 20:33:46 +00001402 ``load_tests`` is responsible for loading all tests in the package.
1403
1404 The pattern is deliberately not stored as a loader attribute so that
1405 packages can continue discovery themselves. *top_level_dir* is stored so
1406 ``load_tests`` does not need to pass this argument in to
1407 ``loader.discover()``.
1408
Michael Foordba097ec2010-04-03 17:03:11 +00001409 *start_dir* can be a dotted module name as well as a directory.
1410
Michael Foord17565e52009-09-27 20:08:23 +00001411 .. versionadded:: 2.7
Michael Foordb4a81c82009-05-29 20:33:46 +00001412
Benjamin Peterson99721e02009-03-23 23:10:14 +00001413 The following attributes of a :class:`TestLoader` can be configured either by
1414 subclassing or assignment on an instance:
1415
1416
1417 .. attribute:: testMethodPrefix
1418
1419 String giving the prefix of method names which will be interpreted as test
1420 methods. The default value is ``'test'``.
1421
1422 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1423 methods.
1424
1425
1426 .. attribute:: sortTestMethodsUsing
1427
1428 Function to be used to compare method names when sorting them in
1429 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
1430 default value is the built-in :func:`cmp` function; the attribute can also
1431 be set to :const:`None` to disable the sort.
1432
1433
1434 .. attribute:: suiteClass
1435
1436 Callable object that constructs a test suite from a list of tests. No
1437 methods on the resulting object are needed. The default value is the
1438 :class:`TestSuite` class.
1439
1440 This affects all the :meth:`loadTestsFrom\*` methods.
1441
1442
Benjamin Peterson99721e02009-03-23 23:10:14 +00001443.. class:: TestResult
1444
1445 This class is used to compile information about which tests have succeeded
1446 and which have failed.
1447
1448 A :class:`TestResult` object stores the results of a set of tests. The
1449 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1450 properly recorded; test authors do not need to worry about recording the
1451 outcome of tests.
1452
1453 Testing frameworks built on top of :mod:`unittest` may want access to the
1454 :class:`TestResult` object generated by running a set of tests for reporting
1455 purposes; a :class:`TestResult` instance is returned by the
1456 :meth:`TestRunner.run` method for this purpose.
1457
1458 :class:`TestResult` instances have the following attributes that will be of
1459 interest when inspecting the results of running a set of tests:
1460
1461
1462 .. attribute:: errors
1463
1464 A list containing 2-tuples of :class:`TestCase` instances and strings
1465 holding formatted tracebacks. Each tuple represents a test which raised an
1466 unexpected exception.
1467
1468 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001469 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1470
1471
1472 .. attribute:: failures
1473
1474 A list containing 2-tuples of :class:`TestCase` instances and strings
1475 holding formatted tracebacks. Each tuple represents a test where a failure
1476 was explicitly signalled using the :meth:`TestCase.fail\*` or
1477 :meth:`TestCase.assert\*` methods.
1478
1479 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001480 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1481
1482 .. attribute:: skipped
1483
1484 A list containing 2-tuples of :class:`TestCase` instances and strings
1485 holding the reason for skipping the test.
1486
1487 .. versionadded:: 2.7
1488
1489 .. attribute:: expectedFailures
1490
1491 A list contaning 2-tuples of :class:`TestCase` instances and strings
1492 holding formatted tracebacks. Each tuple represents a expected failures
1493 of the test case.
1494
1495 .. attribute:: unexpectedSuccesses
1496
1497 A list containing :class:`TestCase` instances that were marked as expected
1498 failures, but succeeded.
1499
1500 .. attribute:: shouldStop
1501
1502 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1503
1504
1505 .. attribute:: testsRun
1506
1507 The total number of tests run so far.
1508
1509
Michael Foordba097ec2010-04-03 17:03:11 +00001510 .. attribute:: buffer
1511
1512 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1513 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1514 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1515 fails or errors. Any output is also attached to the failure / error message.
1516
1517 .. versionadded:: 2.7
1518
1519
1520 .. attribute:: failfast
1521
1522 If set to true :meth:`stop` will be called on the first failure or error,
1523 halting the test run.
1524
1525 .. versionadded:: 2.7
1526
1527
Benjamin Peterson99721e02009-03-23 23:10:14 +00001528 .. method:: wasSuccessful()
1529
1530 Return :const:`True` if all tests run so far have passed, otherwise returns
1531 :const:`False`.
1532
1533
1534 .. method:: stop()
1535
1536 This method can be called to signal that the set of tests being run should
1537 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1538 :class:`TestRunner` objects should respect this flag and return without
1539 running any additional tests.
1540
1541 For example, this feature is used by the :class:`TextTestRunner` class to
1542 stop the test framework when the user signals an interrupt from the
1543 keyboard. Interactive tools which provide :class:`TestRunner`
1544 implementations can use this in a similar manner.
1545
1546 The following methods of the :class:`TestResult` class are used to maintain
1547 the internal data structures, and may be extended in subclasses to support
1548 additional reporting requirements. This is particularly useful in building
1549 tools which support interactive reporting while tests are being run.
1550
1551
1552 .. method:: startTest(test)
1553
1554 Called when the test case *test* is about to be run.
1555
Benjamin Peterson99721e02009-03-23 23:10:14 +00001556 .. method:: stopTest(test)
1557
1558 Called after the test case *test* has been executed, regardless of the
1559 outcome.
1560
Michael Foord07ef4872009-05-02 22:43:34 +00001561 .. method:: startTestRun(test)
1562
1563 Called once before any tests are executed.
1564
1565 .. versionadded:: 2.7
1566
1567
1568 .. method:: stopTestRun(test)
1569
Ezio Melotti7b4e02c2010-01-27 20:25:11 +00001570 Called once after all tests are executed.
Michael Foord07ef4872009-05-02 22:43:34 +00001571
1572 .. versionadded:: 2.7
1573
1574
Benjamin Peterson99721e02009-03-23 23:10:14 +00001575 .. method:: addError(test, err)
1576
1577 Called when the test case *test* raises an unexpected exception *err* is a
1578 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1579 traceback)``.
1580
1581 The default implementation appends a tuple ``(test, formatted_err)`` to
1582 the instance's :attr:`errors` attribute, where *formatted_err* is a
1583 formatted traceback derived from *err*.
1584
1585
1586 .. method:: addFailure(test, err)
1587
Michael Foordb4a81c82009-05-29 20:33:46 +00001588 Called when the test case *test* signals a failure. *err* is a tuple of
1589 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001590
1591 The default implementation appends a tuple ``(test, formatted_err)`` to
1592 the instance's :attr:`failures` attribute, where *formatted_err* is a
1593 formatted traceback derived from *err*.
1594
1595
1596 .. method:: addSuccess(test)
1597
1598 Called when the test case *test* succeeds.
1599
1600 The default implementation does nothing.
1601
1602
1603 .. method:: addSkip(test, reason)
1604
1605 Called when the test case *test* is skipped. *reason* is the reason the
1606 test gave for skipping.
1607
1608 The default implementation appends a tuple ``(test, reason)`` to the
1609 instance's :attr:`skipped` attribute.
1610
1611
1612 .. method:: addExpectedFailure(test, err)
1613
1614 Called when the test case *test* fails, but was marked with the
1615 :func:`expectedFailure` decorator.
1616
1617 The default implementation appends a tuple ``(test, formatted_err)`` to
1618 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1619 is a formatted traceback derived from *err*.
1620
1621
1622 .. method:: addUnexpectedSuccess(test)
1623
1624 Called when the test case *test* was marked with the
1625 :func:`expectedFailure` decorator, but succeeded.
1626
1627 The default implementation appends the test to the instance's
1628 :attr:`unexpectedSuccesses` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001629
Michael Foorddb43b5a2010-02-10 14:25:12 +00001630.. class:: TextTestResult(stream, descriptions, verbosity)
1631
1632 A concrete implementation of :class:`TestResult` used by the
1633 :class:`TextTestRunner`.
1634
1635 .. versionadded:: 2.7
1636 This class was previously named ``_TextTestResult``. The old name still
1637 exists as an alias but is deprecated.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001638
1639.. data:: defaultTestLoader
1640
1641 Instance of the :class:`TestLoader` class intended to be shared. If no
1642 customization of the :class:`TestLoader` is needed, this instance can be used
1643 instead of repeatedly creating new instances.
1644
1645
Michael Foorddb43b5a2010-02-10 14:25:12 +00001646.. class:: TextTestRunner([stream[, descriptions[, verbosity], [resultclass]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001647
1648 A basic test runner implementation which prints results on standard error. It
1649 has a few configurable parameters, but is essentially very simple. Graphical
1650 applications which run test suites should provide alternate implementations.
1651
Georg Brandl9bc66822009-04-27 17:04:23 +00001652 .. method:: _makeResult()
1653
1654 This method returns the instance of ``TestResult`` used by :meth:`run`.
1655 It is not intended to be called directly, but can be overridden in
1656 subclasses to provide a custom ``TestResult``.
1657
Michael Foorddb43b5a2010-02-10 14:25:12 +00001658 ``_makeResult()`` instantiates the class or callable passed in the
1659 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Michael Foordefc2f492010-04-08 04:33:20 +00001660 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foorddb43b5a2010-02-10 14:25:12 +00001661 The result class is instantiated with the following arguments::
1662
1663 stream, descriptions, verbosity
1664
Georg Brandl8ec7f652007-08-15 14:28:01 +00001665
Michael Foordddb20df2010-04-04 23:28:44 +00001666.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit[, verbosity[, failfast[, catchbreak[,buffer]]]]]]]]]])
Michael Foord55430352010-04-05 00:39:50 +00001667
Georg Brandl8ec7f652007-08-15 14:28:01 +00001668 A command-line program that runs a set of tests; this is primarily for making
1669 test modules conveniently executable. The simplest use for this function is to
1670 include the following line at the end of a test script::
1671
1672 if __name__ == '__main__':
1673 unittest.main()
1674
Michael Foord5d31e052009-05-11 17:59:43 +00001675 You can run tests with more detailed information by passing in the verbosity
1676 argument::
1677
1678 if __name__ == '__main__':
1679 unittest.main(verbosity=2)
1680
Georg Brandl8ec7f652007-08-15 14:28:01 +00001681 The *testRunner* argument can either be a test runner class or an already
Michael Foord829f6b82009-05-02 11:43:06 +00001682 created instance of it. By default ``main`` calls :func:`sys.exit` with
1683 an exit code indicating success or failure of the tests run.
1684
1685 ``main`` supports being used from the interactive interpreter by passing in the
1686 argument ``exit=False``. This displays the result on standard output without
1687 calling :func:`sys.exit`::
1688
1689 >>> from unittest import main
1690 >>> main(module='test_module', exit=False)
1691
Michael Foordddb20df2010-04-04 23:28:44 +00001692 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
1693 effect as the `failfast, catch and buffer command line options`_.
1694
Michael Foord829f6b82009-05-02 11:43:06 +00001695 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1696 This stores the result of the tests run as the ``result`` attribute.
1697
1698 .. versionchanged:: 2.7
Michael Foordddb20df2010-04-04 23:28:44 +00001699 The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
1700 parameters were added.
Michael Foordb4a81c82009-05-29 20:33:46 +00001701
1702
1703load_tests Protocol
1704###################
1705
Michael Foord17565e52009-09-27 20:08:23 +00001706
1707.. versionadded:: 2.7
1708
1709
Michael Foordb4a81c82009-05-29 20:33:46 +00001710Modules or packages can customize how tests are loaded from them during normal
1711test runs or test discovery by implementing a function called ``load_tests``.
1712
1713If a test module defines ``load_tests`` it will be called by
1714:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1715
1716 load_tests(loader, standard_tests, None)
1717
1718It should return a :class:`TestSuite`.
1719
1720*loader* is the instance of :class:`TestLoader` doing the loading.
1721*standard_tests* are the tests that would be loaded by default from the
1722module. It is common for test modules to only want to add or remove tests
1723from the standard set of tests.
1724The third argument is used when loading packages as part of test discovery.
1725
1726A typical ``load_tests`` function that loads tests from a specific set of
1727:class:`TestCase` classes may look like::
1728
1729 test_cases = (TestCase1, TestCase2, TestCase3)
1730
1731 def load_tests(loader, tests, pattern):
1732 suite = TestSuite()
1733 for test_class in test_cases:
1734 tests = loader.loadTestsFromTestCase(test_class)
1735 suite.addTests(tests)
1736 return suite
1737
1738If discovery is started, either from the command line or by calling
1739:meth:`TestLoader.discover`, with a pattern that matches a package
1740name then the package :file:`__init__.py` will be checked for ``load_tests``.
1741
1742.. note::
1743
Ezio Melotti062d2b52009-12-19 22:41:49 +00001744 The default pattern is 'test*.py'. This matches all Python files
Michael Foordb4a81c82009-05-29 20:33:46 +00001745 that start with 'test' but *won't* match any test directories.
1746
1747 A pattern like 'test*' will match test packages as well as
1748 modules.
1749
1750If the package :file:`__init__.py` defines ``load_tests`` then it will be
1751called and discovery not continued into the package. ``load_tests``
1752is called with the following arguments::
1753
1754 load_tests(loader, standard_tests, pattern)
1755
1756This should return a :class:`TestSuite` representing all the tests
1757from the package. (``standard_tests`` will only contain tests
1758collected from :file:`__init__.py`.)
1759
1760Because the pattern is passed into ``load_tests`` the package is free to
1761continue (and potentially modify) test discovery. A 'do nothing'
1762``load_tests`` function for a test package would look like::
1763
1764 def load_tests(loader, standard_tests, pattern):
1765 # top level directory cached on loader instance
1766 this_dir = os.path.dirname(__file__)
1767 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1768 standard_tests.addTests(package_tests)
1769 return standard_tests
Michael Foordba097ec2010-04-03 17:03:11 +00001770
1771
1772Class and Module Fixtures
1773-------------------------
1774
Michael Foord09e29802010-04-04 22:41:54 +00001775Class and module level fixtures are implemented in :class:`TestSuite`. When
1776the test suite encounters a test from a new class then :meth:`tearDownClass`
1777from the previous class (if there is one) is called, followed by
1778:meth:`setUpClass` from the new class.
Michael Foordba097ec2010-04-03 17:03:11 +00001779
Michael Foord09e29802010-04-04 22:41:54 +00001780Similarly if a test is from a different module from the previous test then
1781``tearDownModule`` from the previous module is run, followed by
1782``setUpModule`` from the new module.
Michael Foordba097ec2010-04-03 17:03:11 +00001783
Michael Foord09e29802010-04-04 22:41:54 +00001784After all the tests have run the final ``tearDownClass`` and
1785``tearDownModule`` are run.
Michael Foordba097ec2010-04-03 17:03:11 +00001786
Michael Foord09e29802010-04-04 22:41:54 +00001787Note that shared fixtures do not play well with [potential] features like test
1788parallelization and they break test isolation. They should be used with care.
Michael Foordba097ec2010-04-03 17:03:11 +00001789
Michael Foord09e29802010-04-04 22:41:54 +00001790The default ordering of tests created by the unittest test loaders is to group
1791all tests from the same modules and classes together. This will lead to
1792``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
1793module. If you randomize the order, so that tests from different modules and
1794classes are adjacent to each other, then these shared fixture functions may be
1795called multiple times in a single test run.
Michael Foordba097ec2010-04-03 17:03:11 +00001796
Michael Foord09e29802010-04-04 22:41:54 +00001797Shared fixtures are not intended to work with suites with non-standard
1798ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
1799support shared fixtures.
Michael Foordba097ec2010-04-03 17:03:11 +00001800
Michael Foord09e29802010-04-04 22:41:54 +00001801If there are any exceptions raised during one of the shared fixture functions
1802the test is reported as an error. Because there is no corresponding test
1803instance an ``_ErrorHolder`` object (that has the same interface as a
1804:class:`TestCase`) is created to represent the error. If you are just using
1805the standard unittest test runner then this detail doesn't matter, but if you
1806are a framework author it may be relevant.
Michael Foordba097ec2010-04-03 17:03:11 +00001807
1808
1809setUpClass and tearDownClass
1810~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1811
1812These must be implemented as class methods::
1813
1814 import unittest
1815
1816 class Test(unittest.TestCase):
1817 @classmethod
1818 def setUpClass(cls):
1819 cls._connection = createExpensiveConnectionObject()
1820
1821 @classmethod
1822 def tearDownClass(cls):
1823 cls._connection.destroy()
1824
Michael Foord09e29802010-04-04 22:41:54 +00001825If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
1826then you must call up to them yourself. The implementations in
1827:class:`TestCase` are empty.
Michael Foordba097ec2010-04-03 17:03:11 +00001828
Michael Foord09e29802010-04-04 22:41:54 +00001829If an exception is raised during a ``setUpClass`` then the tests in the class
1830are not run and the ``tearDownClass`` is not run. Skipped classes will not
1831have ``setUpClass`` or ``tearDownClass`` run.
Michael Foordba097ec2010-04-03 17:03:11 +00001832
1833
1834setUpModule and tearDownModule
1835~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1836
1837These should be implemented as functions::
1838
1839 def setUpModule():
1840 createConnection()
1841
1842 def tearDownModule():
1843 closeConnection()
1844
Michael Foord09e29802010-04-04 22:41:54 +00001845If an exception is raised in a ``setUpModule`` then none of the tests in the
1846module will be run and the ``tearDownModule`` will not be run.
Michael Foordba097ec2010-04-03 17:03:11 +00001847
1848
Michael Foord55430352010-04-05 00:39:50 +00001849Signal Handling
1850---------------
1851
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +00001852The :option:`-c`/:option:`--catch` command line option to unittest, along with the ``catchbreak``
Michael Foord55430352010-04-05 00:39:50 +00001853parameter to :func:`unittest.main()`, provide more friendly handling of
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +00001854control-C during a test run. With catch break behavior enabled control-C will
Michael Foord55430352010-04-05 00:39:50 +00001855allow the currently running test to complete, and the test run will then end
1856and report all the results so far. A second control-c will raise a
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +00001857:exc:`KeyboardInterrupt` in the usual way.
Michael Foord55430352010-04-05 00:39:50 +00001858
Michael Foord5c322ec2010-04-25 19:02:46 +00001859The control-c handling signal handler attempts to remain compatible with code or
1860tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
1861handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
1862i.e. it has been replaced by the system under test and delegated to, then it
1863calls the default handler. This will normally be the expected behavior by code
1864that replaces an installed handler and delegates to it. For individual tests
1865that need ``unittest`` control-c handling disabled the :func:`removeHandler`
1866decorator can be used.
1867
1868There are a few utility functions for framework authors to enable control-c
1869handling functionality within test frameworks.
Michael Foord55430352010-04-05 00:39:50 +00001870
1871.. function:: installHandler()
1872
Michael Foord31655032010-04-05 10:26:26 +00001873 Install the control-c handler. When a :const:`signal.SIGINT` is received
1874 (usually in response to the user pressing control-c) all registered results
Michael Foord55430352010-04-05 00:39:50 +00001875 have :meth:`~TestResult.stop` called.
1876
Michael Foord47b54402010-04-26 23:36:47 +00001877 .. versionadded:: 2.7
1878
Michael Foord55430352010-04-05 00:39:50 +00001879.. function:: registerResult(result)
1880
Michael Foord31655032010-04-05 10:26:26 +00001881 Register a :class:`TestResult` object for control-c handling. Registering a
Michael Foord55430352010-04-05 00:39:50 +00001882 result stores a weak reference to it, so it doesn't prevent the result from
1883 being garbage collected.
1884
Michael Foord5c322ec2010-04-25 19:02:46 +00001885 Registering a :class:`TestResult` object has no side-effects if control-c
1886 handling is not enabled, so test frameworks can unconditionally register
1887 all results they create independently of whether or not handling is enabled.
1888
Michael Foord47b54402010-04-26 23:36:47 +00001889 .. versionadded:: 2.7
1890
Michael Foord55430352010-04-05 00:39:50 +00001891.. function:: removeResult(result)
1892
Michael Foord31655032010-04-05 10:26:26 +00001893 Remove a registered result. Once a result has been removed then
Michael Foordd341ec82010-04-05 10:30:14 +00001894 :meth:`~TestResult.stop` will no longer be called on that result object in
Michael Foord31655032010-04-05 10:26:26 +00001895 response to a control-c.
Michael Foord55430352010-04-05 00:39:50 +00001896
Michael Foord47b54402010-04-26 23:36:47 +00001897 .. versionadded:: 2.7
1898
Michael Foord5c322ec2010-04-25 19:02:46 +00001899.. function:: removeHandler(function=None)
1900
1901 When called without arguments this function removes the control-c handler
1902 if it has been installed. This function can also be used as a test decorator
1903 to temporarily remove the handler whilst the test is being executed::
1904
1905 @unittest.removeHandler
1906 def test_signal_handling(self):
1907 ...
1908
Michael Foord47b54402010-04-26 23:36:47 +00001909 .. versionadded:: 2.7
1910