blob: f28f4f0dbf87926fc0948094a8c4f3b4995694bd [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
226* -f / --failfast
227
228 Stop the test run on the first error or failure.
229
230* -c / --catch
231
Michael Foord31655032010-04-05 10:26:26 +0000232 Control-c during the test run waits for the current test to end and then
233 reports all the results so far. A second control-c raises the normal
Michael Foordba097ec2010-04-03 17:03:11 +0000234 ``KeyboardInterrupt`` exception.
235
Michael Foord55430352010-04-05 00:39:50 +0000236 See `Signal Handling`_ for the functions that provide this functionality.
237
Michael Foordba097ec2010-04-03 17:03:11 +0000238* -b / --buffer
239
240 The standard out and standard error streams are buffered during the test
241 run. Output during a passing test is discarded. Output is echoed normally
242 on test fail or error and is added to the failure messages.
243
244.. versionadded:: 2.7
245 The command line options ``-c``, ``-b`` and ``-f`` where added.
246
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
276The -s, -p, & -t options can be passsed in as positional arguments. The
277following two command lines are equivalent::
278
Ezio Melotti7b4e02c2010-01-27 20:25:11 +0000279 python -m unittest discover -s project_directory -p '*_test.py'
280 python -m unittest discover project_directory '*_test.py'
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000281
282Test modules and packages can customize test loading and discovery by through
283the `load_tests protocol`_.
284
285
Georg Brandl8ec7f652007-08-15 14:28:01 +0000286.. _organizing-tests:
287
288Organizing test code
289--------------------
290
291The basic building blocks of unit testing are :dfn:`test cases` --- single
292scenarios that must be set up and checked for correctness. In :mod:`unittest`,
293test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
294class. To make your own test cases you must write subclasses of
295:class:`TestCase`, or use :class:`FunctionTestCase`.
296
297An instance of a :class:`TestCase`\ -derived class is an object that can
298completely run a single test method, together with optional set-up and tidy-up
299code.
300
301The testing code of a :class:`TestCase` instance should be entirely self
302contained, such that it can be run either in isolation or in arbitrary
303combination with any number of other test cases.
304
Benjamin Peterson99721e02009-03-23 23:10:14 +0000305The simplest :class:`TestCase` subclass will simply override the
306:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307
308 import unittest
309
310 class DefaultWidgetSizeTestCase(unittest.TestCase):
311 def runTest(self):
312 widget = Widget('The widget')
313 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
314
Gregory P. Smith28399852009-03-31 16:54:10 +0000315Note that in order to test something, we use the one of the :meth:`assert\*`
Georg Brandl2fcd1732009-05-30 10:45:40 +0000316methods provided by the :class:`TestCase` base class. If the test fails, an
317exception will be raised, and :mod:`unittest` will identify the test case as a
318:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
319helps you identify where the problem is: :dfn:`failures` are caused by incorrect
320results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
321code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000322
323The way to run a test case will be described later. For now, note that to
324construct an instance of such a test case, we call its constructor without
325arguments::
326
327 testCase = DefaultWidgetSizeTestCase()
328
329Now, such test cases can be numerous, and their set-up can be repetitive. In
330the above case, constructing a :class:`Widget` in each of 100 Widget test case
331subclasses would mean unsightly duplication.
332
333Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson99721e02009-03-23 23:10:14 +0000334:meth:`~TestCase.setUp`, which the testing framework will automatically call for
335us when we run the test::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336
337 import unittest
338
339 class SimpleWidgetTestCase(unittest.TestCase):
340 def setUp(self):
341 self.widget = Widget('The widget')
342
343 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
344 def runTest(self):
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000345 self.assertEqual(self.widget.size(), (50,50),
346 'incorrect default size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000347
348 class WidgetResizeTestCase(SimpleWidgetTestCase):
349 def runTest(self):
350 self.widget.resize(100,150)
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000351 self.assertEqual(self.widget.size(), (100,150),
352 'wrong size after resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000353
Benjamin Peterson99721e02009-03-23 23:10:14 +0000354If the :meth:`~TestCase.setUp` method raises an exception while the test is
355running, the framework will consider the test to have suffered an error, and the
356:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000357
Benjamin Peterson99721e02009-03-23 23:10:14 +0000358Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
359after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000360
361 import unittest
362
363 class SimpleWidgetTestCase(unittest.TestCase):
364 def setUp(self):
365 self.widget = Widget('The widget')
366
367 def tearDown(self):
368 self.widget.dispose()
369 self.widget = None
370
Benjamin Peterson99721e02009-03-23 23:10:14 +0000371If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
372be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000373
374Such a working environment for the testing code is called a :dfn:`fixture`.
375
376Often, many small test cases will use the same fixture. In this case, we would
377end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
378classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000379discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
380mechanism::
381
382 import unittest
383
384 class WidgetTestCase(unittest.TestCase):
385 def setUp(self):
386 self.widget = Widget('The widget')
387
388 def tearDown(self):
389 self.widget.dispose()
390 self.widget = None
391
Ezio Melotti68beef62010-02-28 03:11:07 +0000392 def test_default_size(self):
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000393 self.assertEqual(self.widget.size(), (50,50),
394 'incorrect default size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000395
Ezio Melotti68beef62010-02-28 03:11:07 +0000396 def test_resize(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000397 self.widget.resize(100,150)
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000398 self.assertEqual(self.widget.size(), (100,150),
399 'wrong size after resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000400
Benjamin Peterson99721e02009-03-23 23:10:14 +0000401Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
402provided two different test methods. Class instances will now each run one of
Ezio Melotti68beef62010-02-28 03:11:07 +0000403the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson99721e02009-03-23 23:10:14 +0000404separately for each instance. When creating an instance we must specify the
405test method it is to run. We do this by passing the method name in the
406constructor::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000407
Ezio Melotti68beef62010-02-28 03:11:07 +0000408 defaultSizeTestCase = WidgetTestCase('test_default_size')
409 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000410
411Test case instances are grouped together according to the features they test.
412:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
413represented by :mod:`unittest`'s :class:`TestSuite` class::
414
415 widgetTestSuite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000416 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
417 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000418
419For the ease of running tests, as we will see later, it is a good idea to
420provide in each test module a callable object that returns a pre-built test
421suite::
422
423 def suite():
424 suite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000425 suite.addTest(WidgetTestCase('test_default_size'))
426 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000427 return suite
428
429or even::
430
431 def suite():
Ezio Melotti68beef62010-02-28 03:11:07 +0000432 tests = ['test_default_size', 'test_resize']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000433
434 return unittest.TestSuite(map(WidgetTestCase, tests))
435
436Since it is a common pattern to create a :class:`TestCase` subclass with many
437similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
438class that can be used to automate the process of creating a test suite and
439populating it with individual tests. For example, ::
440
441 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
442
Ezio Melotti68beef62010-02-28 03:11:07 +0000443will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
444``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl8ec7f652007-08-15 14:28:01 +0000445name prefix to identify test methods automatically.
446
447Note that the order in which the various test cases will be run is determined by
448sorting the test function names with the built-in :func:`cmp` function.
449
450Often it is desirable to group suites of test cases together, so as to run tests
451for the whole system at once. This is easy, since :class:`TestSuite` instances
452can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
453added to a :class:`TestSuite`::
454
455 suite1 = module1.TheTestSuite()
456 suite2 = module2.TheTestSuite()
457 alltests = unittest.TestSuite([suite1, suite2])
458
459You can place the definitions of test cases and test suites in the same modules
460as the code they are to test (such as :file:`widget.py`), but there are several
461advantages to placing the test code in a separate module, such as
462:file:`test_widget.py`:
463
464* The test module can be run standalone from the command line.
465
466* The test code can more easily be separated from shipped code.
467
468* There is less temptation to change test code to fit the code it tests without
469 a good reason.
470
471* Test code should be modified much less frequently than the code it tests.
472
473* Tested code can be refactored more easily.
474
475* Tests for modules written in C must be in separate modules anyway, so why not
476 be consistent?
477
478* If the testing strategy changes, there is no need to change the source code.
479
480
481.. _legacy-unit-tests:
482
483Re-using old test code
484----------------------
485
486Some users will find that they have existing test code that they would like to
487run from :mod:`unittest`, without converting every old test function to a
488:class:`TestCase` subclass.
489
490For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
491This subclass of :class:`TestCase` can be used to wrap an existing test
492function. Set-up and tear-down functions can also be provided.
493
494Given the following test function::
495
496 def testSomething():
497 something = makeSomething()
498 assert something.name is not None
499 # ...
500
501one can create an equivalent test case instance as follows::
502
503 testcase = unittest.FunctionTestCase(testSomething)
504
505If there are additional set-up and tear-down methods that should be called as
506part of the test case's operation, they can also be provided like so::
507
508 testcase = unittest.FunctionTestCase(testSomething,
509 setUp=makeSomethingDB,
510 tearDown=deleteSomethingDB)
511
512To make migrating existing test suites easier, :mod:`unittest` supports tests
513raising :exc:`AssertionError` to indicate test failure. However, it is
514recommended that you use the explicit :meth:`TestCase.fail\*` and
515:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
516may treat :exc:`AssertionError` differently.
517
518.. note::
519
Georg Brandl2fcd1732009-05-30 10:45:40 +0000520 Even though :class:`FunctionTestCase` can be used to quickly convert an
521 existing test base over to a :mod:`unittest`\ -based system, this approach is
522 not recommended. Taking the time to set up proper :class:`TestCase`
523 subclasses will make future test refactorings infinitely easier.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000524
Benjamin Peterson99721e02009-03-23 23:10:14 +0000525In some cases, the existing tests may have been written using the :mod:`doctest`
526module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
527automatically build :class:`unittest.TestSuite` instances from the existing
528:mod:`doctest`\ -based tests.
529
Georg Brandl8ec7f652007-08-15 14:28:01 +0000530
Benjamin Peterson692428e2009-03-23 21:50:21 +0000531.. _unittest-skipping:
532
533Skipping tests and expected failures
534------------------------------------
535
Michael Foordfb0844b2010-02-05 21:45:12 +0000536.. versionadded:: 2.7
537
Benjamin Peterson692428e2009-03-23 21:50:21 +0000538Unittest supports skipping individual test methods and even whole classes of
539tests. In addition, it supports marking a test as a "expected failure," a test
540that is broken and will fail, but shouldn't be counted as a failure on a
541:class:`TestResult`.
542
543Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
544or one of its conditional variants.
545
546Basic skipping looks like this: ::
547
548 class MyTestCase(unittest.TestCase):
549
550 @unittest.skip("demonstrating skipping")
551 def test_nothing(self):
552 self.fail("shouldn't happen")
553
Georg Brandl2fcd1732009-05-30 10:45:40 +0000554 @unittest.skipIf(mylib.__version__ < (1, 3),
555 "not supported in this library version")
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000556 def test_format(self):
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000557 # Tests that work for only a certain version of the library.
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000558 pass
559
560 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
561 def test_windows_support(self):
562 # windows specific testing code
563 pass
564
Benjamin Peterson692428e2009-03-23 21:50:21 +0000565This is the output of running the example above in verbose mode: ::
566
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000567 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000568 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000569 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000570
571 ----------------------------------------------------------------------
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000572 Ran 3 tests in 0.005s
573
574 OK (skipped=3)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000575
576Classes can be skipped just like methods: ::
577
578 @skip("showing class skipping")
579 class MySkippedTestCase(unittest.TestCase):
580 def test_not_run(self):
581 pass
582
Benjamin Peterson31b78062009-03-23 23:13:36 +0000583:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
584that needs to be set up is not available.
585
Benjamin Peterson692428e2009-03-23 21:50:21 +0000586Expected failures use the :func:`expectedFailure` decorator. ::
587
588 class ExpectedFailureTestCase(unittest.TestCase):
589 @unittest.expectedFailure
590 def test_fail(self):
591 self.assertEqual(1, 0, "broken")
592
593It's easy to roll your own skipping decorators by making a decorator that calls
594:func:`skip` on the test when it wants it to be skipped. This decorator skips
595the test unless the passed object has a certain attribute: ::
596
597 def skipUnlessHasattr(obj, attr):
598 if hasattr(obj, attr):
599 return lambda func: func
600 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
601
602The following decorators implement test skipping and expected failures:
603
604.. function:: skip(reason)
605
606 Unconditionally skip the decorated test. *reason* should describe why the
607 test is being skipped.
608
609.. function:: skipIf(condition, reason)
610
611 Skip the decorated test if *condition* is true.
612
613.. function:: skipUnless(condition, reason)
614
615 Skip the decoratored test unless *condition* is true.
616
617.. function:: expectedFailure
618
619 Mark the test as an expected failure. If the test fails when run, the test
620 is not counted as a failure.
621
Michael Foord09e29802010-04-04 22:41:54 +0000622Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
623Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
Michael Foordba097ec2010-04-03 17:03:11 +0000624
Benjamin Peterson692428e2009-03-23 21:50:21 +0000625
Georg Brandl8ec7f652007-08-15 14:28:01 +0000626.. _unittest-contents:
627
628Classes and functions
629---------------------
630
Benjamin Peterson99721e02009-03-23 23:10:14 +0000631This section describes in depth the API of :mod:`unittest`.
632
633
634.. _testcase-objects:
635
636Test cases
637~~~~~~~~~~
Georg Brandl8ec7f652007-08-15 14:28:01 +0000638
639.. class:: TestCase([methodName])
640
641 Instances of the :class:`TestCase` class represent the smallest testable units
642 in the :mod:`unittest` universe. This class is intended to be used as a base
643 class, with specific tests being implemented by concrete subclasses. This class
644 implements the interface needed by the test runner to allow it to drive the
645 test, and methods that the test code can use to check for and report various
646 kinds of failure.
647
648 Each instance of :class:`TestCase` will run a single test method: the method
649 named *methodName*. If you remember, we had an earlier example that went
650 something like this::
651
652 def suite():
653 suite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000654 suite.addTest(WidgetTestCase('test_default_size'))
655 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000656 return suite
657
658 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
659 single test.
660
Benjamin Peterson99721e02009-03-23 23:10:14 +0000661 *methodName* defaults to :meth:`runTest`.
662
663 :class:`TestCase` instances provide three groups of methods: one group used
664 to run the test, another used by the test implementation to check conditions
665 and report failures, and some inquiry methods allowing information about the
666 test itself to be gathered.
667
668 Methods in the first group (running the test) are:
669
670
671 .. method:: setUp()
672
673 Method called to prepare the test fixture. This is called immediately
674 before calling the test method; any exception raised by this method will
675 be considered an error rather than a test failure. The default
676 implementation does nothing.
677
678
679 .. method:: tearDown()
680
681 Method called immediately after the test method has been called and the
682 result recorded. This is called even if the test method raised an
683 exception, so the implementation in subclasses may need to be particularly
684 careful about checking internal state. Any exception raised by this
685 method will be considered an error rather than a test failure. This
686 method will only be called if the :meth:`setUp` succeeds, regardless of
687 the outcome of the test method. The default implementation does nothing.
688
689
Michael Foordba097ec2010-04-03 17:03:11 +0000690 .. method:: setUpClass()
691
692 A class method called before tests in an individual class run.
693 ``setUpClass`` is called with the class as the only argument
Michael Foord09e29802010-04-04 22:41:54 +0000694 and must be decorated as a :func:`classmethod`::
Michael Foordba097ec2010-04-03 17:03:11 +0000695
696 @classmethod
697 def setUpClass(cls):
698 ...
699
700 See `Class and Module Fixtures`_ for more details.
701
702 .. versionadded:: 2.7
703
704
705 .. method:: tearDownClass()
706
707 A class method called after tests in an individual class have run.
708 ``tearDownClass`` is called with the class as the only argument
709 and must be decorated as a :meth:`classmethod`::
710
711 @classmethod
712 def tearDownClass(cls):
713 ...
714
715 See `Class and Module Fixtures`_ for more details.
716
717 .. versionadded:: 2.7
718
719
Benjamin Peterson99721e02009-03-23 23:10:14 +0000720 .. method:: run([result])
721
722 Run the test, collecting the result into the test result object passed as
723 *result*. If *result* is omitted or :const:`None`, a temporary result
Ezio Melottic2f5a592009-06-30 22:51:06 +0000724 object is created (by calling the :meth:`defaultTestResult` method) and
725 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000726
727 The same effect may be had by simply calling the :class:`TestCase`
728 instance.
729
730
Benjamin Peterson47d97382009-03-26 20:05:50 +0000731 .. method:: skipTest(reason)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000732
Benjamin Peterson31b78062009-03-23 23:13:36 +0000733 Calling this during the a test method or :meth:`setUp` skips the current
734 test. See :ref:`unittest-skipping` for more information.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000735
Georg Brandl90aae552010-04-10 11:15:24 +0000736 .. versionadded:: 2.7
737
Benjamin Peterson99721e02009-03-23 23:10:14 +0000738
739 .. method:: debug()
740
741 Run the test without collecting the result. This allows exceptions raised
742 by the test to be propagated to the caller, and can be used to support
743 running tests under a debugger.
744
745 The test code can use any of the following methods to check for and report
746 failures.
747
748
Gregory P. Smith28399852009-03-31 16:54:10 +0000749 .. method:: assertTrue(expr[, msg])
750 assert_(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000751 failUnless(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000752
Georg Brandl64034bb2009-04-25 14:51:31 +0000753 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson99721e02009-03-23 23:10:14 +0000754 will be *msg* if given, otherwise it will be :const:`None`.
755
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000756 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000757 :meth:`failUnless`; use one of the ``assert`` variants.
Michael Foorddb43b5a2010-02-10 14:25:12 +0000758 :meth:`assert_`; use :meth:`assertTrue`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000759
Benjamin Peterson99721e02009-03-23 23:10:14 +0000760
761 .. method:: assertEqual(first, second[, msg])
762 failUnlessEqual(first, second[, msg])
763
764 Test that *first* and *second* are equal. If the values do not compare
765 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000766 :const:`None`. Note that using :meth:`assertEqual` improves upon
767 doing the comparison as the first parameter to :meth:`assertTrue`: the
768 default value for *msg* include representations of both *first* and
769 *second*.
770
771 In addition, if *first* and *second* are the exact same type and one of
Michael Foordfe6349c2010-02-08 22:41:16 +0000772 list, tuple, dict, set, frozenset or unicode or any type that a subclass
Michael Foord7b5aa462010-02-08 23:15:22 +0000773 registers with :meth:`addTypeEqualityFunc` the type specific equality
774 function will be called in order to generate a more useful default error
775 message.
Gregory P. Smith28399852009-03-31 16:54:10 +0000776
777 .. versionchanged:: 2.7
778 Added the automatic calling of type specific equality function.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000779
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000780 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000781 :meth:`failUnlessEqual`; use :meth:`assertEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000782
Benjamin Peterson99721e02009-03-23 23:10:14 +0000783
784 .. method:: assertNotEqual(first, second[, msg])
785 failIfEqual(first, second[, msg])
786
787 Test that *first* and *second* are not equal. If the values do compare
788 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000789 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
790 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson99721e02009-03-23 23:10:14 +0000791 default value for *msg* can be computed to include representations of both
792 *first* and *second*.
793
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000794 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000795 :meth:`failIfEqual`; use :meth:`assertNotEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000796
Benjamin Peterson99721e02009-03-23 23:10:14 +0000797
Michael Foordba097ec2010-04-03 17:03:11 +0000798 .. method:: assertAlmostEqual(first, second[, places[, msg[, delta]]])
Michael Foordefc2f492010-04-08 04:33:20 +0000799 failUnlessAlmostEqual(first, second[, places[, msg[, delta]]])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000800
801 Test that *first* and *second* are approximately equal by computing the
802 difference, rounding to the given number of decimal *places* (default 7),
803 and comparing to zero.
804
805 Note that comparing a given number of decimal places is not the same as
806 comparing a given number of significant digits. If the values do not
807 compare equal, the test will fail with the explanation given by *msg*, or
808 :const:`None`.
809
Michael Foordba097ec2010-04-03 17:03:11 +0000810 If *delta* is supplied instead of *places* then the the difference
811 between *first* and *second* must be less than *delta*.
812
813 Supplying both *delta* and *places* raises a ``TypeError``.
814
Michael Foordc3f79372009-09-13 16:40:02 +0000815 .. versionchanged:: 2.7
816 Objects that compare equal are automatically almost equal.
Michael Foordba097ec2010-04-03 17:03:11 +0000817 Added the ``delta`` keyword argument.
Michael Foordc3f79372009-09-13 16:40:02 +0000818
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000819 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000820 :meth:`failUnlessAlmostEqual`; use :meth:`assertAlmostEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000821
Benjamin Peterson99721e02009-03-23 23:10:14 +0000822
Michael Foordba097ec2010-04-03 17:03:11 +0000823 .. method:: assertNotAlmostEqual(first, second[, places[, msg[, delta]]])
Michael Foordefc2f492010-04-08 04:33:20 +0000824 failIfAlmostEqual(first, second[, places[, msg[, delta]]])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000825
826 Test that *first* and *second* are not approximately equal by computing
827 the difference, rounding to the given number of decimal *places* (default
828 7), and comparing to zero.
829
830 Note that comparing a given number of decimal places is not the same as
831 comparing a given number of significant digits. If the values do not
832 compare equal, the test will fail with the explanation given by *msg*, or
833 :const:`None`.
834
Michael Foordba097ec2010-04-03 17:03:11 +0000835 If *delta* is supplied instead of *places* then the the difference
836 between *first* and *second* must be more than *delta*.
837
838 Supplying both *delta* and *places* raises a ``TypeError``.
839
Michael Foordc3f79372009-09-13 16:40:02 +0000840 .. versionchanged:: 2.7
841 Objects that compare equal automatically fail.
Michael Foordba097ec2010-04-03 17:03:11 +0000842 Added the ``delta`` keyword argument.
Michael Foordc3f79372009-09-13 16:40:02 +0000843
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000844 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000845 :meth:`failIfAlmostEqual`; use :meth:`assertNotAlmostEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000846
Benjamin Peterson99721e02009-03-23 23:10:14 +0000847
Gregory P. Smith28399852009-03-31 16:54:10 +0000848 .. method:: assertGreater(first, second, msg=None)
849 assertGreaterEqual(first, second, msg=None)
850 assertLess(first, second, msg=None)
851 assertLessEqual(first, second, msg=None)
852
853 Test that *first* is respectively >, >=, < or <= than *second* depending
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000854 on the method name. If not, the test will fail with an explanation
Gregory P. Smith28399852009-03-31 16:54:10 +0000855 or with the explanation given by *msg*::
856
857 >>> self.assertGreaterEqual(3, 4)
858 AssertionError: "3" unexpectedly not greater than or equal to "4"
859
860 .. versionadded:: 2.7
861
862
863 .. method:: assertMultiLineEqual(self, first, second, msg=None)
864
865 Test that the multiline string *first* is equal to the string *second*.
866 When not equal a diff of the two strings highlighting the differences
Michael Foordfe6349c2010-02-08 22:41:16 +0000867 will be included in the error message. This method is used by default
868 when comparing Unicode strings with :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000869
Michael Foord98e7b762010-03-20 03:00:34 +0000870 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000871
872 .. versionadded:: 2.7
873
874
Ezio Melotti5afe42b2010-01-16 19:36:42 +0000875 .. method:: assertRegexpMatches(text, regexp, msg=None)
Gregory P. Smith28399852009-03-31 16:54:10 +0000876
877 Verifies that a *regexp* search matches *text*. Fails with an error
878 message including the pattern and the *text*. *regexp* may be
879 a regular expression object or a string containing a regular expression
880 suitable for use by :func:`re.search`.
881
882 .. versionadded:: 2.7
883
884
Michael Foordba097ec2010-04-03 17:03:11 +0000885 .. method:: assertNotRegexpMatches(text, regexp, msg=None)
886
887 Verifies that a *regexp* search does not match *text*. Fails with an error
888 message including the pattern and the *text*. *regexp* may be
889 a regular expression object or a string containing a regular expression
890 suitable for use by :func:`re.search`.
891
892 .. versionadded:: 2.7
893
894
Gregory P. Smith28399852009-03-31 16:54:10 +0000895 .. method:: assertIn(first, second, msg=None)
896 assertNotIn(first, second, msg=None)
897
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000898 Tests that *first* is or is not in *second* with an explanatory error
Gregory P. Smith28399852009-03-31 16:54:10 +0000899 message as appropriate.
900
Michael Foord98e7b762010-03-20 03:00:34 +0000901 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000902
903 .. versionadded:: 2.7
904
905
Michael Foord98e7b762010-03-20 03:00:34 +0000906 .. method:: assertItemsEqual(actual, expected, msg=None)
Gregory P. Smith28399852009-03-31 16:54:10 +0000907
Michael Foorde70c72c2010-01-31 19:59:26 +0000908 Test that sequence *expected* contains the same elements as *actual*,
Michael Foord98e7b762010-03-20 03:00:34 +0000909 regardless of their order. When they don't, an error message listing the
910 differences between the sequences will be generated.
Gregory P. Smith28399852009-03-31 16:54:10 +0000911
Michael Foord98e7b762010-03-20 03:00:34 +0000912 Duplicate elements are *not* ignored when comparing *actual* and
913 *expected*. It verifies if each element has the same count in both
914 sequences. It is the equivalent of ``assertEqual(sorted(expected),
915 sorted(actual))`` but it works with sequences of unhashable objects as
916 well.
Michael Foord1c430012010-02-05 20:52:14 +0000917
Michael Foord98e7b762010-03-20 03:00:34 +0000918 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000919
920 .. versionadded:: 2.7
921
922
923 .. method:: assertSetEqual(set1, set2, msg=None)
924
925 Tests that two sets are equal. If not, an error message is constructed
Michael Foordfe6349c2010-02-08 22:41:16 +0000926 that lists the differences between the sets. This method is used by
927 default when comparing sets or frozensets with :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000928
929 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
930 method.
931
Michael Foord98e7b762010-03-20 03:00:34 +0000932 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000933
934 .. versionadded:: 2.7
935
936
937 .. method:: assertDictEqual(expected, actual, msg=None)
938
939 Test that two dictionaries are equal. If not, an error message is
Michael Foordfe6349c2010-02-08 22:41:16 +0000940 constructed that shows the differences in the dictionaries. This
941 method will be used by default to compare dictionaries in
942 calls to :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000943
Michael Foord98e7b762010-03-20 03:00:34 +0000944 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000945
946 .. versionadded:: 2.7
947
948
949 .. method:: assertDictContainsSubset(expected, actual, msg=None)
950
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000951 Tests whether the key/value pairs in dictionary *actual* are a
Gregory P. Smith28399852009-03-31 16:54:10 +0000952 superset of those in *expected*. If not, an error message listing
953 the missing keys and mismatched values is generated.
954
Michael Foord98e7b762010-03-20 03:00:34 +0000955 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000956
957 .. versionadded:: 2.7
958
959
960 .. method:: assertListEqual(list1, list2, msg=None)
961 assertTupleEqual(tuple1, tuple2, msg=None)
962
963 Tests that two lists or tuples are equal. If not an error message is
964 constructed that shows only the differences between the two. An error
965 is also raised if either of the parameters are of the wrong type.
Michael Foordfe6349c2010-02-08 22:41:16 +0000966 These methods are used by default when comparing lists or tuples with
967 :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000968
Michael Foord98e7b762010-03-20 03:00:34 +0000969 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000970
971 .. versionadded:: 2.7
972
973
974 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
975
976 Tests that two sequences are equal. If a *seq_type* is supplied, both
977 *seq1* and *seq2* must be instances of *seq_type* or a failure will
978 be raised. If the sequences are different an error message is
979 constructed that shows the difference between the two.
980
Michael Foord98e7b762010-03-20 03:00:34 +0000981 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000982
983 This method is used to implement :meth:`assertListEqual` and
984 :meth:`assertTupleEqual`.
985
986 .. versionadded:: 2.7
987
988
Benjamin Peterson99721e02009-03-23 23:10:14 +0000989 .. method:: assertRaises(exception[, callable, ...])
990 failUnlessRaises(exception[, callable, ...])
991
992 Test that an exception is raised when *callable* is called with any
993 positional or keyword arguments that are also passed to
994 :meth:`assertRaises`. The test passes if *exception* is raised, is an
995 error if another exception is raised, or fails if no exception is raised.
996 To catch any of a group of exceptions, a tuple containing the exception
997 classes may be passed as *exception*.
998
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000999 If *callable* is omitted or None, returns a context manager so that the
1000 code under test can be written inline rather than as a function::
1001
Michael Foord1f3fa8a2010-02-05 21:07:38 +00001002 with self.assertRaises(SomeException):
Benjamin Peterson7233acc2009-03-29 03:31:40 +00001003 do_something()
1004
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00001005 The context manager will store the caught exception object in its
Georg Brandldc3694b2010-02-07 17:02:22 +00001006 :attr:`exception` attribute. This can be useful if the intention
Michael Foord1f3fa8a2010-02-05 21:07:38 +00001007 is to perform additional checks on the exception raised::
1008
1009 with self.assertRaises(SomeException) as cm:
1010 do_something()
1011
Georg Brandldc3694b2010-02-07 17:02:22 +00001012 the_exception = cm.exception
Michael Foordba7732e2010-02-05 23:28:12 +00001013 self.assertEqual(the_exception.error_code, 3)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00001014
Benjamin Peterson99721e02009-03-23 23:10:14 +00001015 .. versionchanged:: 2.7
Benjamin Peterson7233acc2009-03-29 03:31:40 +00001016 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001017
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001018 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +00001019 :meth:`failUnlessRaises`; use :meth:`assertRaises`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001020
Benjamin Peterson99721e02009-03-23 23:10:14 +00001021
Gregory P. Smith28399852009-03-31 16:54:10 +00001022 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
Benjamin Peterson99721e02009-03-23 23:10:14 +00001023
Gregory P. Smith28399852009-03-31 16:54:10 +00001024 Like :meth:`assertRaises` but also tests that *regexp* matches
1025 on the string representation of the raised exception. *regexp* may be
1026 a regular expression object or a string containing a regular expression
1027 suitable for use by :func:`re.search`. Examples::
1028
1029 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
1030 int, 'XYZ')
1031
1032 or::
1033
1034 with self.assertRaisesRegexp(ValueError, 'literal'):
1035 int('XYZ')
1036
1037 .. versionadded:: 2.7
1038
1039
1040 .. method:: assertIsNone(expr[, msg])
1041
1042 This signals a test failure if *expr* is not None.
1043
1044 .. versionadded:: 2.7
1045
1046
1047 .. method:: assertIsNotNone(expr[, msg])
1048
1049 The inverse of the :meth:`assertIsNone` method.
1050 This signals a test failure if *expr* is None.
1051
1052 .. versionadded:: 2.7
1053
1054
Michael Foordf2dfef12009-04-05 19:19:28 +00001055 .. method:: assertIs(expr1, expr2[, msg])
1056
1057 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
1058 object.
1059
1060 .. versionadded:: 2.7
1061
1062
1063 .. method:: assertIsNot(expr1, expr2[, msg])
1064
1065 The inverse of the :meth:`assertIs` method.
1066 This signals a test failure if *expr1* and *expr2* evaluate to the same
1067 object.
1068
1069 .. versionadded:: 2.7
1070
1071
Georg Brandlf895cf52009-10-01 20:59:31 +00001072 .. method:: assertIsInstance(obj, cls[, msg])
1073
1074 This signals a test failure if *obj* is not an instance of *cls* (which
1075 can be a class or a tuple of classes, as supported by :func:`isinstance`).
1076
1077 .. versionadded:: 2.7
1078
1079
1080 .. method:: assertNotIsInstance(obj, cls[, msg])
1081
1082 The inverse of the :meth:`assertIsInstance` method. This signals a test
1083 failure if *obj* is an instance of *cls*.
1084
1085 .. versionadded:: 2.7
1086
1087
Gregory P. Smith28399852009-03-31 16:54:10 +00001088 .. method:: assertFalse(expr[, msg])
1089 failIf(expr[, msg])
1090
1091 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001092 This signals a test failure if *expr* is true, with *msg* or :const:`None`
1093 for the error message.
1094
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001095 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +00001096 :meth:`failIf`; use :meth:`assertFalse`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001097
Benjamin Peterson99721e02009-03-23 23:10:14 +00001098
1099 .. method:: fail([msg])
1100
1101 Signals a test failure unconditionally, with *msg* or :const:`None` for
1102 the error message.
1103
1104
1105 .. attribute:: failureException
1106
1107 This class attribute gives the exception raised by the test method. If a
1108 test framework needs to use a specialized exception, possibly to carry
1109 additional information, it must subclass this exception in order to "play
1110 fair" with the framework. The initial value of this attribute is
1111 :exc:`AssertionError`.
1112
Michael Foord345b2fe2009-04-02 03:20:38 +00001113
1114 .. attribute:: longMessage
1115
1116 If set to True then any explicit failure message you pass in to the
1117 assert methods will be appended to the end of the normal failure message.
1118 The normal messages contain useful information about the objects involved,
1119 for example the message from assertEqual shows you the repr of the two
1120 unequal objects. Setting this attribute to True allows you to have a
1121 custom error message in addition to the normal one.
1122
1123 This attribute defaults to False, meaning that a custom message passed
1124 to an assert method will silence the normal message.
1125
1126 The class setting can be overridden in individual tests by assigning an
1127 instance attribute to True or False before calling the assert methods.
1128
1129 .. versionadded:: 2.7
1130
1131
Benjamin Peterson99721e02009-03-23 23:10:14 +00001132 Testing frameworks can use the following methods to collect information on
1133 the test:
1134
1135
1136 .. method:: countTestCases()
1137
1138 Return the number of tests represented by this test object. For
1139 :class:`TestCase` instances, this will always be ``1``.
1140
1141
1142 .. method:: defaultTestResult()
1143
1144 Return an instance of the test result class that should be used for this
1145 test case class (if no other result instance is provided to the
1146 :meth:`run` method).
1147
1148 For :class:`TestCase` instances, this will always be an instance of
1149 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1150 as necessary.
1151
1152
1153 .. method:: id()
1154
1155 Return a string identifying the specific test case. This is usually the
1156 full name of the test method, including the module and class name.
1157
1158
1159 .. method:: shortDescription()
1160
Gregory P. Smith28399852009-03-31 16:54:10 +00001161 Returns a description of the test, or :const:`None` if no description
1162 has been provided. The default implementation of this method
1163 returns the first line of the test method's docstring, if available,
Michael Foorddb43b5a2010-02-10 14:25:12 +00001164 or :const:`None`.
Gregory P. Smith28399852009-03-31 16:54:10 +00001165
1166
1167 .. method:: addTypeEqualityFunc(typeobj, function)
1168
1169 Registers a type specific :meth:`assertEqual` equality checking
1170 function to be called by :meth:`assertEqual` when both objects it has
1171 been asked to compare are exactly *typeobj* (not subclasses).
1172 *function* must take two positional arguments and a third msg=None
1173 keyword argument just as :meth:`assertEqual` does. It must raise
Andrew M. Kuchling59631852009-04-09 11:23:36 +00001174 ``self.failureException`` when inequality between the first two
Gregory P. Smith28399852009-03-31 16:54:10 +00001175 parameters is detected.
1176
1177 One good use of custom equality checking functions for a type
Andrew M. Kuchling59631852009-04-09 11:23:36 +00001178 is to raise ``self.failureException`` with an error message useful
1179 for debugging the problem by explaining the inequalities in detail.
Gregory P. Smith28399852009-03-31 16:54:10 +00001180
1181 .. versionadded:: 2.7
Georg Brandl8ec7f652007-08-15 14:28:01 +00001182
1183
Michael Foorde2fb98f2009-05-02 20:15:05 +00001184 .. method:: addCleanup(function[, *args[, **kwargs]])
1185
1186 Add a function to be called after :meth:`tearDown` to cleanup resources
1187 used during the test. Functions will be called in reverse order to the
1188 order they are added (LIFO). They are called with any arguments and
1189 keyword arguments passed into :meth:`addCleanup` when they are
1190 added.
1191
1192 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1193 then any cleanup functions added will still be called.
1194
1195 .. versionadded:: 2.7
1196
1197
1198 .. method:: doCleanups()
1199
Barry Warsawfa900d42010-04-12 14:40:49 +00001200 This method is called unconditionally after :meth:`tearDown`, or
Michael Foorde2fb98f2009-05-02 20:15:05 +00001201 after :meth:`setUp` if :meth:`setUp` raises an exception.
1202
1203 It is responsible for calling all the cleanup functions added by
1204 :meth:`addCleanup`. If you need cleanup functions to be called
1205 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1206 yourself.
1207
1208 :meth:`doCleanups` pops methods off the stack of cleanup
1209 functions one at a time, so it can be called at any time.
1210
1211 .. versionadded:: 2.7
1212
1213
Georg Brandl8ec7f652007-08-15 14:28:01 +00001214.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
1215
1216 This class implements the portion of the :class:`TestCase` interface which
Georg Brandl2fcd1732009-05-30 10:45:40 +00001217 allows the test runner to drive the test, but does not provide the methods
1218 which test code can use to check and report errors. This is used to create
1219 test cases using legacy test code, allowing it to be integrated into a
1220 :mod:`unittest`-based test framework.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001221
1222
Benjamin Peterson99721e02009-03-23 23:10:14 +00001223.. _testsuite-objects:
1224
1225Grouping tests
1226~~~~~~~~~~~~~~
1227
Georg Brandl8ec7f652007-08-15 14:28:01 +00001228.. class:: TestSuite([tests])
1229
1230 This class represents an aggregation of individual tests cases and test suites.
1231 The class presents the interface needed by the test runner to allow it to be run
1232 as any other test case. Running a :class:`TestSuite` instance is the same as
1233 iterating over the suite, running each test individually.
1234
1235 If *tests* is given, it must be an iterable of individual test cases or other
1236 test suites that will be used to build the suite initially. Additional methods
1237 are provided to add test cases and suites to the collection later on.
1238
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001239 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1240 they do not actually implement a test. Instead, they are used to aggregate
1241 tests into groups of tests that should be run together. Some additional
1242 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson99721e02009-03-23 23:10:14 +00001243
1244
1245 .. method:: TestSuite.addTest(test)
1246
1247 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1248
1249
1250 .. method:: TestSuite.addTests(tests)
1251
1252 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1253 instances to this test suite.
1254
Georg Brandl2fcd1732009-05-30 10:45:40 +00001255 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1256 each element.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001257
1258 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1259
1260
1261 .. method:: run(result)
1262
1263 Run the tests associated with this suite, collecting the result into the
1264 test result object passed as *result*. Note that unlike
1265 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1266 be passed in.
1267
1268
1269 .. method:: debug()
1270
1271 Run the tests associated with this suite without collecting the
1272 result. This allows exceptions raised by the test to be propagated to the
1273 caller and can be used to support running tests under a debugger.
1274
1275
1276 .. method:: countTestCases()
1277
1278 Return the number of tests represented by this test object, including all
1279 individual tests and sub-suites.
1280
Georg Brandl9bc66822009-04-27 17:04:23 +00001281
1282 .. method:: __iter__()
1283
1284 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1285 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1286 that this method maybe called several times on a single suite
1287 (for example when counting tests or comparing for equality)
1288 so the tests returned must be the same for repeated iterations.
1289
1290 .. versionchanged:: 2.7
1291 In earlier versions the :class:`TestSuite` accessed tests directly rather
1292 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1293 for providing tests.
1294
Benjamin Peterson99721e02009-03-23 23:10:14 +00001295 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1296 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1297
1298
Benjamin Peterson99721e02009-03-23 23:10:14 +00001299Loading and running tests
1300~~~~~~~~~~~~~~~~~~~~~~~~~
1301
Georg Brandl8ec7f652007-08-15 14:28:01 +00001302.. class:: TestLoader()
1303
Benjamin Peterson99721e02009-03-23 23:10:14 +00001304 The :class:`TestLoader` class is used to create test suites from classes and
1305 modules. Normally, there is no need to create an instance of this class; the
1306 :mod:`unittest` module provides an instance that can be shared as
1307 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1308 customization of some configurable properties.
1309
1310 :class:`TestLoader` objects have the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001311
1312
Benjamin Peterson99721e02009-03-23 23:10:14 +00001313 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001314
Benjamin Peterson99721e02009-03-23 23:10:14 +00001315 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1316 :class:`testCaseClass`.
1317
1318
1319 .. method:: loadTestsFromModule(module)
1320
1321 Return a suite of all tests cases contained in the given module. This
1322 method searches *module* for classes derived from :class:`TestCase` and
1323 creates an instance of the class for each test method defined for the
1324 class.
1325
Georg Brandl16a57f62009-04-27 15:29:09 +00001326 .. note::
Benjamin Peterson99721e02009-03-23 23:10:14 +00001327
1328 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1329 convenient in sharing fixtures and helper functions, defining test
1330 methods on base classes that are not intended to be instantiated
1331 directly does not play well with this method. Doing so, however, can
1332 be useful when the fixtures are different and defined in subclasses.
1333
Michael Foordb4a81c82009-05-29 20:33:46 +00001334 If a module provides a ``load_tests`` function it will be called to
1335 load the tests. This allows modules to customize test loading.
1336 This is the `load_tests protocol`_.
1337
1338 .. versionchanged:: 2.7
1339 Support for ``load_tests`` added.
1340
Benjamin Peterson99721e02009-03-23 23:10:14 +00001341
1342 .. method:: loadTestsFromName(name[, module])
1343
1344 Return a suite of all tests cases given a string specifier.
1345
1346 The specifier *name* is a "dotted name" that may resolve either to a
1347 module, a test case class, a test method within a test case class, a
1348 :class:`TestSuite` instance, or a callable object which returns a
1349 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1350 applied in the order listed here; that is, a method on a possible test
1351 case class will be picked up as "a test method within a test case class",
1352 rather than "a callable object".
1353
1354 For example, if you have a module :mod:`SampleTests` containing a
Georg Brandl2fcd1732009-05-30 10:45:40 +00001355 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1356 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1357 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1358 return a suite which will run all three test methods. Using the specifier
1359 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1360 suite which will run only the :meth:`test_two` test method. The specifier
1361 can refer to modules and packages which have not been imported; they will
1362 be imported as a side-effect.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001363
1364 The method optionally resolves *name* relative to the given *module*.
1365
1366
1367 .. method:: loadTestsFromNames(names[, module])
1368
1369 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1370 than a single name. The return value is a test suite which supports all
1371 the tests defined for each name.
1372
1373
1374 .. method:: getTestCaseNames(testCaseClass)
1375
1376 Return a sorted sequence of method names found within *testCaseClass*;
1377 this should be a subclass of :class:`TestCase`.
1378
Michael Foordb4a81c82009-05-29 20:33:46 +00001379
1380 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1381
1382 Find and return all test modules from the specified start directory,
1383 recursing into subdirectories to find them. Only test files that match
Michael Foorde91ea562009-09-13 19:07:03 +00001384 *pattern* will be loaded. (Using shell style pattern matching.) Only
1385 module names that are importable (i.e. are valid Python identifiers) will
1386 be loaded.
Michael Foordb4a81c82009-05-29 20:33:46 +00001387
1388 All test modules must be importable from the top level of the project. If
1389 the start directory is not the top level directory then the top level
1390 directory must be specified separately.
1391
Michael Foorde91ea562009-09-13 19:07:03 +00001392 If importing a module fails, for example due to a syntax error, then this
1393 will be recorded as a single error and discovery will continue.
1394
Michael Foordb4a81c82009-05-29 20:33:46 +00001395 If a test package name (directory with :file:`__init__.py`) matches the
1396 pattern then the package will be checked for a ``load_tests``
1397 function. If this exists then it will be called with *loader*, *tests*,
1398 *pattern*.
1399
Michael Foorddc0460a2009-09-13 19:08:18 +00001400 If load_tests exists then discovery does *not* recurse into the package,
Michael Foordb4a81c82009-05-29 20:33:46 +00001401 ``load_tests`` is responsible for loading all tests in the package.
1402
1403 The pattern is deliberately not stored as a loader attribute so that
1404 packages can continue discovery themselves. *top_level_dir* is stored so
1405 ``load_tests`` does not need to pass this argument in to
1406 ``loader.discover()``.
1407
Michael Foordba097ec2010-04-03 17:03:11 +00001408 *start_dir* can be a dotted module name as well as a directory.
1409
Michael Foord17565e52009-09-27 20:08:23 +00001410 .. versionadded:: 2.7
Michael Foordb4a81c82009-05-29 20:33:46 +00001411
Benjamin Peterson99721e02009-03-23 23:10:14 +00001412 The following attributes of a :class:`TestLoader` can be configured either by
1413 subclassing or assignment on an instance:
1414
1415
1416 .. attribute:: testMethodPrefix
1417
1418 String giving the prefix of method names which will be interpreted as test
1419 methods. The default value is ``'test'``.
1420
1421 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1422 methods.
1423
1424
1425 .. attribute:: sortTestMethodsUsing
1426
1427 Function to be used to compare method names when sorting them in
1428 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
1429 default value is the built-in :func:`cmp` function; the attribute can also
1430 be set to :const:`None` to disable the sort.
1431
1432
1433 .. attribute:: suiteClass
1434
1435 Callable object that constructs a test suite from a list of tests. No
1436 methods on the resulting object are needed. The default value is the
1437 :class:`TestSuite` class.
1438
1439 This affects all the :meth:`loadTestsFrom\*` methods.
1440
1441
Benjamin Peterson99721e02009-03-23 23:10:14 +00001442.. class:: TestResult
1443
1444 This class is used to compile information about which tests have succeeded
1445 and which have failed.
1446
1447 A :class:`TestResult` object stores the results of a set of tests. The
1448 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1449 properly recorded; test authors do not need to worry about recording the
1450 outcome of tests.
1451
1452 Testing frameworks built on top of :mod:`unittest` may want access to the
1453 :class:`TestResult` object generated by running a set of tests for reporting
1454 purposes; a :class:`TestResult` instance is returned by the
1455 :meth:`TestRunner.run` method for this purpose.
1456
1457 :class:`TestResult` instances have the following attributes that will be of
1458 interest when inspecting the results of running a set of tests:
1459
1460
1461 .. attribute:: errors
1462
1463 A list containing 2-tuples of :class:`TestCase` instances and strings
1464 holding formatted tracebacks. Each tuple represents a test which raised an
1465 unexpected exception.
1466
1467 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001468 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1469
1470
1471 .. attribute:: failures
1472
1473 A list containing 2-tuples of :class:`TestCase` instances and strings
1474 holding formatted tracebacks. Each tuple represents a test where a failure
1475 was explicitly signalled using the :meth:`TestCase.fail\*` or
1476 :meth:`TestCase.assert\*` methods.
1477
1478 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001479 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1480
1481 .. attribute:: skipped
1482
1483 A list containing 2-tuples of :class:`TestCase` instances and strings
1484 holding the reason for skipping the test.
1485
1486 .. versionadded:: 2.7
1487
1488 .. attribute:: expectedFailures
1489
1490 A list contaning 2-tuples of :class:`TestCase` instances and strings
1491 holding formatted tracebacks. Each tuple represents a expected failures
1492 of the test case.
1493
1494 .. attribute:: unexpectedSuccesses
1495
1496 A list containing :class:`TestCase` instances that were marked as expected
1497 failures, but succeeded.
1498
1499 .. attribute:: shouldStop
1500
1501 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1502
1503
1504 .. attribute:: testsRun
1505
1506 The total number of tests run so far.
1507
1508
Michael Foordba097ec2010-04-03 17:03:11 +00001509 .. attribute:: buffer
1510
1511 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1512 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1513 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1514 fails or errors. Any output is also attached to the failure / error message.
1515
1516 .. versionadded:: 2.7
1517
1518
1519 .. attribute:: failfast
1520
1521 If set to true :meth:`stop` will be called on the first failure or error,
1522 halting the test run.
1523
1524 .. versionadded:: 2.7
1525
1526
Benjamin Peterson99721e02009-03-23 23:10:14 +00001527 .. method:: wasSuccessful()
1528
1529 Return :const:`True` if all tests run so far have passed, otherwise returns
1530 :const:`False`.
1531
1532
1533 .. method:: stop()
1534
1535 This method can be called to signal that the set of tests being run should
1536 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1537 :class:`TestRunner` objects should respect this flag and return without
1538 running any additional tests.
1539
1540 For example, this feature is used by the :class:`TextTestRunner` class to
1541 stop the test framework when the user signals an interrupt from the
1542 keyboard. Interactive tools which provide :class:`TestRunner`
1543 implementations can use this in a similar manner.
1544
1545 The following methods of the :class:`TestResult` class are used to maintain
1546 the internal data structures, and may be extended in subclasses to support
1547 additional reporting requirements. This is particularly useful in building
1548 tools which support interactive reporting while tests are being run.
1549
1550
1551 .. method:: startTest(test)
1552
1553 Called when the test case *test* is about to be run.
1554
Benjamin Peterson99721e02009-03-23 23:10:14 +00001555 .. method:: stopTest(test)
1556
1557 Called after the test case *test* has been executed, regardless of the
1558 outcome.
1559
Michael Foord07ef4872009-05-02 22:43:34 +00001560 .. method:: startTestRun(test)
1561
1562 Called once before any tests are executed.
1563
1564 .. versionadded:: 2.7
1565
1566
1567 .. method:: stopTestRun(test)
1568
Ezio Melotti7b4e02c2010-01-27 20:25:11 +00001569 Called once after all tests are executed.
Michael Foord07ef4872009-05-02 22:43:34 +00001570
1571 .. versionadded:: 2.7
1572
1573
Benjamin Peterson99721e02009-03-23 23:10:14 +00001574 .. method:: addError(test, err)
1575
1576 Called when the test case *test* raises an unexpected exception *err* is a
1577 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1578 traceback)``.
1579
1580 The default implementation appends a tuple ``(test, formatted_err)`` to
1581 the instance's :attr:`errors` attribute, where *formatted_err* is a
1582 formatted traceback derived from *err*.
1583
1584
1585 .. method:: addFailure(test, err)
1586
Michael Foordb4a81c82009-05-29 20:33:46 +00001587 Called when the test case *test* signals a failure. *err* is a tuple of
1588 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001589
1590 The default implementation appends a tuple ``(test, formatted_err)`` to
1591 the instance's :attr:`failures` attribute, where *formatted_err* is a
1592 formatted traceback derived from *err*.
1593
1594
1595 .. method:: addSuccess(test)
1596
1597 Called when the test case *test* succeeds.
1598
1599 The default implementation does nothing.
1600
1601
1602 .. method:: addSkip(test, reason)
1603
1604 Called when the test case *test* is skipped. *reason* is the reason the
1605 test gave for skipping.
1606
1607 The default implementation appends a tuple ``(test, reason)`` to the
1608 instance's :attr:`skipped` attribute.
1609
1610
1611 .. method:: addExpectedFailure(test, err)
1612
1613 Called when the test case *test* fails, but was marked with the
1614 :func:`expectedFailure` decorator.
1615
1616 The default implementation appends a tuple ``(test, formatted_err)`` to
1617 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1618 is a formatted traceback derived from *err*.
1619
1620
1621 .. method:: addUnexpectedSuccess(test)
1622
1623 Called when the test case *test* was marked with the
1624 :func:`expectedFailure` decorator, but succeeded.
1625
1626 The default implementation appends the test to the instance's
1627 :attr:`unexpectedSuccesses` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001628
Michael Foorddb43b5a2010-02-10 14:25:12 +00001629.. class:: TextTestResult(stream, descriptions, verbosity)
1630
1631 A concrete implementation of :class:`TestResult` used by the
1632 :class:`TextTestRunner`.
1633
1634 .. versionadded:: 2.7
1635 This class was previously named ``_TextTestResult``. The old name still
1636 exists as an alias but is deprecated.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001637
1638.. data:: defaultTestLoader
1639
1640 Instance of the :class:`TestLoader` class intended to be shared. If no
1641 customization of the :class:`TestLoader` is needed, this instance can be used
1642 instead of repeatedly creating new instances.
1643
1644
Michael Foorddb43b5a2010-02-10 14:25:12 +00001645.. class:: TextTestRunner([stream[, descriptions[, verbosity], [resultclass]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001646
1647 A basic test runner implementation which prints results on standard error. It
1648 has a few configurable parameters, but is essentially very simple. Graphical
1649 applications which run test suites should provide alternate implementations.
1650
Georg Brandl9bc66822009-04-27 17:04:23 +00001651 .. method:: _makeResult()
1652
1653 This method returns the instance of ``TestResult`` used by :meth:`run`.
1654 It is not intended to be called directly, but can be overridden in
1655 subclasses to provide a custom ``TestResult``.
1656
Michael Foorddb43b5a2010-02-10 14:25:12 +00001657 ``_makeResult()`` instantiates the class or callable passed in the
1658 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Michael Foordefc2f492010-04-08 04:33:20 +00001659 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foorddb43b5a2010-02-10 14:25:12 +00001660 The result class is instantiated with the following arguments::
1661
1662 stream, descriptions, verbosity
1663
Georg Brandl8ec7f652007-08-15 14:28:01 +00001664
Michael Foordddb20df2010-04-04 23:28:44 +00001665.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit[, verbosity[, failfast[, catchbreak[,buffer]]]]]]]]]])
Michael Foord55430352010-04-05 00:39:50 +00001666
Georg Brandl8ec7f652007-08-15 14:28:01 +00001667 A command-line program that runs a set of tests; this is primarily for making
1668 test modules conveniently executable. The simplest use for this function is to
1669 include the following line at the end of a test script::
1670
1671 if __name__ == '__main__':
1672 unittest.main()
1673
Michael Foord5d31e052009-05-11 17:59:43 +00001674 You can run tests with more detailed information by passing in the verbosity
1675 argument::
1676
1677 if __name__ == '__main__':
1678 unittest.main(verbosity=2)
1679
Georg Brandl8ec7f652007-08-15 14:28:01 +00001680 The *testRunner* argument can either be a test runner class or an already
Michael Foord829f6b82009-05-02 11:43:06 +00001681 created instance of it. By default ``main`` calls :func:`sys.exit` with
1682 an exit code indicating success or failure of the tests run.
1683
1684 ``main`` supports being used from the interactive interpreter by passing in the
1685 argument ``exit=False``. This displays the result on standard output without
1686 calling :func:`sys.exit`::
1687
1688 >>> from unittest import main
1689 >>> main(module='test_module', exit=False)
1690
Michael Foordddb20df2010-04-04 23:28:44 +00001691 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
1692 effect as the `failfast, catch and buffer command line options`_.
1693
Michael Foord829f6b82009-05-02 11:43:06 +00001694 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1695 This stores the result of the tests run as the ``result`` attribute.
1696
1697 .. versionchanged:: 2.7
Michael Foordddb20df2010-04-04 23:28:44 +00001698 The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
1699 parameters were added.
Michael Foordb4a81c82009-05-29 20:33:46 +00001700
1701
1702load_tests Protocol
1703###################
1704
Michael Foord17565e52009-09-27 20:08:23 +00001705
1706.. versionadded:: 2.7
1707
1708
Michael Foordb4a81c82009-05-29 20:33:46 +00001709Modules or packages can customize how tests are loaded from them during normal
1710test runs or test discovery by implementing a function called ``load_tests``.
1711
1712If a test module defines ``load_tests`` it will be called by
1713:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1714
1715 load_tests(loader, standard_tests, None)
1716
1717It should return a :class:`TestSuite`.
1718
1719*loader* is the instance of :class:`TestLoader` doing the loading.
1720*standard_tests* are the tests that would be loaded by default from the
1721module. It is common for test modules to only want to add or remove tests
1722from the standard set of tests.
1723The third argument is used when loading packages as part of test discovery.
1724
1725A typical ``load_tests`` function that loads tests from a specific set of
1726:class:`TestCase` classes may look like::
1727
1728 test_cases = (TestCase1, TestCase2, TestCase3)
1729
1730 def load_tests(loader, tests, pattern):
1731 suite = TestSuite()
1732 for test_class in test_cases:
1733 tests = loader.loadTestsFromTestCase(test_class)
1734 suite.addTests(tests)
1735 return suite
1736
1737If discovery is started, either from the command line or by calling
1738:meth:`TestLoader.discover`, with a pattern that matches a package
1739name then the package :file:`__init__.py` will be checked for ``load_tests``.
1740
1741.. note::
1742
Ezio Melotti062d2b52009-12-19 22:41:49 +00001743 The default pattern is 'test*.py'. This matches all Python files
Michael Foordb4a81c82009-05-29 20:33:46 +00001744 that start with 'test' but *won't* match any test directories.
1745
1746 A pattern like 'test*' will match test packages as well as
1747 modules.
1748
1749If the package :file:`__init__.py` defines ``load_tests`` then it will be
1750called and discovery not continued into the package. ``load_tests``
1751is called with the following arguments::
1752
1753 load_tests(loader, standard_tests, pattern)
1754
1755This should return a :class:`TestSuite` representing all the tests
1756from the package. (``standard_tests`` will only contain tests
1757collected from :file:`__init__.py`.)
1758
1759Because the pattern is passed into ``load_tests`` the package is free to
1760continue (and potentially modify) test discovery. A 'do nothing'
1761``load_tests`` function for a test package would look like::
1762
1763 def load_tests(loader, standard_tests, pattern):
1764 # top level directory cached on loader instance
1765 this_dir = os.path.dirname(__file__)
1766 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1767 standard_tests.addTests(package_tests)
1768 return standard_tests
Michael Foordba097ec2010-04-03 17:03:11 +00001769
1770
1771Class and Module Fixtures
1772-------------------------
1773
Michael Foord09e29802010-04-04 22:41:54 +00001774Class and module level fixtures are implemented in :class:`TestSuite`. When
1775the test suite encounters a test from a new class then :meth:`tearDownClass`
1776from the previous class (if there is one) is called, followed by
1777:meth:`setUpClass` from the new class.
Michael Foordba097ec2010-04-03 17:03:11 +00001778
Michael Foord09e29802010-04-04 22:41:54 +00001779Similarly if a test is from a different module from the previous test then
1780``tearDownModule`` from the previous module is run, followed by
1781``setUpModule`` from the new module.
Michael Foordba097ec2010-04-03 17:03:11 +00001782
Michael Foord09e29802010-04-04 22:41:54 +00001783After all the tests have run the final ``tearDownClass`` and
1784``tearDownModule`` are run.
Michael Foordba097ec2010-04-03 17:03:11 +00001785
Michael Foord09e29802010-04-04 22:41:54 +00001786Note that shared fixtures do not play well with [potential] features like test
1787parallelization and they break test isolation. They should be used with care.
Michael Foordba097ec2010-04-03 17:03:11 +00001788
Michael Foord09e29802010-04-04 22:41:54 +00001789The default ordering of tests created by the unittest test loaders is to group
1790all tests from the same modules and classes together. This will lead to
1791``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
1792module. If you randomize the order, so that tests from different modules and
1793classes are adjacent to each other, then these shared fixture functions may be
1794called multiple times in a single test run.
Michael Foordba097ec2010-04-03 17:03:11 +00001795
Michael Foord09e29802010-04-04 22:41:54 +00001796Shared fixtures are not intended to work with suites with non-standard
1797ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
1798support shared fixtures.
Michael Foordba097ec2010-04-03 17:03:11 +00001799
Michael Foord09e29802010-04-04 22:41:54 +00001800If there are any exceptions raised during one of the shared fixture functions
1801the test is reported as an error. Because there is no corresponding test
1802instance an ``_ErrorHolder`` object (that has the same interface as a
1803:class:`TestCase`) is created to represent the error. If you are just using
1804the standard unittest test runner then this detail doesn't matter, but if you
1805are a framework author it may be relevant.
Michael Foordba097ec2010-04-03 17:03:11 +00001806
1807
1808setUpClass and tearDownClass
1809~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1810
1811These must be implemented as class methods::
1812
1813 import unittest
1814
1815 class Test(unittest.TestCase):
1816 @classmethod
1817 def setUpClass(cls):
1818 cls._connection = createExpensiveConnectionObject()
1819
1820 @classmethod
1821 def tearDownClass(cls):
1822 cls._connection.destroy()
1823
Michael Foord09e29802010-04-04 22:41:54 +00001824If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
1825then you must call up to them yourself. The implementations in
1826:class:`TestCase` are empty.
Michael Foordba097ec2010-04-03 17:03:11 +00001827
Michael Foord09e29802010-04-04 22:41:54 +00001828If an exception is raised during a ``setUpClass`` then the tests in the class
1829are not run and the ``tearDownClass`` is not run. Skipped classes will not
1830have ``setUpClass`` or ``tearDownClass`` run.
Michael Foordba097ec2010-04-03 17:03:11 +00001831
1832
1833setUpModule and tearDownModule
1834~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1835
1836These should be implemented as functions::
1837
1838 def setUpModule():
1839 createConnection()
1840
1841 def tearDownModule():
1842 closeConnection()
1843
Michael Foord09e29802010-04-04 22:41:54 +00001844If an exception is raised in a ``setUpModule`` then none of the tests in the
1845module will be run and the ``tearDownModule`` will not be run.
Michael Foordba097ec2010-04-03 17:03:11 +00001846
1847
Michael Foord55430352010-04-05 00:39:50 +00001848Signal Handling
1849---------------
1850
1851The -c / --catch command line option to unittest, along with the ``catchbreak``
1852parameter to :func:`unittest.main()`, provide more friendly handling of
1853control-c during a test run. With catch break behavior enabled control-c will
1854allow the currently running test to complete, and the test run will then end
1855and report all the results so far. A second control-c will raise a
1856``KeyboardInterrupt`` in the usual way.
1857
1858There are a few utility functions for framework authors to enable this
1859functionality within test frameworks.
1860
1861.. function:: installHandler()
1862
Michael Foord31655032010-04-05 10:26:26 +00001863 Install the control-c handler. When a :const:`signal.SIGINT` is received
1864 (usually in response to the user pressing control-c) all registered results
Michael Foord55430352010-04-05 00:39:50 +00001865 have :meth:`~TestResult.stop` called.
1866
1867.. function:: registerResult(result)
1868
Michael Foord31655032010-04-05 10:26:26 +00001869 Register a :class:`TestResult` object for control-c handling. Registering a
Michael Foord55430352010-04-05 00:39:50 +00001870 result stores a weak reference to it, so it doesn't prevent the result from
1871 being garbage collected.
1872
1873.. function:: removeResult(result)
1874
Michael Foord31655032010-04-05 10:26:26 +00001875 Remove a registered result. Once a result has been removed then
Michael Foordd341ec82010-04-05 10:30:14 +00001876 :meth:`~TestResult.stop` will no longer be called on that result object in
Michael Foord31655032010-04-05 10:26:26 +00001877 response to a control-c.
Michael Foord55430352010-04-05 00:39:50 +00001878