blob: 640ed4bc63fb835551a27a1b99f4984f3591abbe [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`unittest` --- Unit testing framework
2==========================================
3
4.. module:: unittest
5 :synopsis: Unit testing framework for Python.
6.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
7.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9.. sectionauthor:: Raymond Hettinger <python@rcn.com>
10
Ezio Melotti22170ed2010-11-20 09:57:27 +000011(If you are already familiar with the basic concepts of testing, you might want
12to skip to :ref:`the list of assert methods <assert-methods>`.)
Georg Brandl116aa622007-08-15 14:28:22 +000013
Georg Brandl116aa622007-08-15 14:28:22 +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 Peterson52baa292009-03-24 00:56:30 +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 Brandl116aa622007-08-15 14:28:22 +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 Peterson14a3dd72009-05-25 00:51:58 +000062all tests added directly to the suite and in "child" test suites are run.
Georg Brandl116aa622007-08-15 14:28:22 +000063
Benjamin Peterson52baa292009-03-24 00:56:30 +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 Brandl116aa622007-08-15 14:28:22 +000072
73
74.. seealso::
75
76 Module :mod:`doctest`
77 Another test-support module with a very different flavor.
78
Benjamin Petersonb48af542010-04-11 20:43:16 +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 Brandl116aa622007-08-15 14:28:22 +000084 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000085 Kent Beck's original paper on testing frameworks using the pattern shared
86 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000087
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000088 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000089 Third-party unittest frameworks with a lighter-weight syntax for writing
90 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000091
Benjamin Petersonb48af542010-04-11 20:43:16 +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.
Benjamin Petersond2397752009-06-27 23:45:02 +000095
Benjamin Petersonb48af542010-04-11 20:43:16 +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.
Benjamin Petersond2397752009-06-27 23:45:02 +000099
Georg Brandl116aa622007-08-15 14:28:22 +0000100.. _unittest-minimal-example:
101
102Basic example
103-------------
104
105The :mod:`unittest` module provides a rich set of tools for constructing and
106running tests. This section demonstrates that a small subset of the tools
107suffice to meet the needs of most users.
108
109Here is a short script to test three functions from the :mod:`random` module::
110
111 import random
112 import unittest
113
114 class TestSequenceFunctions(unittest.TestCase):
115
116 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000117 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Benjamin Peterson52baa292009-03-24 00:56:30 +0000119 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000120 # make sure the shuffled sequence does not lose any elements
121 random.shuffle(self.seq)
122 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000123 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +0000124
Benjamin Peterson847a4112010-03-14 15:04:17 +0000125 # should raise an exception for an immutable sequence
126 self.assertRaises(TypeError, random.shuffle, (1,2,3))
127
Benjamin Peterson52baa292009-03-24 00:56:30 +0000128 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000129 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000130 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000131
Benjamin Peterson52baa292009-03-24 00:56:30 +0000132 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000133 with self.assertRaises(ValueError):
134 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000135 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000136 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138 if __name__ == '__main__':
139 unittest.main()
140
Benjamin Peterson52baa292009-03-24 00:56:30 +0000141A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000142individual tests are defined with methods whose names start with the letters
143``test``. This naming convention informs the test runner about which methods
144represent tests.
145
Benjamin Peterson52baa292009-03-24 00:56:30 +0000146The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000147expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000148:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
149These methods are used instead of the :keyword:`assert` statement so the test
150runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000151
Benjamin Peterson52baa292009-03-24 00:56:30 +0000152When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
153method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
154defined, the test runner will invoke that method after each test. In the
155example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
156test.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000159provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000160line, the above script produces an output that looks like this::
161
162 ...
163 ----------------------------------------------------------------------
164 Ran 3 tests in 0.000s
165
166 OK
167
168Instead of :func:`unittest.main`, there are other ways to run the tests with a
169finer level of control, less terse output, and no requirement to be run from the
170command line. For example, the last two lines may be replaced with::
171
172 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
173 unittest.TextTestRunner(verbosity=2).run(suite)
174
175Running the revised script from the interpreter or another script produces the
176following output::
177
Ezio Melottid59e44a2010-02-28 03:46:13 +0000178 test_choice (__main__.TestSequenceFunctions) ... ok
179 test_sample (__main__.TestSequenceFunctions) ... ok
180 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182 ----------------------------------------------------------------------
183 Ran 3 tests in 0.110s
184
185 OK
186
187The above examples show the most commonly used :mod:`unittest` features which
188are sufficient to meet many everyday testing needs. The remainder of the
189documentation explores the full feature set from first principles.
190
Benjamin Petersonb48af542010-04-11 20:43:16 +0000191
192.. _unittest-command-line-interface:
193
194Command Line Interface
195----------------------
196
197The unittest module can be used from the command line to run tests from
198modules, classes or even individual test methods::
199
200 python -m unittest test_module1 test_module2
201 python -m unittest test_module.TestClass
202 python -m unittest test_module.TestClass.test_method
203
204You can pass in a list with any combination of module names, and fully
205qualified class or method names.
206
207You can run tests with more detail (higher verbosity) by passing in the -v flag::
208
209 python -m unittest -v test_module
210
Michael Foord086f3082010-11-21 21:28:01 +0000211When executed without arguments :ref:`unittest-test-discovery` is started::
212
213 python -m unittest
214
Éric Araujo713d3032010-11-18 16:38:46 +0000215For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000216
217 python -m unittest -h
218
Georg Brandl67b21b72010-08-17 15:07:14 +0000219.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000220 In earlier versions it was only possible to run individual test methods and
221 not modules or classes.
222
223
Éric Araujo713d3032010-11-18 16:38:46 +0000224failfast, catch and buffer command-line options
Benjamin Petersonb48af542010-04-11 20:43:16 +0000225~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
226
Éric Araujod3309df2010-11-21 03:09:17 +0000227:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000228
Éric Araujo713d3032010-11-18 16:38:46 +0000229.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000230
Éric Araujo713d3032010-11-18 16:38:46 +0000231.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000232
Éric Araujo713d3032010-11-18 16:38:46 +0000233 The standard output and standard error streams are buffered during the test
234 run. Output during a passing test is discarded. Output is echoed normally
235 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000236
Éric Araujo713d3032010-11-18 16:38:46 +0000237.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000238
Éric Araujo713d3032010-11-18 16:38:46 +0000239 Control-C during the test run waits for the current test to end and then
240 reports all the results so far. A second control-C raises the normal
241 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000242
Éric Araujo713d3032010-11-18 16:38:46 +0000243 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000244
Éric Araujo713d3032010-11-18 16:38:46 +0000245.. cmdoption:: -f, --failfast
246
247 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000248
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000249.. versionadded:: 3.2
Éric Araujo713d3032010-11-18 16:38:46 +0000250 The command-line options :option:`-c`, :option:`-b` and :option:`-f` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000251
252The command line can also be used for test discovery, for running all of the
253tests in a project or just a subset.
254
255
256.. _unittest-test-discovery:
257
258Test Discovery
259--------------
260
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000261.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000262
263Unittest supports simple test discovery. For a project's tests to be
264compatible with test discovery they must all be importable from the top level
265directory of the project (in other words, they must all be in Python packages).
266
267Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000268used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000269
270 cd project_directory
271 python -m unittest discover
272
Michael Foord086f3082010-11-21 21:28:01 +0000273.. note::
274
275 As a shortcut, ``python -m unittest`` is the equivalent of
276 ``python -m unittest discover``. If you want to pass arguments to test
277 discovery the `discover` sub-command must be used explicitly.
278
Benjamin Petersonb48af542010-04-11 20:43:16 +0000279The ``discover`` sub-command has the following options:
280
Éric Araujo713d3032010-11-18 16:38:46 +0000281.. program:: unittest discover
282
283.. cmdoption:: -v, --verbose
284
285 Verbose output
286
287.. cmdoption:: -s directory
288
289 Directory to start discovery ('.' default)
290
291.. cmdoption:: -p pattern
292
293 Pattern to match test files ('test*.py' default)
294
295.. cmdoption:: -t directory
296
297 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000298
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000299The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
300as positional arguments in that order. The following two command lines
301are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000302
303 python -m unittest discover -s project_directory -p '*_test.py'
304 python -m unittest discover project_directory '*_test.py'
305
Michael Foord16f3e902010-05-08 15:13:42 +0000306As well as being a path it is possible to pass a package name, for example
307``myproject.subpackage.test``, as the start directory. The package name you
308supply will then be imported and its location on the filesystem will be used
309as the start directory.
310
311.. caution::
312
Senthil Kumaran916bd382010-10-15 12:55:19 +0000313 Test discovery loads tests by importing them. Once test discovery has found
314 all the test files from the start directory you specify it turns the paths
315 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000316 imported as ``foo.bar.baz``.
317
318 If you have a package installed globally and attempt test discovery on
319 a different copy of the package then the import *could* happen from the
320 wrong place. If this happens test discovery will warn you and exit.
321
322 If you supply the start directory as a package name rather than a
323 path to a directory then discover assumes that whichever location it
324 imports from is the location you intended, so you will not get the
325 warning.
326
Benjamin Petersonb48af542010-04-11 20:43:16 +0000327Test modules and packages can customize test loading and discovery by through
328the `load_tests protocol`_.
329
330
Georg Brandl116aa622007-08-15 14:28:22 +0000331.. _organizing-tests:
332
333Organizing test code
334--------------------
335
336The basic building blocks of unit testing are :dfn:`test cases` --- single
337scenarios that must be set up and checked for correctness. In :mod:`unittest`,
338test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
339class. To make your own test cases you must write subclasses of
340:class:`TestCase`, or use :class:`FunctionTestCase`.
341
342An instance of a :class:`TestCase`\ -derived class is an object that can
343completely run a single test method, together with optional set-up and tidy-up
344code.
345
346The testing code of a :class:`TestCase` instance should be entirely self
347contained, such that it can be run either in isolation or in arbitrary
348combination with any number of other test cases.
349
Benjamin Peterson52baa292009-03-24 00:56:30 +0000350The simplest :class:`TestCase` subclass will simply override the
351:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353 import unittest
354
355 class DefaultWidgetSizeTestCase(unittest.TestCase):
356 def runTest(self):
357 widget = Widget('The widget')
358 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
359
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000360Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000361methods provided by the :class:`TestCase` base class. If the test fails, an
362exception will be raised, and :mod:`unittest` will identify the test case as a
363:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
364helps you identify where the problem is: :dfn:`failures` are caused by incorrect
365results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
366code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368The way to run a test case will be described later. For now, note that to
369construct an instance of such a test case, we call its constructor without
370arguments::
371
372 testCase = DefaultWidgetSizeTestCase()
373
374Now, such test cases can be numerous, and their set-up can be repetitive. In
375the above case, constructing a :class:`Widget` in each of 100 Widget test case
376subclasses would mean unsightly duplication.
377
378Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000379:meth:`~TestCase.setUp`, which the testing framework will automatically call for
380us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382 import unittest
383
384 class SimpleWidgetTestCase(unittest.TestCase):
385 def setUp(self):
386 self.widget = Widget('The widget')
387
388 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
389 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000390 self.assertEqual(self.widget.size(), (50,50),
391 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000392
393 class WidgetResizeTestCase(SimpleWidgetTestCase):
394 def runTest(self):
395 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000396 self.assertEqual(self.widget.size(), (100,150),
397 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000398
Benjamin Peterson52baa292009-03-24 00:56:30 +0000399If the :meth:`~TestCase.setUp` method raises an exception while the test is
400running, the framework will consider the test to have suffered an error, and the
401:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000402
Benjamin Peterson52baa292009-03-24 00:56:30 +0000403Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
404after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000405
406 import unittest
407
408 class SimpleWidgetTestCase(unittest.TestCase):
409 def setUp(self):
410 self.widget = Widget('The widget')
411
412 def tearDown(self):
413 self.widget.dispose()
414 self.widget = None
415
Benjamin Peterson52baa292009-03-24 00:56:30 +0000416If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
417be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000418
419Such a working environment for the testing code is called a :dfn:`fixture`.
420
421Often, many small test cases will use the same fixture. In this case, we would
422end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
423classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000424discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
425mechanism::
426
427 import unittest
428
429 class WidgetTestCase(unittest.TestCase):
430 def setUp(self):
431 self.widget = Widget('The widget')
432
433 def tearDown(self):
434 self.widget.dispose()
435 self.widget = None
436
Ezio Melottid59e44a2010-02-28 03:46:13 +0000437 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000438 self.assertEqual(self.widget.size(), (50,50),
439 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000440
Ezio Melottid59e44a2010-02-28 03:46:13 +0000441 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000442 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000443 self.assertEqual(self.widget.size(), (100,150),
444 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000445
Benjamin Peterson52baa292009-03-24 00:56:30 +0000446Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
447provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000448the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000449separately for each instance. When creating an instance we must specify the
450test method it is to run. We do this by passing the method name in the
451constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000452
Ezio Melottid59e44a2010-02-28 03:46:13 +0000453 defaultSizeTestCase = WidgetTestCase('test_default_size')
454 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456Test case instances are grouped together according to the features they test.
457:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
458represented by :mod:`unittest`'s :class:`TestSuite` class::
459
460 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000461 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
462 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000463
464For the ease of running tests, as we will see later, it is a good idea to
465provide in each test module a callable object that returns a pre-built test
466suite::
467
468 def suite():
469 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000470 suite.addTest(WidgetTestCase('test_default_size'))
471 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000472 return suite
473
474or even::
475
476 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000477 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479 return unittest.TestSuite(map(WidgetTestCase, tests))
480
481Since it is a common pattern to create a :class:`TestCase` subclass with many
482similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
483class that can be used to automate the process of creating a test suite and
484populating it with individual tests. For example, ::
485
486 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
487
Ezio Melottid59e44a2010-02-28 03:46:13 +0000488will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
489``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000490name prefix to identify test methods automatically.
491
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000492Note that the order in which the various test cases will be run is
493determined by sorting the test function names with respect to the
494built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496Often it is desirable to group suites of test cases together, so as to run tests
497for the whole system at once. This is easy, since :class:`TestSuite` instances
498can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
499added to a :class:`TestSuite`::
500
501 suite1 = module1.TheTestSuite()
502 suite2 = module2.TheTestSuite()
503 alltests = unittest.TestSuite([suite1, suite2])
504
505You can place the definitions of test cases and test suites in the same modules
506as the code they are to test (such as :file:`widget.py`), but there are several
507advantages to placing the test code in a separate module, such as
508:file:`test_widget.py`:
509
510* The test module can be run standalone from the command line.
511
512* The test code can more easily be separated from shipped code.
513
514* There is less temptation to change test code to fit the code it tests without
515 a good reason.
516
517* Test code should be modified much less frequently than the code it tests.
518
519* Tested code can be refactored more easily.
520
521* Tests for modules written in C must be in separate modules anyway, so why not
522 be consistent?
523
524* If the testing strategy changes, there is no need to change the source code.
525
526
527.. _legacy-unit-tests:
528
529Re-using old test code
530----------------------
531
532Some users will find that they have existing test code that they would like to
533run from :mod:`unittest`, without converting every old test function to a
534:class:`TestCase` subclass.
535
536For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
537This subclass of :class:`TestCase` can be used to wrap an existing test
538function. Set-up and tear-down functions can also be provided.
539
540Given the following test function::
541
542 def testSomething():
543 something = makeSomething()
544 assert something.name is not None
545 # ...
546
547one can create an equivalent test case instance as follows::
548
549 testcase = unittest.FunctionTestCase(testSomething)
550
551If there are additional set-up and tear-down methods that should be called as
552part of the test case's operation, they can also be provided like so::
553
554 testcase = unittest.FunctionTestCase(testSomething,
555 setUp=makeSomethingDB,
556 tearDown=deleteSomethingDB)
557
558To make migrating existing test suites easier, :mod:`unittest` supports tests
559raising :exc:`AssertionError` to indicate test failure. However, it is
560recommended that you use the explicit :meth:`TestCase.fail\*` and
561:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
562may treat :exc:`AssertionError` differently.
563
564.. note::
565
Benjamin Petersond2397752009-06-27 23:45:02 +0000566 Even though :class:`FunctionTestCase` can be used to quickly convert an
567 existing test base over to a :mod:`unittest`\ -based system, this approach is
568 not recommended. Taking the time to set up proper :class:`TestCase`
569 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000570
Benjamin Peterson52baa292009-03-24 00:56:30 +0000571In some cases, the existing tests may have been written using the :mod:`doctest`
572module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
573automatically build :class:`unittest.TestSuite` instances from the existing
574:mod:`doctest`\ -based tests.
575
Georg Brandl116aa622007-08-15 14:28:22 +0000576
Benjamin Peterson5254c042009-03-23 22:25:03 +0000577.. _unittest-skipping:
578
579Skipping tests and expected failures
580------------------------------------
581
Michael Foordf5c851a2010-02-05 21:48:03 +0000582.. versionadded:: 3.1
583
Benjamin Peterson5254c042009-03-23 22:25:03 +0000584Unittest supports skipping individual test methods and even whole classes of
585tests. In addition, it supports marking a test as a "expected failure," a test
586that is broken and will fail, but shouldn't be counted as a failure on a
587:class:`TestResult`.
588
589Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
590or one of its conditional variants.
591
592Basic skipping looks like this: ::
593
594 class MyTestCase(unittest.TestCase):
595
596 @unittest.skip("demonstrating skipping")
597 def test_nothing(self):
598 self.fail("shouldn't happen")
599
Benjamin Petersond2397752009-06-27 23:45:02 +0000600 @unittest.skipIf(mylib.__version__ < (1, 3),
601 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000602 def test_format(self):
603 # Tests that work for only a certain version of the library.
604 pass
605
606 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
607 def test_windows_support(self):
608 # windows specific testing code
609 pass
610
Benjamin Peterson5254c042009-03-23 22:25:03 +0000611This is the output of running the example above in verbose mode: ::
612
Benjamin Petersonded31c42009-03-30 15:04:16 +0000613 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000614 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000615 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000616
617 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000618 Ran 3 tests in 0.005s
619
620 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000621
622Classes can be skipped just like methods: ::
623
624 @skip("showing class skipping")
625 class MySkippedTestCase(unittest.TestCase):
626 def test_not_run(self):
627 pass
628
Benjamin Peterson52baa292009-03-24 00:56:30 +0000629:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
630that needs to be set up is not available.
631
Benjamin Peterson5254c042009-03-23 22:25:03 +0000632Expected failures use the :func:`expectedFailure` decorator. ::
633
634 class ExpectedFailureTestCase(unittest.TestCase):
635 @unittest.expectedFailure
636 def test_fail(self):
637 self.assertEqual(1, 0, "broken")
638
639It's easy to roll your own skipping decorators by making a decorator that calls
640:func:`skip` on the test when it wants it to be skipped. This decorator skips
641the test unless the passed object has a certain attribute: ::
642
643 def skipUnlessHasattr(obj, attr):
644 if hasattr(obj, attr):
645 return lambda func: func
646 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
647
648The following decorators implement test skipping and expected failures:
649
Georg Brandl8a1caa22010-07-29 16:01:11 +0000650.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000651
652 Unconditionally skip the decorated test. *reason* should describe why the
653 test is being skipped.
654
Georg Brandl8a1caa22010-07-29 16:01:11 +0000655.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000656
657 Skip the decorated test if *condition* is true.
658
Georg Brandl8a1caa22010-07-29 16:01:11 +0000659.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000660
Georg Brandl6faee4e2010-09-21 14:48:28 +0000661 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000662
Georg Brandl8a1caa22010-07-29 16:01:11 +0000663.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000664
665 Mark the test as an expected failure. If the test fails when run, the test
666 is not counted as a failure.
667
Benjamin Petersonb48af542010-04-11 20:43:16 +0000668Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
669Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
670
Benjamin Peterson5254c042009-03-23 22:25:03 +0000671
Georg Brandl116aa622007-08-15 14:28:22 +0000672.. _unittest-contents:
673
674Classes and functions
675---------------------
676
Benjamin Peterson52baa292009-03-24 00:56:30 +0000677This section describes in depth the API of :mod:`unittest`.
678
679
680.. _testcase-objects:
681
682Test cases
683~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000684
Georg Brandl7f01a132009-09-16 15:58:14 +0000685.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000686
687 Instances of the :class:`TestCase` class represent the smallest testable units
688 in the :mod:`unittest` universe. This class is intended to be used as a base
689 class, with specific tests being implemented by concrete subclasses. This class
690 implements the interface needed by the test runner to allow it to drive the
691 test, and methods that the test code can use to check for and report various
692 kinds of failure.
693
694 Each instance of :class:`TestCase` will run a single test method: the method
695 named *methodName*. If you remember, we had an earlier example that went
696 something like this::
697
698 def suite():
699 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000700 suite.addTest(WidgetTestCase('test_default_size'))
701 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000702 return suite
703
704 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
705 single test.
706
Benjamin Peterson52baa292009-03-24 00:56:30 +0000707 *methodName* defaults to :meth:`runTest`.
708
709 :class:`TestCase` instances provide three groups of methods: one group used
710 to run the test, another used by the test implementation to check conditions
711 and report failures, and some inquiry methods allowing information about the
712 test itself to be gathered.
713
714 Methods in the first group (running the test) are:
715
716
717 .. method:: setUp()
718
719 Method called to prepare the test fixture. This is called immediately
720 before calling the test method; any exception raised by this method will
721 be considered an error rather than a test failure. The default
722 implementation does nothing.
723
724
725 .. method:: tearDown()
726
727 Method called immediately after the test method has been called and the
728 result recorded. This is called even if the test method raised an
729 exception, so the implementation in subclasses may need to be particularly
730 careful about checking internal state. Any exception raised by this
731 method will be considered an error rather than a test failure. This
732 method will only be called if the :meth:`setUp` succeeds, regardless of
733 the outcome of the test method. The default implementation does nothing.
734
735
Benjamin Petersonb48af542010-04-11 20:43:16 +0000736 .. method:: setUpClass()
737
738 A class method called before tests in an individual class run.
739 ``setUpClass`` is called with the class as the only argument
740 and must be decorated as a :func:`classmethod`::
741
742 @classmethod
743 def setUpClass(cls):
744 ...
745
746 See `Class and Module Fixtures`_ for more details.
747
748 .. versionadded:: 3.2
749
750
751 .. method:: tearDownClass()
752
753 A class method called after tests in an individual class have run.
754 ``tearDownClass`` is called with the class as the only argument
755 and must be decorated as a :meth:`classmethod`::
756
757 @classmethod
758 def tearDownClass(cls):
759 ...
760
761 See `Class and Module Fixtures`_ for more details.
762
763 .. versionadded:: 3.2
764
765
Georg Brandl7f01a132009-09-16 15:58:14 +0000766 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000767
768 Run the test, collecting the result into the test result object passed as
Ezio Melotti75b2a5e2010-11-20 10:13:45 +0000769 *result*. If *result* is omitted or ``None``, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000770 object is created (by calling the :meth:`defaultTestResult` method) and
771 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000772
773 The same effect may be had by simply calling the :class:`TestCase`
774 instance.
775
776
Benjamin Petersone549ead2009-03-28 21:42:05 +0000777 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000778
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000779 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000780 test. See :ref:`unittest-skipping` for more information.
781
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000782 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000783
Benjamin Peterson52baa292009-03-24 00:56:30 +0000784
785 .. method:: debug()
786
787 Run the test without collecting the result. This allows exceptions raised
788 by the test to be propagated to the caller, and can be used to support
789 running tests under a debugger.
790
Ezio Melotti22170ed2010-11-20 09:57:27 +0000791 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000792
Ezio Melotti4370b302010-11-03 20:39:14 +0000793 The :class:`TestCase` class provides a number of methods to check for and
794 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000795
Ezio Melotti4370b302010-11-03 20:39:14 +0000796 +-----------------------------------------+-----------------------------+---------------+
797 | Method | Checks that | New in |
798 +=========================================+=============================+===============+
799 | :meth:`assertEqual(a, b) | ``a == b`` | |
800 | <TestCase.assertEqual>` | | |
801 +-----------------------------------------+-----------------------------+---------------+
802 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
803 | <TestCase.assertNotEqual>` | | |
804 +-----------------------------------------+-----------------------------+---------------+
805 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
806 | <TestCase.assertTrue>` | | |
807 +-----------------------------------------+-----------------------------+---------------+
808 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
809 | <TestCase.assertFalse>` | | |
810 +-----------------------------------------+-----------------------------+---------------+
811 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
812 | <TestCase.assertIs>` | | |
813 +-----------------------------------------+-----------------------------+---------------+
814 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
815 | <TestCase.assertIsNot>` | | |
816 +-----------------------------------------+-----------------------------+---------------+
817 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
818 | <TestCase.assertIsNone>` | | |
819 +-----------------------------------------+-----------------------------+---------------+
820 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
821 | <TestCase.assertIsNotNone>` | | |
822 +-----------------------------------------+-----------------------------+---------------+
823 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
824 | <TestCase.assertIn>` | | |
825 +-----------------------------------------+-----------------------------+---------------+
826 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
827 | <TestCase.assertNotIn>` | | |
828 +-----------------------------------------+-----------------------------+---------------+
829 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
830 | <TestCase.assertIsInstance>` | | |
831 +-----------------------------------------+-----------------------------+---------------+
832 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
833 | <TestCase.assertNotIsInstance>` | | |
834 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000835
Ezio Melotti22170ed2010-11-20 09:57:27 +0000836 All the assert methods (except :meth:`assertRaises`,
837 :meth:`assertRaisesRegexp`, :meth:`assertWarns`, :meth:`assertWarnsRegexp`)
838 accept a *msg* argument that, if specified, is used as the error message on
839 failure (see also :data:`longMessage`).
Benjamin Peterson52baa292009-03-24 00:56:30 +0000840
Georg Brandl7f01a132009-09-16 15:58:14 +0000841 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000842
843 Test that *first* and *second* are equal. If the values do not compare
Ezio Melotti4841fd62010-11-05 15:43:40 +0000844 equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000845
846 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000847 list, tuple, dict, set, frozenset or str or any type that a subclass
848 registers with :meth:`addTypeEqualityFunc` the type specific equality
849 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000850 error message (see also the :ref:`list of type-specific methods
851 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000852
Raymond Hettinger35a88362009-04-09 00:08:24 +0000853 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000854 Added the automatic calling of type specific equality function.
855
Michael Foord28a817e2010-02-09 00:03:57 +0000856 .. versionchanged:: 3.2
857 :meth:`assertMultiLineEqual` added as the default type equality
858 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000859
Benjamin Peterson52baa292009-03-24 00:56:30 +0000860
Georg Brandl7f01a132009-09-16 15:58:14 +0000861 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000862
863 Test that *first* and *second* are not equal. If the values do compare
Ezio Melotti4841fd62010-11-05 15:43:40 +0000864 equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000865
Ezio Melotti4370b302010-11-03 20:39:14 +0000866 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000867 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000868
Ezio Melotti4841fd62010-11-05 15:43:40 +0000869 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000870
Ezio Melotti4841fd62010-11-05 15:43:40 +0000871 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
872 is True`` (use ``assertIs(expr, True)`` for the latter). This method
873 should also be avoided when more specific methods are available (e.g.
874 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
875 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000876
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000877
Ezio Melotti9794a262010-11-04 14:52:13 +0000878 .. method:: assertIs(first, second, msg=None)
879 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000880
Ezio Melotti9794a262010-11-04 14:52:13 +0000881 Test that *first* and *second* evaluate (or don't evaluate) to the same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000882
Raymond Hettinger35a88362009-04-09 00:08:24 +0000883 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000884
885
Ezio Melotti4370b302010-11-03 20:39:14 +0000886 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000887 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000888
Ezio Melotti9794a262010-11-04 14:52:13 +0000889 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000890
Ezio Melotti4370b302010-11-03 20:39:14 +0000891 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000892
893
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000894 .. method:: assertIn(first, second, msg=None)
895 assertNotIn(first, second, msg=None)
896
Ezio Melotti4841fd62010-11-05 15:43:40 +0000897 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000898
Raymond Hettinger35a88362009-04-09 00:08:24 +0000899 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000900
901
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000902 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000903 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000904
Ezio Melotti9794a262010-11-04 14:52:13 +0000905 Test that *obj* is (or is not) an instance of *cls* (which can be a
906 class or a tuple of classes, as supported by :func:`isinstance`).
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000907
Ezio Melotti4370b302010-11-03 20:39:14 +0000908 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000909
910
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000911
Ezio Melotti4370b302010-11-03 20:39:14 +0000912 It is also possible to check that exceptions and warnings are raised using
913 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000914
Ezio Melotti4370b302010-11-03 20:39:14 +0000915 +---------------------------------------------------------+--------------------------------------+------------+
916 | Method | Checks that | New in |
917 +=========================================================+======================================+============+
918 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | |
919 | <TestCase.assertRaises>` | | |
920 +---------------------------------------------------------+--------------------------------------+------------+
921 | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
922 | <TestCase.assertRaisesRegexp>` | and the message matches `re` | |
923 +---------------------------------------------------------+--------------------------------------+------------+
924 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
925 | <TestCase.assertWarns>` | | |
926 +---------------------------------------------------------+--------------------------------------+------------+
927 | :meth:`assertWarnsRegexp(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
928 | <TestCase.assertWarnsRegexp>` | and the message matches `re` | |
929 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000930
Georg Brandl7f01a132009-09-16 15:58:14 +0000931 .. method:: assertRaises(exception, callable, *args, **kwds)
Georg Brandl7f01a132009-09-16 15:58:14 +0000932 assertRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000933
934 Test that an exception is raised when *callable* is called with any
935 positional or keyword arguments that are also passed to
936 :meth:`assertRaises`. The test passes if *exception* is raised, is an
937 error if another exception is raised, or fails if no exception is raised.
938 To catch any of a group of exceptions, a tuple containing the exception
939 classes may be passed as *exception*.
940
Georg Brandl7f01a132009-09-16 15:58:14 +0000941 If only the *exception* argument is given, returns a context manager so
942 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000943
Michael Foord41531f22010-02-05 21:13:40 +0000944 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000945 do_something()
946
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000947 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000948 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000949 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000950
Georg Brandl8a1caa22010-07-29 16:01:11 +0000951 with self.assertRaises(SomeException) as cm:
952 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000953
Georg Brandl8a1caa22010-07-29 16:01:11 +0000954 the_exception = cm.exception
955 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000956
Ezio Melotti49008232010-02-08 21:57:48 +0000957 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000958 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000959
Ezio Melotti49008232010-02-08 21:57:48 +0000960 .. versionchanged:: 3.2
961 Added the :attr:`exception` attribute.
962
Benjamin Peterson52baa292009-03-24 00:56:30 +0000963
Ezio Melotti327433f2010-11-03 20:51:17 +0000964 .. method:: assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
965 assertRaisesRegexp(exception, regexp)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000966
967 Like :meth:`assertRaises` but also tests that *regexp* matches
968 on the string representation of the raised exception. *regexp* may be
969 a regular expression object or a string containing a regular expression
970 suitable for use by :func:`re.search`. Examples::
971
972 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
973 int, 'XYZ')
974
975 or::
976
977 with self.assertRaisesRegexp(ValueError, 'literal'):
978 int('XYZ')
979
Raymond Hettinger35a88362009-04-09 00:08:24 +0000980 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000981
982
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000983 .. method:: assertWarns(warning, callable, *args, **kwds)
984 assertWarns(warning)
985
986 Test that a warning is triggered when *callable* is called with any
987 positional or keyword arguments that are also passed to
988 :meth:`assertWarns`. The test passes if *warning* is triggered and
989 fails if it isn't. Also, any unexpected exception is an error.
990 To catch any of a group of warnings, a tuple containing the warning
991 classes may be passed as *warnings*.
992
993 If only the *warning* argument is given, returns a context manager so
994 that the code under test can be written inline rather than as a function::
995
996 with self.assertWarns(SomeWarning):
997 do_something()
998
999 The context manager will store the caught warning object in its
1000 :attr:`warning` attribute, and the source line which triggered the
1001 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1002 This can be useful if the intention is to perform additional checks
1003 on the exception raised::
1004
1005 with self.assertWarns(SomeWarning) as cm:
1006 do_something()
1007
1008 self.assertIn('myfile.py', cm.filename)
1009 self.assertEqual(320, cm.lineno)
1010
1011 This method works regardless of the warning filters in place when it
1012 is called.
1013
1014 .. versionadded:: 3.2
1015
1016
Ezio Melotti327433f2010-11-03 20:51:17 +00001017 .. method:: assertWarnsRegexp(warning, regexp, callable, *args, **kwds)
1018 assertWarnsRegexp(warning, regexp)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001019
1020 Like :meth:`assertWarns` but also tests that *regexp* matches on the
1021 message of the triggered warning. *regexp* may be a regular expression
1022 object or a string containing a regular expression suitable for use
1023 by :func:`re.search`. Example::
1024
1025 self.assertWarnsRegexp(DeprecationWarning,
1026 r'legacy_function\(\) is deprecated',
1027 legacy_function, 'XYZ')
1028
1029 or::
1030
1031 with self.assertWarnsRegexp(RuntimeWarning, 'unsafe frobnicating'):
1032 frobnicate('/etc/passwd')
1033
1034 .. versionadded:: 3.2
1035
1036
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001037
Ezio Melotti4370b302010-11-03 20:39:14 +00001038 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001039
Ezio Melotti4370b302010-11-03 20:39:14 +00001040 +---------------------------------------+--------------------------------+--------------+
1041 | Method | Checks that | New in |
1042 +=======================================+================================+==============+
1043 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1044 | <TestCase.assertAlmostEqual>` | | |
1045 +---------------------------------------+--------------------------------+--------------+
1046 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1047 | <TestCase.assertNotAlmostEqual>` | | |
1048 +---------------------------------------+--------------------------------+--------------+
1049 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1050 | <TestCase.assertGreater>` | | |
1051 +---------------------------------------+--------------------------------+--------------+
1052 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1053 | <TestCase.assertGreaterEqual>` | | |
1054 +---------------------------------------+--------------------------------+--------------+
1055 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1056 | <TestCase.assertLess>` | | |
1057 +---------------------------------------+--------------------------------+--------------+
1058 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1059 | <TestCase.assertLessEqual>` | | |
1060 +---------------------------------------+--------------------------------+--------------+
1061 | :meth:`assertRegexpMatches(s, re) | ``regex.search(s)`` | 3.1 |
1062 | <TestCase.assertRegexpMatches>` | | |
1063 +---------------------------------------+--------------------------------+--------------+
1064 | :meth:`assertNotRegexpMatches(s, re) | ``not regex.search(s)`` | 3.2 |
1065 | <TestCase.assertNotRegexpMatches>` | | |
1066 +---------------------------------------+--------------------------------+--------------+
1067 | :meth:`assertDictContainsSubset(a, b) | all the key/value pairs | 3.1 |
1068 | <TestCase.assertDictContainsSubset>` | in `a` exist in `b` | |
1069 +---------------------------------------+--------------------------------+--------------+
1070 | :meth:`assertItemsEqual(a, b) | `a` and `b` have the same | 3.2 |
1071 | <TestCase.assertItemsEqual>` | elements in the same number, | |
1072 | | regardless of their order | |
1073 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001074
1075
Ezio Melotti4370b302010-11-03 20:39:14 +00001076 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001077 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001078
Ezio Melotti4841fd62010-11-05 15:43:40 +00001079 Test that *first* and *second* are approximately (or not approximately)
1080 equal by computing the difference, rounding to the given number of
1081 decimal *places* (default 7), and comparing to zero. Note that these
1082 methods round the values to the given number of *decimal places* (i.e.
1083 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001084
Ezio Melotti4370b302010-11-03 20:39:14 +00001085 If *delta* is supplied instead of *places* then the difference
Ezio Melotti4841fd62010-11-05 15:43:40 +00001086 between *first* and *second* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001087
Ezio Melotti4370b302010-11-03 20:39:14 +00001088 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001089
Ezio Melotti4370b302010-11-03 20:39:14 +00001090 .. versionchanged:: 3.2
Ezio Melotti4841fd62010-11-05 15:43:40 +00001091 assertAlmostEqual automatically considers almost equal objects that compare equal.
1092 assertNotAlmostEqual automatically fails if the objects compare equal.
Ezio Melotti4370b302010-11-03 20:39:14 +00001093 Added the ``delta`` keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001094
Ezio Melotti4370b302010-11-03 20:39:14 +00001095
Ezio Melotti4370b302010-11-03 20:39:14 +00001096 .. method:: assertGreater(first, second, msg=None)
1097 assertGreaterEqual(first, second, msg=None)
1098 assertLess(first, second, msg=None)
1099 assertLessEqual(first, second, msg=None)
1100
1101 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001102 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001103
1104 >>> self.assertGreaterEqual(3, 4)
1105 AssertionError: "3" unexpectedly not greater than or equal to "4"
1106
1107 .. versionadded:: 3.1
1108
1109
1110 .. method:: assertRegexpMatches(text, regexp, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001111 assertNotRegexpMatches(text, regexp, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001112
Ezio Melotti4841fd62010-11-05 15:43:40 +00001113 Test that a *regexp* search matches (or does not match) *text*. In case
1114 of failure, the error message will include the pattern and the *text* (or
1115 the pattern and the part of *text* that unexpectedly matched). *regexp*
Ezio Melotti4370b302010-11-03 20:39:14 +00001116 may be a regular expression object or a string containing a regular
1117 expression suitable for use by :func:`re.search`.
1118
Ezio Melotti4841fd62010-11-05 15:43:40 +00001119 .. versionadded:: 3.1 :meth:`~TestCase.assertRegexpMatches`
1120 .. versionadded:: 3.2 :meth:`~TestCase.assertNotRegexpMatches`
Ezio Melotti4370b302010-11-03 20:39:14 +00001121
1122
1123 .. method:: assertDictContainsSubset(expected, actual, msg=None)
1124
1125 Tests whether the key/value pairs in dictionary *actual* are a
1126 superset of those in *expected*. If not, an error message listing
1127 the missing keys and mismatched values is generated.
1128
Ezio Melotti4370b302010-11-03 20:39:14 +00001129 .. versionadded:: 3.1
1130
1131
1132 .. method:: assertItemsEqual(actual, expected, msg=None)
1133
1134 Test that sequence *expected* contains the same elements as *actual*,
1135 regardless of their order. When they don't, an error message listing the
1136 differences between the sequences will be generated.
1137
1138 Duplicate elements are *not* ignored when comparing *actual* and
1139 *expected*. It verifies if each element has the same count in both
1140 sequences. It is the equivalent of ``assertEqual(sorted(expected),
1141 sorted(actual))`` but it works with sequences of unhashable objects as
1142 well.
1143
Ezio Melotti4370b302010-11-03 20:39:14 +00001144 .. versionadded:: 3.2
1145
1146
1147 .. method:: assertSameElements(actual, expected, msg=None)
1148
1149 Test that sequence *expected* contains the same elements as *actual*,
1150 regardless of their order. When they don't, an error message listing
1151 the differences between the sequences will be generated.
1152
1153 Duplicate elements are ignored when comparing *actual* and *expected*.
1154 It is the equivalent of ``assertEqual(set(expected), set(actual))``
1155 but it works with sequences of unhashable objects as well. Because
1156 duplicates are ignored, this method has been deprecated in favour of
1157 :meth:`assertItemsEqual`.
1158
Ezio Melotti4370b302010-11-03 20:39:14 +00001159 .. versionadded:: 3.1
1160 .. deprecated:: 3.2
1161
1162
Ezio Melotti22170ed2010-11-20 09:57:27 +00001163 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001164
Ezio Melotti22170ed2010-11-20 09:57:27 +00001165 The :meth:`assertEqual` method dispatches the equality check for objects of
1166 the same type to different type-specific methods. These methods are already
1167 implemented for most of the built-in types, but it's also possible to
1168 register new methods using :meth:`addTypeEqualityFunc`:
1169
1170 .. method:: addTypeEqualityFunc(typeobj, function)
1171
1172 Registers a type-specific method called by :meth:`assertEqual` to check
1173 if two objects of exactly the same *typeobj* (not subclasses) compare
1174 equal. *function* must take two positional arguments and a third msg=None
1175 keyword argument just as :meth:`assertEqual` does. It must raise
1176 :data:`self.failureException(msg) <failureException>` when inequality
1177 between the first two parameters is detected -- possibly providing useful
1178 information and explaining the inequalities in details in the error
1179 message.
1180
1181 .. versionadded:: 3.1
1182
1183 The list of type-specific methods automatically used by
1184 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1185 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001186
1187 +-----------------------------------------+-----------------------------+--------------+
1188 | Method | Used to compare | New in |
1189 +=========================================+=============================+==============+
1190 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1191 | <TestCase.assertMultiLineEqual>` | | |
1192 +-----------------------------------------+-----------------------------+--------------+
1193 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1194 | <TestCase.assertSequenceEqual>` | | |
1195 +-----------------------------------------+-----------------------------+--------------+
1196 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1197 | <TestCase.assertListEqual>` | | |
1198 +-----------------------------------------+-----------------------------+--------------+
1199 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1200 | <TestCase.assertTupleEqual>` | | |
1201 +-----------------------------------------+-----------------------------+--------------+
1202 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1203 | <TestCase.assertSetEqual>` | | |
1204 +-----------------------------------------+-----------------------------+--------------+
1205 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1206 | <TestCase.assertDictEqual>` | | |
1207 +-----------------------------------------+-----------------------------+--------------+
1208
1209
1210
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001211 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001212
1213 Test that the multiline string *first* is equal to the string *second*.
1214 When not equal a diff of the two strings highlighting the differences
1215 will be included in the error message. This method is used by default
1216 when comparing strings with :meth:`assertEqual`.
1217
Ezio Melotti4370b302010-11-03 20:39:14 +00001218 .. versionadded:: 3.1
1219
1220
1221 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
1222
1223 Tests that two sequences are equal. If a *seq_type* is supplied, both
1224 *seq1* and *seq2* must be instances of *seq_type* or a failure will
1225 be raised. If the sequences are different an error message is
1226 constructed that shows the difference between the two.
1227
Ezio Melotti22170ed2010-11-20 09:57:27 +00001228 This method is not called directly by :meth:`assertEqual`, but
1229 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001230 :meth:`assertTupleEqual`.
1231
1232 .. versionadded:: 3.1
1233
1234
1235 .. method:: assertListEqual(list1, list2, msg=None)
1236 assertTupleEqual(tuple1, tuple2, msg=None)
1237
1238 Tests that two lists or tuples are equal. If not an error message is
1239 constructed that shows only the differences between the two. An error
1240 is also raised if either of the parameters are of the wrong type.
1241 These methods are used by default when comparing lists or tuples with
1242 :meth:`assertEqual`.
1243
Ezio Melotti4370b302010-11-03 20:39:14 +00001244 .. versionadded:: 3.1
1245
1246
1247 .. method:: assertSetEqual(set1, set2, msg=None)
1248
1249 Tests that two sets are equal. If not, an error message is constructed
1250 that lists the differences between the sets. This method is used by
1251 default when comparing sets or frozensets with :meth:`assertEqual`.
1252
1253 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
1254 method.
1255
Ezio Melotti4370b302010-11-03 20:39:14 +00001256 .. versionadded:: 3.1
1257
1258
1259 .. method:: assertDictEqual(expected, actual, msg=None)
1260
1261 Test that two dictionaries are equal. If not, an error message is
1262 constructed that shows the differences in the dictionaries. This
1263 method will be used by default to compare dictionaries in
1264 calls to :meth:`assertEqual`.
1265
Ezio Melotti4370b302010-11-03 20:39:14 +00001266 .. versionadded:: 3.1
1267
1268
1269
Ezio Melotti22170ed2010-11-20 09:57:27 +00001270 .. _other-methods-and-attrs:
1271
Ezio Melotti4370b302010-11-03 20:39:14 +00001272 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001273
Benjamin Peterson52baa292009-03-24 00:56:30 +00001274
Georg Brandl7f01a132009-09-16 15:58:14 +00001275 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001276
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001277 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001278 the error message.
1279
1280
1281 .. attribute:: failureException
1282
1283 This class attribute gives the exception raised by the test method. If a
1284 test framework needs to use a specialized exception, possibly to carry
1285 additional information, it must subclass this exception in order to "play
1286 fair" with the framework. The initial value of this attribute is
1287 :exc:`AssertionError`.
1288
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001289
1290 .. attribute:: longMessage
1291
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001292 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001293 :ref:`assert methods <assert-methods>` will be appended to the end of the
1294 normal failure message. The normal messages contain useful information
1295 about the objects involved, for example the message from assertEqual
1296 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001297 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001298 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001299
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001300 This attribute defaults to ``False``, meaning that a custom message passed
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001301 to an assert method will silence the normal message.
1302
1303 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001304 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001305
Raymond Hettinger35a88362009-04-09 00:08:24 +00001306 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001307
1308
Michael Foord98b3e762010-06-05 21:59:55 +00001309 .. attribute:: maxDiff
1310
1311 This attribute controls the maximum length of diffs output by assert
1312 methods that report diffs on failure. It defaults to 80*8 characters.
1313 Assert methods affected by this attribute are
1314 :meth:`assertSequenceEqual` (including all the sequence comparison
1315 methods that delegate to it), :meth:`assertDictEqual` and
1316 :meth:`assertMultiLineEqual`.
1317
1318 Setting ``maxDiff`` to None means that there is no maximum length of
1319 diffs.
1320
1321 .. versionadded:: 3.2
1322
1323
Benjamin Peterson52baa292009-03-24 00:56:30 +00001324 Testing frameworks can use the following methods to collect information on
1325 the test:
1326
1327
1328 .. method:: countTestCases()
1329
1330 Return the number of tests represented by this test object. For
1331 :class:`TestCase` instances, this will always be ``1``.
1332
1333
1334 .. method:: defaultTestResult()
1335
1336 Return an instance of the test result class that should be used for this
1337 test case class (if no other result instance is provided to the
1338 :meth:`run` method).
1339
1340 For :class:`TestCase` instances, this will always be an instance of
1341 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1342 as necessary.
1343
1344
1345 .. method:: id()
1346
1347 Return a string identifying the specific test case. This is usually the
1348 full name of the test method, including the module and class name.
1349
1350
1351 .. method:: shortDescription()
1352
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001353 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001354 has been provided. The default implementation of this method
1355 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001356 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001357
Michael Foord34c94622010-02-10 15:51:42 +00001358 .. versionchanged:: 3.1,3.2
1359 In 3.1 this was changed to add the test name to the short description
1360 even in the presence of a docstring. This caused compatibility issues
1361 with unittest extensions and adding the test name was moved to the
1362 :class:`TextTestResult`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001363
Georg Brandl116aa622007-08-15 14:28:22 +00001364
Georg Brandl7f01a132009-09-16 15:58:14 +00001365 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001366
1367 Add a function to be called after :meth:`tearDown` to cleanup resources
1368 used during the test. Functions will be called in reverse order to the
1369 order they are added (LIFO). They are called with any arguments and
1370 keyword arguments passed into :meth:`addCleanup` when they are
1371 added.
1372
1373 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1374 then any cleanup functions added will still be called.
1375
Georg Brandl853947a2010-01-31 18:53:23 +00001376 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001377
1378
1379 .. method:: doCleanups()
1380
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001381 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001382 after :meth:`setUp` if :meth:`setUp` raises an exception.
1383
1384 It is responsible for calling all the cleanup functions added by
1385 :meth:`addCleanup`. If you need cleanup functions to be called
1386 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1387 yourself.
1388
1389 :meth:`doCleanups` pops methods off the stack of cleanup
1390 functions one at a time, so it can be called at any time.
1391
Georg Brandl853947a2010-01-31 18:53:23 +00001392 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001393
1394
Georg Brandl7f01a132009-09-16 15:58:14 +00001395.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001396
1397 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001398 allows the test runner to drive the test, but does not provide the methods
1399 which test code can use to check and report errors. This is used to create
1400 test cases using legacy test code, allowing it to be integrated into a
1401 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001402
1403
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001404Deprecated aliases
1405##################
1406
1407For historical reasons, some of the :class:`TestCase` methods had one or more
1408aliases that are now deprecated. The following table lists the correct names
1409along with their deprecated aliases:
1410
1411 ============================== ===============================
1412 Method Name Deprecated alias(es)
1413 ============================== ===============================
1414 :meth:`.assertEqual` failUnlessEqual, assertEquals
1415 :meth:`.assertNotEqual` failIfEqual
1416 :meth:`.assertTrue` failUnless, assert\_
1417 :meth:`.assertFalse` failIf
1418 :meth:`.assertRaises` failUnlessRaises
1419 :meth:`.assertAlmostEqual` failUnlessAlmostEqual
1420 :meth:`.assertNotAlmostEqual` failIfAlmostEqual
1421 ============================== ===============================
1422
1423 .. deprecated:: 3.1
1424 the aliases listed in the second column
1425
1426
1427
Benjamin Peterson52baa292009-03-24 00:56:30 +00001428.. _testsuite-objects:
1429
Benjamin Peterson52baa292009-03-24 00:56:30 +00001430Grouping tests
1431~~~~~~~~~~~~~~
1432
Georg Brandl7f01a132009-09-16 15:58:14 +00001433.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001434
1435 This class represents an aggregation of individual tests cases and test suites.
1436 The class presents the interface needed by the test runner to allow it to be run
1437 as any other test case. Running a :class:`TestSuite` instance is the same as
1438 iterating over the suite, running each test individually.
1439
1440 If *tests* is given, it must be an iterable of individual test cases or other
1441 test suites that will be used to build the suite initially. Additional methods
1442 are provided to add test cases and suites to the collection later on.
1443
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001444 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1445 they do not actually implement a test. Instead, they are used to aggregate
1446 tests into groups of tests that should be run together. Some additional
1447 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001448
1449
1450 .. method:: TestSuite.addTest(test)
1451
1452 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1453
1454
1455 .. method:: TestSuite.addTests(tests)
1456
1457 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1458 instances to this test suite.
1459
Benjamin Petersond2397752009-06-27 23:45:02 +00001460 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1461 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001462
1463 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1464
1465
1466 .. method:: run(result)
1467
1468 Run the tests associated with this suite, collecting the result into the
1469 test result object passed as *result*. Note that unlike
1470 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1471 be passed in.
1472
1473
1474 .. method:: debug()
1475
1476 Run the tests associated with this suite without collecting the
1477 result. This allows exceptions raised by the test to be propagated to the
1478 caller and can be used to support running tests under a debugger.
1479
1480
1481 .. method:: countTestCases()
1482
1483 Return the number of tests represented by this test object, including all
1484 individual tests and sub-suites.
1485
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001486
1487 .. method:: __iter__()
1488
1489 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1490 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1491 that this method maybe called several times on a single suite
1492 (for example when counting tests or comparing for equality)
1493 so the tests returned must be the same for repeated iterations.
1494
Georg Brandl853947a2010-01-31 18:53:23 +00001495 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001496 In earlier versions the :class:`TestSuite` accessed tests directly rather
1497 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1498 for providing tests.
1499
Benjamin Peterson52baa292009-03-24 00:56:30 +00001500 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1501 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1502
1503
Benjamin Peterson52baa292009-03-24 00:56:30 +00001504Loading and running tests
1505~~~~~~~~~~~~~~~~~~~~~~~~~
1506
Georg Brandl116aa622007-08-15 14:28:22 +00001507.. class:: TestLoader()
1508
Benjamin Peterson52baa292009-03-24 00:56:30 +00001509 The :class:`TestLoader` class is used to create test suites from classes and
1510 modules. Normally, there is no need to create an instance of this class; the
1511 :mod:`unittest` module provides an instance that can be shared as
1512 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1513 customization of some configurable properties.
1514
1515 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001516
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001517
Benjamin Peterson52baa292009-03-24 00:56:30 +00001518 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001519
Benjamin Peterson52baa292009-03-24 00:56:30 +00001520 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1521 :class:`testCaseClass`.
1522
1523
1524 .. method:: loadTestsFromModule(module)
1525
1526 Return a suite of all tests cases contained in the given module. This
1527 method searches *module* for classes derived from :class:`TestCase` and
1528 creates an instance of the class for each test method defined for the
1529 class.
1530
Georg Brandle720c0a2009-04-27 16:20:50 +00001531 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001532
1533 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1534 convenient in sharing fixtures and helper functions, defining test
1535 methods on base classes that are not intended to be instantiated
1536 directly does not play well with this method. Doing so, however, can
1537 be useful when the fixtures are different and defined in subclasses.
1538
Benjamin Petersond2397752009-06-27 23:45:02 +00001539 If a module provides a ``load_tests`` function it will be called to
1540 load the tests. This allows modules to customize test loading.
1541 This is the `load_tests protocol`_.
1542
Georg Brandl853947a2010-01-31 18:53:23 +00001543 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001544 Support for ``load_tests`` added.
1545
Benjamin Peterson52baa292009-03-24 00:56:30 +00001546
Georg Brandl7f01a132009-09-16 15:58:14 +00001547 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001548
1549 Return a suite of all tests cases given a string specifier.
1550
1551 The specifier *name* is a "dotted name" that may resolve either to a
1552 module, a test case class, a test method within a test case class, a
1553 :class:`TestSuite` instance, or a callable object which returns a
1554 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1555 applied in the order listed here; that is, a method on a possible test
1556 case class will be picked up as "a test method within a test case class",
1557 rather than "a callable object".
1558
1559 For example, if you have a module :mod:`SampleTests` containing a
1560 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1561 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001562 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1563 return a suite which will run all three test methods. Using the specifier
1564 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1565 suite which will run only the :meth:`test_two` test method. The specifier
1566 can refer to modules and packages which have not been imported; they will
1567 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001568
1569 The method optionally resolves *name* relative to the given *module*.
1570
1571
Georg Brandl7f01a132009-09-16 15:58:14 +00001572 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001573
1574 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1575 than a single name. The return value is a test suite which supports all
1576 the tests defined for each name.
1577
1578
1579 .. method:: getTestCaseNames(testCaseClass)
1580
1581 Return a sorted sequence of method names found within *testCaseClass*;
1582 this should be a subclass of :class:`TestCase`.
1583
Benjamin Petersond2397752009-06-27 23:45:02 +00001584
1585 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1586
1587 Find and return all test modules from the specified start directory,
1588 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001589 *pattern* will be loaded. (Using shell style pattern matching.) Only
1590 module names that are importable (i.e. are valid Python identifiers) will
1591 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001592
1593 All test modules must be importable from the top level of the project. If
1594 the start directory is not the top level directory then the top level
1595 directory must be specified separately.
1596
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001597 If importing a module fails, for example due to a syntax error, then this
1598 will be recorded as a single error and discovery will continue.
1599
Benjamin Petersond2397752009-06-27 23:45:02 +00001600 If a test package name (directory with :file:`__init__.py`) matches the
1601 pattern then the package will be checked for a ``load_tests``
1602 function. If this exists then it will be called with *loader*, *tests*,
1603 *pattern*.
1604
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001605 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001606 ``load_tests`` is responsible for loading all tests in the package.
1607
1608 The pattern is deliberately not stored as a loader attribute so that
1609 packages can continue discovery themselves. *top_level_dir* is stored so
1610 ``load_tests`` does not need to pass this argument in to
1611 ``loader.discover()``.
1612
Benjamin Petersonb48af542010-04-11 20:43:16 +00001613 *start_dir* can be a dotted module name as well as a directory.
1614
Georg Brandl853947a2010-01-31 18:53:23 +00001615 .. versionadded:: 3.2
1616
Benjamin Petersond2397752009-06-27 23:45:02 +00001617
Benjamin Peterson52baa292009-03-24 00:56:30 +00001618 The following attributes of a :class:`TestLoader` can be configured either by
1619 subclassing or assignment on an instance:
1620
1621
1622 .. attribute:: testMethodPrefix
1623
1624 String giving the prefix of method names which will be interpreted as test
1625 methods. The default value is ``'test'``.
1626
1627 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1628 methods.
1629
1630
1631 .. attribute:: sortTestMethodsUsing
1632
1633 Function to be used to compare method names when sorting them in
1634 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1635
1636
1637 .. attribute:: suiteClass
1638
1639 Callable object that constructs a test suite from a list of tests. No
1640 methods on the resulting object are needed. The default value is the
1641 :class:`TestSuite` class.
1642
1643 This affects all the :meth:`loadTestsFrom\*` methods.
1644
1645
Benjamin Peterson52baa292009-03-24 00:56:30 +00001646.. class:: TestResult
1647
1648 This class is used to compile information about which tests have succeeded
1649 and which have failed.
1650
1651 A :class:`TestResult` object stores the results of a set of tests. The
1652 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1653 properly recorded; test authors do not need to worry about recording the
1654 outcome of tests.
1655
1656 Testing frameworks built on top of :mod:`unittest` may want access to the
1657 :class:`TestResult` object generated by running a set of tests for reporting
1658 purposes; a :class:`TestResult` instance is returned by the
1659 :meth:`TestRunner.run` method for this purpose.
1660
1661 :class:`TestResult` instances have the following attributes that will be of
1662 interest when inspecting the results of running a set of tests:
1663
1664
1665 .. attribute:: errors
1666
1667 A list containing 2-tuples of :class:`TestCase` instances and strings
1668 holding formatted tracebacks. Each tuple represents a test which raised an
1669 unexpected exception.
1670
Benjamin Peterson52baa292009-03-24 00:56:30 +00001671 .. attribute:: failures
1672
1673 A list containing 2-tuples of :class:`TestCase` instances and strings
1674 holding formatted tracebacks. Each tuple represents a test where a failure
1675 was explicitly signalled using the :meth:`TestCase.fail\*` or
1676 :meth:`TestCase.assert\*` methods.
1677
Benjamin Peterson52baa292009-03-24 00:56:30 +00001678 .. attribute:: skipped
1679
1680 A list containing 2-tuples of :class:`TestCase` instances and strings
1681 holding the reason for skipping the test.
1682
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001683 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001684
1685 .. attribute:: expectedFailures
1686
Georg Brandl6faee4e2010-09-21 14:48:28 +00001687 A list containing 2-tuples of :class:`TestCase` instances and strings
1688 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001689 of the test case.
1690
1691 .. attribute:: unexpectedSuccesses
1692
1693 A list containing :class:`TestCase` instances that were marked as expected
1694 failures, but succeeded.
1695
1696 .. attribute:: shouldStop
1697
1698 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1699
1700
1701 .. attribute:: testsRun
1702
1703 The total number of tests run so far.
1704
1705
Benjamin Petersonb48af542010-04-11 20:43:16 +00001706 .. attribute:: buffer
1707
1708 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1709 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1710 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1711 fails or errors. Any output is also attached to the failure / error message.
1712
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001713 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001714
1715
1716 .. attribute:: failfast
1717
1718 If set to true :meth:`stop` will be called on the first failure or error,
1719 halting the test run.
1720
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001721 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001722
1723
Benjamin Peterson52baa292009-03-24 00:56:30 +00001724 .. method:: wasSuccessful()
1725
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001726 Return ``True`` if all tests run so far have passed, otherwise returns
1727 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001728
1729
1730 .. method:: stop()
1731
1732 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001733 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001734 :class:`TestRunner` objects should respect this flag and return without
1735 running any additional tests.
1736
1737 For example, this feature is used by the :class:`TextTestRunner` class to
1738 stop the test framework when the user signals an interrupt from the
1739 keyboard. Interactive tools which provide :class:`TestRunner`
1740 implementations can use this in a similar manner.
1741
1742 The following methods of the :class:`TestResult` class are used to maintain
1743 the internal data structures, and may be extended in subclasses to support
1744 additional reporting requirements. This is particularly useful in building
1745 tools which support interactive reporting while tests are being run.
1746
1747
1748 .. method:: startTest(test)
1749
1750 Called when the test case *test* is about to be run.
1751
Benjamin Peterson52baa292009-03-24 00:56:30 +00001752 .. method:: stopTest(test)
1753
1754 Called after the test case *test* has been executed, regardless of the
1755 outcome.
1756
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001757 .. method:: startTestRun(test)
1758
1759 Called once before any tests are executed.
1760
Georg Brandl853947a2010-01-31 18:53:23 +00001761 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001762
1763
1764 .. method:: stopTestRun(test)
1765
Ezio Melotti176d6c42010-01-27 20:58:07 +00001766 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001767
Georg Brandl853947a2010-01-31 18:53:23 +00001768 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001769
1770
Benjamin Peterson52baa292009-03-24 00:56:30 +00001771 .. method:: addError(test, err)
1772
1773 Called when the test case *test* raises an unexpected exception *err* is a
1774 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1775 traceback)``.
1776
1777 The default implementation appends a tuple ``(test, formatted_err)`` to
1778 the instance's :attr:`errors` attribute, where *formatted_err* is a
1779 formatted traceback derived from *err*.
1780
1781
1782 .. method:: addFailure(test, err)
1783
Benjamin Petersond2397752009-06-27 23:45:02 +00001784 Called when the test case *test* signals a failure. *err* is a tuple of
1785 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001786
1787 The default implementation appends a tuple ``(test, formatted_err)`` to
1788 the instance's :attr:`failures` attribute, where *formatted_err* is a
1789 formatted traceback derived from *err*.
1790
1791
1792 .. method:: addSuccess(test)
1793
1794 Called when the test case *test* succeeds.
1795
1796 The default implementation does nothing.
1797
1798
1799 .. method:: addSkip(test, reason)
1800
1801 Called when the test case *test* is skipped. *reason* is the reason the
1802 test gave for skipping.
1803
1804 The default implementation appends a tuple ``(test, reason)`` to the
1805 instance's :attr:`skipped` attribute.
1806
1807
1808 .. method:: addExpectedFailure(test, err)
1809
1810 Called when the test case *test* fails, but was marked with the
1811 :func:`expectedFailure` decorator.
1812
1813 The default implementation appends a tuple ``(test, formatted_err)`` to
1814 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1815 is a formatted traceback derived from *err*.
1816
1817
1818 .. method:: addUnexpectedSuccess(test)
1819
1820 Called when the test case *test* was marked with the
1821 :func:`expectedFailure` decorator, but succeeded.
1822
1823 The default implementation appends the test to the instance's
1824 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001825
Georg Brandl67b21b72010-08-17 15:07:14 +00001826
Michael Foord34c94622010-02-10 15:51:42 +00001827.. class:: TextTestResult(stream, descriptions, verbosity)
1828
Georg Brandl67b21b72010-08-17 15:07:14 +00001829 A concrete implementation of :class:`TestResult` used by the
1830 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001831
Georg Brandl67b21b72010-08-17 15:07:14 +00001832 .. versionadded:: 3.2
1833 This class was previously named ``_TextTestResult``. The old name still
1834 exists as an alias but is deprecated.
1835
Georg Brandl116aa622007-08-15 14:28:22 +00001836
1837.. data:: defaultTestLoader
1838
1839 Instance of the :class:`TestLoader` class intended to be shared. If no
1840 customization of the :class:`TestLoader` is needed, this instance can be used
1841 instead of repeatedly creating new instances.
1842
1843
Michael Foord34c94622010-02-10 15:51:42 +00001844.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001845
1846 A basic test runner implementation which prints results on standard error. It
1847 has a few configurable parameters, but is essentially very simple. Graphical
1848 applications which run test suites should provide alternate implementations.
1849
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001850 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001851
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001852 This method returns the instance of ``TestResult`` used by :meth:`run`.
1853 It is not intended to be called directly, but can be overridden in
1854 subclasses to provide a custom ``TestResult``.
1855
Michael Foord34c94622010-02-10 15:51:42 +00001856 ``_makeResult()`` instantiates the class or callable passed in the
1857 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001858 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001859 The result class is instantiated with the following arguments::
1860
1861 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001862
Benjamin Petersonb48af542010-04-11 20:43:16 +00001863.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001864
1865 A command-line program that runs a set of tests; this is primarily for making
1866 test modules conveniently executable. The simplest use for this function is to
1867 include the following line at the end of a test script::
1868
1869 if __name__ == '__main__':
1870 unittest.main()
1871
Benjamin Petersond2397752009-06-27 23:45:02 +00001872 You can run tests with more detailed information by passing in the verbosity
1873 argument::
1874
1875 if __name__ == '__main__':
1876 unittest.main(verbosity=2)
1877
Georg Brandl116aa622007-08-15 14:28:22 +00001878 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001879 created instance of it. By default ``main`` calls :func:`sys.exit` with
1880 an exit code indicating success or failure of the tests run.
1881
1882 ``main`` supports being used from the interactive interpreter by passing in the
1883 argument ``exit=False``. This displays the result on standard output without
1884 calling :func:`sys.exit`::
1885
1886 >>> from unittest import main
1887 >>> main(module='test_module', exit=False)
1888
Benjamin Petersonb48af542010-04-11 20:43:16 +00001889 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
Éric Araujo713d3032010-11-18 16:38:46 +00001890 effect as the `failfast, catch and buffer command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001891
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001892 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1893 This stores the result of the tests run as the ``result`` attribute.
1894
Georg Brandl853947a2010-01-31 18:53:23 +00001895 .. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001896 The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
1897 parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001898
1899
1900load_tests Protocol
1901###################
1902
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001903
Georg Brandl853947a2010-01-31 18:53:23 +00001904.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001905
1906
Benjamin Petersond2397752009-06-27 23:45:02 +00001907Modules or packages can customize how tests are loaded from them during normal
1908test runs or test discovery by implementing a function called ``load_tests``.
1909
1910If a test module defines ``load_tests`` it will be called by
1911:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1912
1913 load_tests(loader, standard_tests, None)
1914
1915It should return a :class:`TestSuite`.
1916
1917*loader* is the instance of :class:`TestLoader` doing the loading.
1918*standard_tests* are the tests that would be loaded by default from the
1919module. It is common for test modules to only want to add or remove tests
1920from the standard set of tests.
1921The third argument is used when loading packages as part of test discovery.
1922
1923A typical ``load_tests`` function that loads tests from a specific set of
1924:class:`TestCase` classes may look like::
1925
1926 test_cases = (TestCase1, TestCase2, TestCase3)
1927
1928 def load_tests(loader, tests, pattern):
1929 suite = TestSuite()
1930 for test_class in test_cases:
1931 tests = loader.loadTestsFromTestCase(test_class)
1932 suite.addTests(tests)
1933 return suite
1934
1935If discovery is started, either from the command line or by calling
1936:meth:`TestLoader.discover`, with a pattern that matches a package
1937name then the package :file:`__init__.py` will be checked for ``load_tests``.
1938
1939.. note::
1940
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001941 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00001942 that start with 'test' but *won't* match any test directories.
1943
1944 A pattern like 'test*' will match test packages as well as
1945 modules.
1946
1947If the package :file:`__init__.py` defines ``load_tests`` then it will be
1948called and discovery not continued into the package. ``load_tests``
1949is called with the following arguments::
1950
1951 load_tests(loader, standard_tests, pattern)
1952
1953This should return a :class:`TestSuite` representing all the tests
1954from the package. (``standard_tests`` will only contain tests
1955collected from :file:`__init__.py`.)
1956
1957Because the pattern is passed into ``load_tests`` the package is free to
1958continue (and potentially modify) test discovery. A 'do nothing'
1959``load_tests`` function for a test package would look like::
1960
1961 def load_tests(loader, standard_tests, pattern):
1962 # top level directory cached on loader instance
1963 this_dir = os.path.dirname(__file__)
1964 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1965 standard_tests.addTests(package_tests)
1966 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00001967
1968
1969Class and Module Fixtures
1970-------------------------
1971
1972Class and module level fixtures are implemented in :class:`TestSuite`. When
1973the test suite encounters a test from a new class then :meth:`tearDownClass`
1974from the previous class (if there is one) is called, followed by
1975:meth:`setUpClass` from the new class.
1976
1977Similarly if a test is from a different module from the previous test then
1978``tearDownModule`` from the previous module is run, followed by
1979``setUpModule`` from the new module.
1980
1981After all the tests have run the final ``tearDownClass`` and
1982``tearDownModule`` are run.
1983
1984Note that shared fixtures do not play well with [potential] features like test
1985parallelization and they break test isolation. They should be used with care.
1986
1987The default ordering of tests created by the unittest test loaders is to group
1988all tests from the same modules and classes together. This will lead to
1989``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
1990module. If you randomize the order, so that tests from different modules and
1991classes are adjacent to each other, then these shared fixture functions may be
1992called multiple times in a single test run.
1993
1994Shared fixtures are not intended to work with suites with non-standard
1995ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
1996support shared fixtures.
1997
1998If there are any exceptions raised during one of the shared fixture functions
1999the test is reported as an error. Because there is no corresponding test
2000instance an ``_ErrorHolder`` object (that has the same interface as a
2001:class:`TestCase`) is created to represent the error. If you are just using
2002the standard unittest test runner then this detail doesn't matter, but if you
2003are a framework author it may be relevant.
2004
2005
2006setUpClass and tearDownClass
2007~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2008
2009These must be implemented as class methods::
2010
2011 import unittest
2012
2013 class Test(unittest.TestCase):
2014 @classmethod
2015 def setUpClass(cls):
2016 cls._connection = createExpensiveConnectionObject()
2017
2018 @classmethod
2019 def tearDownClass(cls):
2020 cls._connection.destroy()
2021
2022If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2023then you must call up to them yourself. The implementations in
2024:class:`TestCase` are empty.
2025
2026If an exception is raised during a ``setUpClass`` then the tests in the class
2027are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002028have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
2029``SkipTest`` exception then the class will be reported as having been skipped
2030instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002031
2032
2033setUpModule and tearDownModule
2034~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2035
2036These should be implemented as functions::
2037
2038 def setUpModule():
2039 createConnection()
2040
2041 def tearDownModule():
2042 closeConnection()
2043
2044If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002045module will be run and the ``tearDownModule`` will not be run. If the exception is a
2046``SkipTest`` exception then the module will be reported as having been skipped
2047instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002048
2049
2050Signal Handling
2051---------------
2052
Éric Araujod3309df2010-11-21 03:09:17 +00002053The ``-c``/``--catch`` command-line option to unittest, along with the ``catchbreak``
Benjamin Petersonb48af542010-04-11 20:43:16 +00002054parameter to :func:`unittest.main()`, provide more friendly handling of
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002055control-C during a test run. With catch break behavior enabled control-C will
Benjamin Petersonb48af542010-04-11 20:43:16 +00002056allow the currently running test to complete, and the test run will then end
2057and report all the results so far. A second control-c will raise a
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002058:exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002059
Michael Foordde4ceab2010-04-25 19:53:49 +00002060The control-c handling signal handler attempts to remain compatible with code or
2061tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2062handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2063i.e. it has been replaced by the system under test and delegated to, then it
2064calls the default handler. This will normally be the expected behavior by code
2065that replaces an installed handler and delegates to it. For individual tests
2066that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2067decorator can be used.
2068
2069There are a few utility functions for framework authors to enable control-c
2070handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002071
2072.. function:: installHandler()
2073
2074 Install the control-c handler. When a :const:`signal.SIGINT` is received
2075 (usually in response to the user pressing control-c) all registered results
2076 have :meth:`~TestResult.stop` called.
2077
Michael Foord469b1f02010-04-26 23:41:26 +00002078 .. versionadded:: 3.2
2079
Benjamin Petersonb48af542010-04-11 20:43:16 +00002080.. function:: registerResult(result)
2081
2082 Register a :class:`TestResult` object for control-c handling. Registering a
2083 result stores a weak reference to it, so it doesn't prevent the result from
2084 being garbage collected.
2085
Michael Foordde4ceab2010-04-25 19:53:49 +00002086 Registering a :class:`TestResult` object has no side-effects if control-c
2087 handling is not enabled, so test frameworks can unconditionally register
2088 all results they create independently of whether or not handling is enabled.
2089
Michael Foord469b1f02010-04-26 23:41:26 +00002090 .. versionadded:: 3.2
2091
Benjamin Petersonb48af542010-04-11 20:43:16 +00002092.. function:: removeResult(result)
2093
2094 Remove a registered result. Once a result has been removed then
2095 :meth:`~TestResult.stop` will no longer be called on that result object in
2096 response to a control-c.
2097
Michael Foord469b1f02010-04-26 23:41:26 +00002098 .. versionadded:: 3.2
2099
Michael Foordde4ceab2010-04-25 19:53:49 +00002100.. function:: removeHandler(function=None)
2101
2102 When called without arguments this function removes the control-c handler
2103 if it has been installed. This function can also be used as a test decorator
2104 to temporarily remove the handler whilst the test is being executed::
2105
2106 @unittest.removeHandler
2107 def test_signal_handling(self):
2108 ...
2109
Michael Foord469b1f02010-04-26 23:41:26 +00002110 .. versionadded:: 3.2
2111