blob: 2c822058ba854482c59345bb9ec22ac0f86156f4 [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
Éric Araujo713d3032010-11-18 16:38:46 +0000211For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000212
213 python -m unittest -h
214
Georg Brandl67b21b72010-08-17 15:07:14 +0000215.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000216 In earlier versions it was only possible to run individual test methods and
217 not modules or classes.
218
219
Éric Araujo713d3032010-11-18 16:38:46 +0000220failfast, catch and buffer command-line options
Benjamin Petersonb48af542010-04-11 20:43:16 +0000221~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
222
Éric Araujo713d3032010-11-18 16:38:46 +0000223:program:`unittest` supports three command-line options.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000224
Éric Araujo713d3032010-11-18 16:38:46 +0000225.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000226
Éric Araujo713d3032010-11-18 16:38:46 +0000227.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000228
Éric Araujo713d3032010-11-18 16:38:46 +0000229 The standard output and standard error streams are buffered during the test
230 run. Output during a passing test is discarded. Output is echoed normally
231 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000232
Éric Araujo713d3032010-11-18 16:38:46 +0000233.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000234
Éric Araujo713d3032010-11-18 16:38:46 +0000235 Control-C during the test run waits for the current test to end and then
236 reports all the results so far. A second control-C raises the normal
237 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000238
Éric Araujo713d3032010-11-18 16:38:46 +0000239 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000240
Éric Araujo713d3032010-11-18 16:38:46 +0000241.. cmdoption:: -f, --failfast
242
243 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000244
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000245.. versionadded:: 3.2
Éric Araujo713d3032010-11-18 16:38:46 +0000246 The command-line options :option:`-c`, :option:`-b` and :option:`-f` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000247
248The command line can also be used for test discovery, for running all of the
249tests in a project or just a subset.
250
251
252.. _unittest-test-discovery:
253
254Test Discovery
255--------------
256
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000257.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000258
259Unittest supports simple test discovery. For a project's tests to be
260compatible with test discovery they must all be importable from the top level
261directory of the project (in other words, they must all be in Python packages).
262
263Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000264used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000265
266 cd project_directory
267 python -m unittest discover
268
269The ``discover`` sub-command has the following options:
270
Éric Araujo713d3032010-11-18 16:38:46 +0000271.. program:: unittest discover
272
273.. cmdoption:: -v, --verbose
274
275 Verbose output
276
277.. cmdoption:: -s directory
278
279 Directory to start discovery ('.' default)
280
281.. cmdoption:: -p pattern
282
283 Pattern to match test files ('test*.py' default)
284
285.. cmdoption:: -t directory
286
287 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000288
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000289The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
290as positional arguments in that order. The following two command lines
291are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000292
293 python -m unittest discover -s project_directory -p '*_test.py'
294 python -m unittest discover project_directory '*_test.py'
295
Michael Foord16f3e902010-05-08 15:13:42 +0000296As well as being a path it is possible to pass a package name, for example
297``myproject.subpackage.test``, as the start directory. The package name you
298supply will then be imported and its location on the filesystem will be used
299as the start directory.
300
301.. caution::
302
Senthil Kumaran916bd382010-10-15 12:55:19 +0000303 Test discovery loads tests by importing them. Once test discovery has found
304 all the test files from the start directory you specify it turns the paths
305 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000306 imported as ``foo.bar.baz``.
307
308 If you have a package installed globally and attempt test discovery on
309 a different copy of the package then the import *could* happen from the
310 wrong place. If this happens test discovery will warn you and exit.
311
312 If you supply the start directory as a package name rather than a
313 path to a directory then discover assumes that whichever location it
314 imports from is the location you intended, so you will not get the
315 warning.
316
Benjamin Petersonb48af542010-04-11 20:43:16 +0000317Test modules and packages can customize test loading and discovery by through
318the `load_tests protocol`_.
319
320
Georg Brandl116aa622007-08-15 14:28:22 +0000321.. _organizing-tests:
322
323Organizing test code
324--------------------
325
326The basic building blocks of unit testing are :dfn:`test cases` --- single
327scenarios that must be set up and checked for correctness. In :mod:`unittest`,
328test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
329class. To make your own test cases you must write subclasses of
330:class:`TestCase`, or use :class:`FunctionTestCase`.
331
332An instance of a :class:`TestCase`\ -derived class is an object that can
333completely run a single test method, together with optional set-up and tidy-up
334code.
335
336The testing code of a :class:`TestCase` instance should be entirely self
337contained, such that it can be run either in isolation or in arbitrary
338combination with any number of other test cases.
339
Benjamin Peterson52baa292009-03-24 00:56:30 +0000340The simplest :class:`TestCase` subclass will simply override the
341:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343 import unittest
344
345 class DefaultWidgetSizeTestCase(unittest.TestCase):
346 def runTest(self):
347 widget = Widget('The widget')
348 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
349
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000350Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000351methods provided by the :class:`TestCase` base class. If the test fails, an
352exception will be raised, and :mod:`unittest` will identify the test case as a
353:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
354helps you identify where the problem is: :dfn:`failures` are caused by incorrect
355results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
356code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000357
358The way to run a test case will be described later. For now, note that to
359construct an instance of such a test case, we call its constructor without
360arguments::
361
362 testCase = DefaultWidgetSizeTestCase()
363
364Now, such test cases can be numerous, and their set-up can be repetitive. In
365the above case, constructing a :class:`Widget` in each of 100 Widget test case
366subclasses would mean unsightly duplication.
367
368Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000369:meth:`~TestCase.setUp`, which the testing framework will automatically call for
370us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372 import unittest
373
374 class SimpleWidgetTestCase(unittest.TestCase):
375 def setUp(self):
376 self.widget = Widget('The widget')
377
378 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
379 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000380 self.assertEqual(self.widget.size(), (50,50),
381 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383 class WidgetResizeTestCase(SimpleWidgetTestCase):
384 def runTest(self):
385 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000386 self.assertEqual(self.widget.size(), (100,150),
387 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Benjamin Peterson52baa292009-03-24 00:56:30 +0000389If the :meth:`~TestCase.setUp` method raises an exception while the test is
390running, the framework will consider the test to have suffered an error, and the
391:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000392
Benjamin Peterson52baa292009-03-24 00:56:30 +0000393Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
394after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396 import unittest
397
398 class SimpleWidgetTestCase(unittest.TestCase):
399 def setUp(self):
400 self.widget = Widget('The widget')
401
402 def tearDown(self):
403 self.widget.dispose()
404 self.widget = None
405
Benjamin Peterson52baa292009-03-24 00:56:30 +0000406If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
407be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000408
409Such a working environment for the testing code is called a :dfn:`fixture`.
410
411Often, many small test cases will use the same fixture. In this case, we would
412end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
413classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000414discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
415mechanism::
416
417 import unittest
418
419 class WidgetTestCase(unittest.TestCase):
420 def setUp(self):
421 self.widget = Widget('The widget')
422
423 def tearDown(self):
424 self.widget.dispose()
425 self.widget = None
426
Ezio Melottid59e44a2010-02-28 03:46:13 +0000427 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000428 self.assertEqual(self.widget.size(), (50,50),
429 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Ezio Melottid59e44a2010-02-28 03:46:13 +0000431 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000432 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000433 self.assertEqual(self.widget.size(), (100,150),
434 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Benjamin Peterson52baa292009-03-24 00:56:30 +0000436Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
437provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000438the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000439separately for each instance. When creating an instance we must specify the
440test method it is to run. We do this by passing the method name in the
441constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000442
Ezio Melottid59e44a2010-02-28 03:46:13 +0000443 defaultSizeTestCase = WidgetTestCase('test_default_size')
444 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000445
446Test case instances are grouped together according to the features they test.
447:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
448represented by :mod:`unittest`'s :class:`TestSuite` class::
449
450 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000451 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
452 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000453
454For the ease of running tests, as we will see later, it is a good idea to
455provide in each test module a callable object that returns a pre-built test
456suite::
457
458 def suite():
459 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000460 suite.addTest(WidgetTestCase('test_default_size'))
461 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000462 return suite
463
464or even::
465
466 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000467 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000468
469 return unittest.TestSuite(map(WidgetTestCase, tests))
470
471Since it is a common pattern to create a :class:`TestCase` subclass with many
472similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
473class that can be used to automate the process of creating a test suite and
474populating it with individual tests. For example, ::
475
476 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
477
Ezio Melottid59e44a2010-02-28 03:46:13 +0000478will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
479``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000480name prefix to identify test methods automatically.
481
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000482Note that the order in which the various test cases will be run is
483determined by sorting the test function names with respect to the
484built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000485
486Often it is desirable to group suites of test cases together, so as to run tests
487for the whole system at once. This is easy, since :class:`TestSuite` instances
488can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
489added to a :class:`TestSuite`::
490
491 suite1 = module1.TheTestSuite()
492 suite2 = module2.TheTestSuite()
493 alltests = unittest.TestSuite([suite1, suite2])
494
495You can place the definitions of test cases and test suites in the same modules
496as the code they are to test (such as :file:`widget.py`), but there are several
497advantages to placing the test code in a separate module, such as
498:file:`test_widget.py`:
499
500* The test module can be run standalone from the command line.
501
502* The test code can more easily be separated from shipped code.
503
504* There is less temptation to change test code to fit the code it tests without
505 a good reason.
506
507* Test code should be modified much less frequently than the code it tests.
508
509* Tested code can be refactored more easily.
510
511* Tests for modules written in C must be in separate modules anyway, so why not
512 be consistent?
513
514* If the testing strategy changes, there is no need to change the source code.
515
516
517.. _legacy-unit-tests:
518
519Re-using old test code
520----------------------
521
522Some users will find that they have existing test code that they would like to
523run from :mod:`unittest`, without converting every old test function to a
524:class:`TestCase` subclass.
525
526For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
527This subclass of :class:`TestCase` can be used to wrap an existing test
528function. Set-up and tear-down functions can also be provided.
529
530Given the following test function::
531
532 def testSomething():
533 something = makeSomething()
534 assert something.name is not None
535 # ...
536
537one can create an equivalent test case instance as follows::
538
539 testcase = unittest.FunctionTestCase(testSomething)
540
541If there are additional set-up and tear-down methods that should be called as
542part of the test case's operation, they can also be provided like so::
543
544 testcase = unittest.FunctionTestCase(testSomething,
545 setUp=makeSomethingDB,
546 tearDown=deleteSomethingDB)
547
548To make migrating existing test suites easier, :mod:`unittest` supports tests
549raising :exc:`AssertionError` to indicate test failure. However, it is
550recommended that you use the explicit :meth:`TestCase.fail\*` and
551:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
552may treat :exc:`AssertionError` differently.
553
554.. note::
555
Benjamin Petersond2397752009-06-27 23:45:02 +0000556 Even though :class:`FunctionTestCase` can be used to quickly convert an
557 existing test base over to a :mod:`unittest`\ -based system, this approach is
558 not recommended. Taking the time to set up proper :class:`TestCase`
559 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000560
Benjamin Peterson52baa292009-03-24 00:56:30 +0000561In some cases, the existing tests may have been written using the :mod:`doctest`
562module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
563automatically build :class:`unittest.TestSuite` instances from the existing
564:mod:`doctest`\ -based tests.
565
Georg Brandl116aa622007-08-15 14:28:22 +0000566
Benjamin Peterson5254c042009-03-23 22:25:03 +0000567.. _unittest-skipping:
568
569Skipping tests and expected failures
570------------------------------------
571
Michael Foordf5c851a2010-02-05 21:48:03 +0000572.. versionadded:: 3.1
573
Benjamin Peterson5254c042009-03-23 22:25:03 +0000574Unittest supports skipping individual test methods and even whole classes of
575tests. In addition, it supports marking a test as a "expected failure," a test
576that is broken and will fail, but shouldn't be counted as a failure on a
577:class:`TestResult`.
578
579Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
580or one of its conditional variants.
581
582Basic skipping looks like this: ::
583
584 class MyTestCase(unittest.TestCase):
585
586 @unittest.skip("demonstrating skipping")
587 def test_nothing(self):
588 self.fail("shouldn't happen")
589
Benjamin Petersond2397752009-06-27 23:45:02 +0000590 @unittest.skipIf(mylib.__version__ < (1, 3),
591 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000592 def test_format(self):
593 # Tests that work for only a certain version of the library.
594 pass
595
596 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
597 def test_windows_support(self):
598 # windows specific testing code
599 pass
600
Benjamin Peterson5254c042009-03-23 22:25:03 +0000601This is the output of running the example above in verbose mode: ::
602
Benjamin Petersonded31c42009-03-30 15:04:16 +0000603 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000604 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000605 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000606
607 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000608 Ran 3 tests in 0.005s
609
610 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000611
612Classes can be skipped just like methods: ::
613
614 @skip("showing class skipping")
615 class MySkippedTestCase(unittest.TestCase):
616 def test_not_run(self):
617 pass
618
Benjamin Peterson52baa292009-03-24 00:56:30 +0000619:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
620that needs to be set up is not available.
621
Benjamin Peterson5254c042009-03-23 22:25:03 +0000622Expected failures use the :func:`expectedFailure` decorator. ::
623
624 class ExpectedFailureTestCase(unittest.TestCase):
625 @unittest.expectedFailure
626 def test_fail(self):
627 self.assertEqual(1, 0, "broken")
628
629It's easy to roll your own skipping decorators by making a decorator that calls
630:func:`skip` on the test when it wants it to be skipped. This decorator skips
631the test unless the passed object has a certain attribute: ::
632
633 def skipUnlessHasattr(obj, attr):
634 if hasattr(obj, attr):
635 return lambda func: func
636 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
637
638The following decorators implement test skipping and expected failures:
639
Georg Brandl8a1caa22010-07-29 16:01:11 +0000640.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000641
642 Unconditionally skip the decorated test. *reason* should describe why the
643 test is being skipped.
644
Georg Brandl8a1caa22010-07-29 16:01:11 +0000645.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000646
647 Skip the decorated test if *condition* is true.
648
Georg Brandl8a1caa22010-07-29 16:01:11 +0000649.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000650
Georg Brandl6faee4e2010-09-21 14:48:28 +0000651 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000652
Georg Brandl8a1caa22010-07-29 16:01:11 +0000653.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000654
655 Mark the test as an expected failure. If the test fails when run, the test
656 is not counted as a failure.
657
Benjamin Petersonb48af542010-04-11 20:43:16 +0000658Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
659Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
660
Benjamin Peterson5254c042009-03-23 22:25:03 +0000661
Georg Brandl116aa622007-08-15 14:28:22 +0000662.. _unittest-contents:
663
664Classes and functions
665---------------------
666
Benjamin Peterson52baa292009-03-24 00:56:30 +0000667This section describes in depth the API of :mod:`unittest`.
668
669
670.. _testcase-objects:
671
672Test cases
673~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000674
Georg Brandl7f01a132009-09-16 15:58:14 +0000675.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000676
677 Instances of the :class:`TestCase` class represent the smallest testable units
678 in the :mod:`unittest` universe. This class is intended to be used as a base
679 class, with specific tests being implemented by concrete subclasses. This class
680 implements the interface needed by the test runner to allow it to drive the
681 test, and methods that the test code can use to check for and report various
682 kinds of failure.
683
684 Each instance of :class:`TestCase` will run a single test method: the method
685 named *methodName*. If you remember, we had an earlier example that went
686 something like this::
687
688 def suite():
689 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000690 suite.addTest(WidgetTestCase('test_default_size'))
691 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000692 return suite
693
694 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
695 single test.
696
Benjamin Peterson52baa292009-03-24 00:56:30 +0000697 *methodName* defaults to :meth:`runTest`.
698
699 :class:`TestCase` instances provide three groups of methods: one group used
700 to run the test, another used by the test implementation to check conditions
701 and report failures, and some inquiry methods allowing information about the
702 test itself to be gathered.
703
704 Methods in the first group (running the test) are:
705
706
707 .. method:: setUp()
708
709 Method called to prepare the test fixture. This is called immediately
710 before calling the test method; any exception raised by this method will
711 be considered an error rather than a test failure. The default
712 implementation does nothing.
713
714
715 .. method:: tearDown()
716
717 Method called immediately after the test method has been called and the
718 result recorded. This is called even if the test method raised an
719 exception, so the implementation in subclasses may need to be particularly
720 careful about checking internal state. Any exception raised by this
721 method will be considered an error rather than a test failure. This
722 method will only be called if the :meth:`setUp` succeeds, regardless of
723 the outcome of the test method. The default implementation does nothing.
724
725
Benjamin Petersonb48af542010-04-11 20:43:16 +0000726 .. method:: setUpClass()
727
728 A class method called before tests in an individual class run.
729 ``setUpClass`` is called with the class as the only argument
730 and must be decorated as a :func:`classmethod`::
731
732 @classmethod
733 def setUpClass(cls):
734 ...
735
736 See `Class and Module Fixtures`_ for more details.
737
738 .. versionadded:: 3.2
739
740
741 .. method:: tearDownClass()
742
743 A class method called after tests in an individual class have run.
744 ``tearDownClass`` is called with the class as the only argument
745 and must be decorated as a :meth:`classmethod`::
746
747 @classmethod
748 def tearDownClass(cls):
749 ...
750
751 See `Class and Module Fixtures`_ for more details.
752
753 .. versionadded:: 3.2
754
755
Georg Brandl7f01a132009-09-16 15:58:14 +0000756 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000757
758 Run the test, collecting the result into the test result object passed as
Ezio Melotti75b2a5e2010-11-20 10:13:45 +0000759 *result*. If *result* is omitted or ``None``, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000760 object is created (by calling the :meth:`defaultTestResult` method) and
761 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000762
763 The same effect may be had by simply calling the :class:`TestCase`
764 instance.
765
766
Benjamin Petersone549ead2009-03-28 21:42:05 +0000767 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000768
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000769 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000770 test. See :ref:`unittest-skipping` for more information.
771
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000772 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000773
Benjamin Peterson52baa292009-03-24 00:56:30 +0000774
775 .. method:: debug()
776
777 Run the test without collecting the result. This allows exceptions raised
778 by the test to be propagated to the caller, and can be used to support
779 running tests under a debugger.
780
Ezio Melotti22170ed2010-11-20 09:57:27 +0000781 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000782
Ezio Melotti4370b302010-11-03 20:39:14 +0000783 The :class:`TestCase` class provides a number of methods to check for and
784 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000785
Ezio Melotti4370b302010-11-03 20:39:14 +0000786 +-----------------------------------------+-----------------------------+---------------+
787 | Method | Checks that | New in |
788 +=========================================+=============================+===============+
789 | :meth:`assertEqual(a, b) | ``a == b`` | |
790 | <TestCase.assertEqual>` | | |
791 +-----------------------------------------+-----------------------------+---------------+
792 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
793 | <TestCase.assertNotEqual>` | | |
794 +-----------------------------------------+-----------------------------+---------------+
795 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
796 | <TestCase.assertTrue>` | | |
797 +-----------------------------------------+-----------------------------+---------------+
798 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
799 | <TestCase.assertFalse>` | | |
800 +-----------------------------------------+-----------------------------+---------------+
801 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
802 | <TestCase.assertIs>` | | |
803 +-----------------------------------------+-----------------------------+---------------+
804 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
805 | <TestCase.assertIsNot>` | | |
806 +-----------------------------------------+-----------------------------+---------------+
807 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
808 | <TestCase.assertIsNone>` | | |
809 +-----------------------------------------+-----------------------------+---------------+
810 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
811 | <TestCase.assertIsNotNone>` | | |
812 +-----------------------------------------+-----------------------------+---------------+
813 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
814 | <TestCase.assertIn>` | | |
815 +-----------------------------------------+-----------------------------+---------------+
816 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
817 | <TestCase.assertNotIn>` | | |
818 +-----------------------------------------+-----------------------------+---------------+
819 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
820 | <TestCase.assertIsInstance>` | | |
821 +-----------------------------------------+-----------------------------+---------------+
822 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
823 | <TestCase.assertNotIsInstance>` | | |
824 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000825
Ezio Melotti22170ed2010-11-20 09:57:27 +0000826 All the assert methods (except :meth:`assertRaises`,
827 :meth:`assertRaisesRegexp`, :meth:`assertWarns`, :meth:`assertWarnsRegexp`)
828 accept a *msg* argument that, if specified, is used as the error message on
829 failure (see also :data:`longMessage`).
Benjamin Peterson52baa292009-03-24 00:56:30 +0000830
Georg Brandl7f01a132009-09-16 15:58:14 +0000831 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000832
833 Test that *first* and *second* are equal. If the values do not compare
Ezio Melotti4841fd62010-11-05 15:43:40 +0000834 equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000835
836 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000837 list, tuple, dict, set, frozenset or str or any type that a subclass
838 registers with :meth:`addTypeEqualityFunc` the type specific equality
839 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000840 error message (see also the :ref:`list of type-specific methods
841 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000842
Raymond Hettinger35a88362009-04-09 00:08:24 +0000843 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000844 Added the automatic calling of type specific equality function.
845
Michael Foord28a817e2010-02-09 00:03:57 +0000846 .. versionchanged:: 3.2
847 :meth:`assertMultiLineEqual` added as the default type equality
848 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000849
Benjamin Peterson52baa292009-03-24 00:56:30 +0000850
Georg Brandl7f01a132009-09-16 15:58:14 +0000851 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000852
853 Test that *first* and *second* are not equal. If the values do compare
Ezio Melotti4841fd62010-11-05 15:43:40 +0000854 equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000855
Ezio Melotti4370b302010-11-03 20:39:14 +0000856 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000857 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000858
Ezio Melotti4841fd62010-11-05 15:43:40 +0000859 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000860
Ezio Melotti4841fd62010-11-05 15:43:40 +0000861 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
862 is True`` (use ``assertIs(expr, True)`` for the latter). This method
863 should also be avoided when more specific methods are available (e.g.
864 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
865 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000866
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000867
Ezio Melotti9794a262010-11-04 14:52:13 +0000868 .. method:: assertIs(first, second, msg=None)
869 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000870
Ezio Melotti9794a262010-11-04 14:52:13 +0000871 Test that *first* and *second* evaluate (or don't evaluate) to the same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000872
Raymond Hettinger35a88362009-04-09 00:08:24 +0000873 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000874
875
Ezio Melotti4370b302010-11-03 20:39:14 +0000876 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000877 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000878
Ezio Melotti9794a262010-11-04 14:52:13 +0000879 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000880
Ezio Melotti4370b302010-11-03 20:39:14 +0000881 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000882
883
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000884 .. method:: assertIn(first, second, msg=None)
885 assertNotIn(first, second, msg=None)
886
Ezio Melotti4841fd62010-11-05 15:43:40 +0000887 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000888
Raymond Hettinger35a88362009-04-09 00:08:24 +0000889 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000890
891
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000892 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000893 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000894
Ezio Melotti9794a262010-11-04 14:52:13 +0000895 Test that *obj* is (or is not) an instance of *cls* (which can be a
896 class or a tuple of classes, as supported by :func:`isinstance`).
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000897
Ezio Melotti4370b302010-11-03 20:39:14 +0000898 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000899
900
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000901
Ezio Melotti4370b302010-11-03 20:39:14 +0000902 It is also possible to check that exceptions and warnings are raised using
903 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000904
Ezio Melotti4370b302010-11-03 20:39:14 +0000905 +---------------------------------------------------------+--------------------------------------+------------+
906 | Method | Checks that | New in |
907 +=========================================================+======================================+============+
908 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | |
909 | <TestCase.assertRaises>` | | |
910 +---------------------------------------------------------+--------------------------------------+------------+
911 | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
912 | <TestCase.assertRaisesRegexp>` | and the message matches `re` | |
913 +---------------------------------------------------------+--------------------------------------+------------+
914 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
915 | <TestCase.assertWarns>` | | |
916 +---------------------------------------------------------+--------------------------------------+------------+
917 | :meth:`assertWarnsRegexp(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
918 | <TestCase.assertWarnsRegexp>` | and the message matches `re` | |
919 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000920
Georg Brandl7f01a132009-09-16 15:58:14 +0000921 .. method:: assertRaises(exception, callable, *args, **kwds)
Georg Brandl7f01a132009-09-16 15:58:14 +0000922 assertRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000923
924 Test that an exception is raised when *callable* is called with any
925 positional or keyword arguments that are also passed to
926 :meth:`assertRaises`. The test passes if *exception* is raised, is an
927 error if another exception is raised, or fails if no exception is raised.
928 To catch any of a group of exceptions, a tuple containing the exception
929 classes may be passed as *exception*.
930
Georg Brandl7f01a132009-09-16 15:58:14 +0000931 If only the *exception* argument is given, returns a context manager so
932 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000933
Michael Foord41531f22010-02-05 21:13:40 +0000934 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000935 do_something()
936
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000937 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000938 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000939 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000940
Georg Brandl8a1caa22010-07-29 16:01:11 +0000941 with self.assertRaises(SomeException) as cm:
942 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000943
Georg Brandl8a1caa22010-07-29 16:01:11 +0000944 the_exception = cm.exception
945 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000946
Ezio Melotti49008232010-02-08 21:57:48 +0000947 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000948 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000949
Ezio Melotti49008232010-02-08 21:57:48 +0000950 .. versionchanged:: 3.2
951 Added the :attr:`exception` attribute.
952
Benjamin Peterson52baa292009-03-24 00:56:30 +0000953
Ezio Melotti327433f2010-11-03 20:51:17 +0000954 .. method:: assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
955 assertRaisesRegexp(exception, regexp)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000956
957 Like :meth:`assertRaises` but also tests that *regexp* matches
958 on the string representation of the raised exception. *regexp* may be
959 a regular expression object or a string containing a regular expression
960 suitable for use by :func:`re.search`. Examples::
961
962 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
963 int, 'XYZ')
964
965 or::
966
967 with self.assertRaisesRegexp(ValueError, 'literal'):
968 int('XYZ')
969
Raymond Hettinger35a88362009-04-09 00:08:24 +0000970 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000971
972
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000973 .. method:: assertWarns(warning, callable, *args, **kwds)
974 assertWarns(warning)
975
976 Test that a warning is triggered when *callable* is called with any
977 positional or keyword arguments that are also passed to
978 :meth:`assertWarns`. The test passes if *warning* is triggered and
979 fails if it isn't. Also, any unexpected exception is an error.
980 To catch any of a group of warnings, a tuple containing the warning
981 classes may be passed as *warnings*.
982
983 If only the *warning* argument is given, returns a context manager so
984 that the code under test can be written inline rather than as a function::
985
986 with self.assertWarns(SomeWarning):
987 do_something()
988
989 The context manager will store the caught warning object in its
990 :attr:`warning` attribute, and the source line which triggered the
991 warnings in the :attr:`filename` and :attr:`lineno` attributes.
992 This can be useful if the intention is to perform additional checks
993 on the exception raised::
994
995 with self.assertWarns(SomeWarning) as cm:
996 do_something()
997
998 self.assertIn('myfile.py', cm.filename)
999 self.assertEqual(320, cm.lineno)
1000
1001 This method works regardless of the warning filters in place when it
1002 is called.
1003
1004 .. versionadded:: 3.2
1005
1006
Ezio Melotti327433f2010-11-03 20:51:17 +00001007 .. method:: assertWarnsRegexp(warning, regexp, callable, *args, **kwds)
1008 assertWarnsRegexp(warning, regexp)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001009
1010 Like :meth:`assertWarns` but also tests that *regexp* matches on the
1011 message of the triggered warning. *regexp* may be a regular expression
1012 object or a string containing a regular expression suitable for use
1013 by :func:`re.search`. Example::
1014
1015 self.assertWarnsRegexp(DeprecationWarning,
1016 r'legacy_function\(\) is deprecated',
1017 legacy_function, 'XYZ')
1018
1019 or::
1020
1021 with self.assertWarnsRegexp(RuntimeWarning, 'unsafe frobnicating'):
1022 frobnicate('/etc/passwd')
1023
1024 .. versionadded:: 3.2
1025
1026
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001027
Ezio Melotti4370b302010-11-03 20:39:14 +00001028 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001029
Ezio Melotti4370b302010-11-03 20:39:14 +00001030 +---------------------------------------+--------------------------------+--------------+
1031 | Method | Checks that | New in |
1032 +=======================================+================================+==============+
1033 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1034 | <TestCase.assertAlmostEqual>` | | |
1035 +---------------------------------------+--------------------------------+--------------+
1036 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1037 | <TestCase.assertNotAlmostEqual>` | | |
1038 +---------------------------------------+--------------------------------+--------------+
1039 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1040 | <TestCase.assertGreater>` | | |
1041 +---------------------------------------+--------------------------------+--------------+
1042 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1043 | <TestCase.assertGreaterEqual>` | | |
1044 +---------------------------------------+--------------------------------+--------------+
1045 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1046 | <TestCase.assertLess>` | | |
1047 +---------------------------------------+--------------------------------+--------------+
1048 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1049 | <TestCase.assertLessEqual>` | | |
1050 +---------------------------------------+--------------------------------+--------------+
1051 | :meth:`assertRegexpMatches(s, re) | ``regex.search(s)`` | 3.1 |
1052 | <TestCase.assertRegexpMatches>` | | |
1053 +---------------------------------------+--------------------------------+--------------+
1054 | :meth:`assertNotRegexpMatches(s, re) | ``not regex.search(s)`` | 3.2 |
1055 | <TestCase.assertNotRegexpMatches>` | | |
1056 +---------------------------------------+--------------------------------+--------------+
1057 | :meth:`assertDictContainsSubset(a, b) | all the key/value pairs | 3.1 |
1058 | <TestCase.assertDictContainsSubset>` | in `a` exist in `b` | |
1059 +---------------------------------------+--------------------------------+--------------+
1060 | :meth:`assertItemsEqual(a, b) | `a` and `b` have the same | 3.2 |
1061 | <TestCase.assertItemsEqual>` | elements in the same number, | |
1062 | | regardless of their order | |
1063 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001064
1065
Ezio Melotti4370b302010-11-03 20:39:14 +00001066 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001067 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001068
Ezio Melotti4841fd62010-11-05 15:43:40 +00001069 Test that *first* and *second* are approximately (or not approximately)
1070 equal by computing the difference, rounding to the given number of
1071 decimal *places* (default 7), and comparing to zero. Note that these
1072 methods round the values to the given number of *decimal places* (i.e.
1073 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001074
Ezio Melotti4370b302010-11-03 20:39:14 +00001075 If *delta* is supplied instead of *places* then the difference
Ezio Melotti4841fd62010-11-05 15:43:40 +00001076 between *first* and *second* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001077
Ezio Melotti4370b302010-11-03 20:39:14 +00001078 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001079
Ezio Melotti4370b302010-11-03 20:39:14 +00001080 .. versionchanged:: 3.2
Ezio Melotti4841fd62010-11-05 15:43:40 +00001081 assertAlmostEqual automatically considers almost equal objects that compare equal.
1082 assertNotAlmostEqual automatically fails if the objects compare equal.
Ezio Melotti4370b302010-11-03 20:39:14 +00001083 Added the ``delta`` keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001084
Ezio Melotti4370b302010-11-03 20:39:14 +00001085
Ezio Melotti4370b302010-11-03 20:39:14 +00001086 .. method:: assertGreater(first, second, msg=None)
1087 assertGreaterEqual(first, second, msg=None)
1088 assertLess(first, second, msg=None)
1089 assertLessEqual(first, second, msg=None)
1090
1091 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001092 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001093
1094 >>> self.assertGreaterEqual(3, 4)
1095 AssertionError: "3" unexpectedly not greater than or equal to "4"
1096
1097 .. versionadded:: 3.1
1098
1099
1100 .. method:: assertRegexpMatches(text, regexp, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001101 assertNotRegexpMatches(text, regexp, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001102
Ezio Melotti4841fd62010-11-05 15:43:40 +00001103 Test that a *regexp* search matches (or does not match) *text*. In case
1104 of failure, the error message will include the pattern and the *text* (or
1105 the pattern and the part of *text* that unexpectedly matched). *regexp*
Ezio Melotti4370b302010-11-03 20:39:14 +00001106 may be a regular expression object or a string containing a regular
1107 expression suitable for use by :func:`re.search`.
1108
Ezio Melotti4841fd62010-11-05 15:43:40 +00001109 .. versionadded:: 3.1 :meth:`~TestCase.assertRegexpMatches`
1110 .. versionadded:: 3.2 :meth:`~TestCase.assertNotRegexpMatches`
Ezio Melotti4370b302010-11-03 20:39:14 +00001111
1112
1113 .. method:: assertDictContainsSubset(expected, actual, msg=None)
1114
1115 Tests whether the key/value pairs in dictionary *actual* are a
1116 superset of those in *expected*. If not, an error message listing
1117 the missing keys and mismatched values is generated.
1118
Ezio Melotti4370b302010-11-03 20:39:14 +00001119 .. versionadded:: 3.1
1120
1121
1122 .. method:: assertItemsEqual(actual, expected, msg=None)
1123
1124 Test that sequence *expected* contains the same elements as *actual*,
1125 regardless of their order. When they don't, an error message listing the
1126 differences between the sequences will be generated.
1127
1128 Duplicate elements are *not* ignored when comparing *actual* and
1129 *expected*. It verifies if each element has the same count in both
1130 sequences. It is the equivalent of ``assertEqual(sorted(expected),
1131 sorted(actual))`` but it works with sequences of unhashable objects as
1132 well.
1133
Ezio Melotti4370b302010-11-03 20:39:14 +00001134 .. versionadded:: 3.2
1135
1136
1137 .. method:: assertSameElements(actual, expected, msg=None)
1138
1139 Test that sequence *expected* contains the same elements as *actual*,
1140 regardless of their order. When they don't, an error message listing
1141 the differences between the sequences will be generated.
1142
1143 Duplicate elements are ignored when comparing *actual* and *expected*.
1144 It is the equivalent of ``assertEqual(set(expected), set(actual))``
1145 but it works with sequences of unhashable objects as well. Because
1146 duplicates are ignored, this method has been deprecated in favour of
1147 :meth:`assertItemsEqual`.
1148
Ezio Melotti4370b302010-11-03 20:39:14 +00001149 .. versionadded:: 3.1
1150 .. deprecated:: 3.2
1151
1152
Ezio Melotti22170ed2010-11-20 09:57:27 +00001153 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001154
Ezio Melotti22170ed2010-11-20 09:57:27 +00001155 The :meth:`assertEqual` method dispatches the equality check for objects of
1156 the same type to different type-specific methods. These methods are already
1157 implemented for most of the built-in types, but it's also possible to
1158 register new methods using :meth:`addTypeEqualityFunc`:
1159
1160 .. method:: addTypeEqualityFunc(typeobj, function)
1161
1162 Registers a type-specific method called by :meth:`assertEqual` to check
1163 if two objects of exactly the same *typeobj* (not subclasses) compare
1164 equal. *function* must take two positional arguments and a third msg=None
1165 keyword argument just as :meth:`assertEqual` does. It must raise
1166 :data:`self.failureException(msg) <failureException>` when inequality
1167 between the first two parameters is detected -- possibly providing useful
1168 information and explaining the inequalities in details in the error
1169 message.
1170
1171 .. versionadded:: 3.1
1172
1173 The list of type-specific methods automatically used by
1174 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1175 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001176
1177 +-----------------------------------------+-----------------------------+--------------+
1178 | Method | Used to compare | New in |
1179 +=========================================+=============================+==============+
1180 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1181 | <TestCase.assertMultiLineEqual>` | | |
1182 +-----------------------------------------+-----------------------------+--------------+
1183 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1184 | <TestCase.assertSequenceEqual>` | | |
1185 +-----------------------------------------+-----------------------------+--------------+
1186 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1187 | <TestCase.assertListEqual>` | | |
1188 +-----------------------------------------+-----------------------------+--------------+
1189 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1190 | <TestCase.assertTupleEqual>` | | |
1191 +-----------------------------------------+-----------------------------+--------------+
1192 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1193 | <TestCase.assertSetEqual>` | | |
1194 +-----------------------------------------+-----------------------------+--------------+
1195 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1196 | <TestCase.assertDictEqual>` | | |
1197 +-----------------------------------------+-----------------------------+--------------+
1198
1199
1200
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001201 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001202
1203 Test that the multiline string *first* is equal to the string *second*.
1204 When not equal a diff of the two strings highlighting the differences
1205 will be included in the error message. This method is used by default
1206 when comparing strings with :meth:`assertEqual`.
1207
Ezio Melotti4370b302010-11-03 20:39:14 +00001208 .. versionadded:: 3.1
1209
1210
1211 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
1212
1213 Tests that two sequences are equal. If a *seq_type* is supplied, both
1214 *seq1* and *seq2* must be instances of *seq_type* or a failure will
1215 be raised. If the sequences are different an error message is
1216 constructed that shows the difference between the two.
1217
Ezio Melotti22170ed2010-11-20 09:57:27 +00001218 This method is not called directly by :meth:`assertEqual`, but
1219 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001220 :meth:`assertTupleEqual`.
1221
1222 .. versionadded:: 3.1
1223
1224
1225 .. method:: assertListEqual(list1, list2, msg=None)
1226 assertTupleEqual(tuple1, tuple2, msg=None)
1227
1228 Tests that two lists or tuples are equal. If not an error message is
1229 constructed that shows only the differences between the two. An error
1230 is also raised if either of the parameters are of the wrong type.
1231 These methods are used by default when comparing lists or tuples with
1232 :meth:`assertEqual`.
1233
Ezio Melotti4370b302010-11-03 20:39:14 +00001234 .. versionadded:: 3.1
1235
1236
1237 .. method:: assertSetEqual(set1, set2, msg=None)
1238
1239 Tests that two sets are equal. If not, an error message is constructed
1240 that lists the differences between the sets. This method is used by
1241 default when comparing sets or frozensets with :meth:`assertEqual`.
1242
1243 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
1244 method.
1245
Ezio Melotti4370b302010-11-03 20:39:14 +00001246 .. versionadded:: 3.1
1247
1248
1249 .. method:: assertDictEqual(expected, actual, msg=None)
1250
1251 Test that two dictionaries are equal. If not, an error message is
1252 constructed that shows the differences in the dictionaries. This
1253 method will be used by default to compare dictionaries in
1254 calls to :meth:`assertEqual`.
1255
Ezio Melotti4370b302010-11-03 20:39:14 +00001256 .. versionadded:: 3.1
1257
1258
1259
Ezio Melotti22170ed2010-11-20 09:57:27 +00001260 .. _other-methods-and-attrs:
1261
Ezio Melotti4370b302010-11-03 20:39:14 +00001262 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001263
Benjamin Peterson52baa292009-03-24 00:56:30 +00001264
Georg Brandl7f01a132009-09-16 15:58:14 +00001265 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001266
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001267 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001268 the error message.
1269
1270
1271 .. attribute:: failureException
1272
1273 This class attribute gives the exception raised by the test method. If a
1274 test framework needs to use a specialized exception, possibly to carry
1275 additional information, it must subclass this exception in order to "play
1276 fair" with the framework. The initial value of this attribute is
1277 :exc:`AssertionError`.
1278
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001279
1280 .. attribute:: longMessage
1281
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001282 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001283 :ref:`assert methods <assert-methods>` will be appended to the end of the
1284 normal failure message. The normal messages contain useful information
1285 about the objects involved, for example the message from assertEqual
1286 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001287 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001288 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001289
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001290 This attribute defaults to ``False``, meaning that a custom message passed
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001291 to an assert method will silence the normal message.
1292
1293 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001294 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001295
Raymond Hettinger35a88362009-04-09 00:08:24 +00001296 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001297
1298
Michael Foord98b3e762010-06-05 21:59:55 +00001299 .. attribute:: maxDiff
1300
1301 This attribute controls the maximum length of diffs output by assert
1302 methods that report diffs on failure. It defaults to 80*8 characters.
1303 Assert methods affected by this attribute are
1304 :meth:`assertSequenceEqual` (including all the sequence comparison
1305 methods that delegate to it), :meth:`assertDictEqual` and
1306 :meth:`assertMultiLineEqual`.
1307
1308 Setting ``maxDiff`` to None means that there is no maximum length of
1309 diffs.
1310
1311 .. versionadded:: 3.2
1312
1313
Benjamin Peterson52baa292009-03-24 00:56:30 +00001314 Testing frameworks can use the following methods to collect information on
1315 the test:
1316
1317
1318 .. method:: countTestCases()
1319
1320 Return the number of tests represented by this test object. For
1321 :class:`TestCase` instances, this will always be ``1``.
1322
1323
1324 .. method:: defaultTestResult()
1325
1326 Return an instance of the test result class that should be used for this
1327 test case class (if no other result instance is provided to the
1328 :meth:`run` method).
1329
1330 For :class:`TestCase` instances, this will always be an instance of
1331 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1332 as necessary.
1333
1334
1335 .. method:: id()
1336
1337 Return a string identifying the specific test case. This is usually the
1338 full name of the test method, including the module and class name.
1339
1340
1341 .. method:: shortDescription()
1342
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001343 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001344 has been provided. The default implementation of this method
1345 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001346 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001347
Michael Foord34c94622010-02-10 15:51:42 +00001348 .. versionchanged:: 3.1,3.2
1349 In 3.1 this was changed to add the test name to the short description
1350 even in the presence of a docstring. This caused compatibility issues
1351 with unittest extensions and adding the test name was moved to the
1352 :class:`TextTestResult`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001353
Georg Brandl116aa622007-08-15 14:28:22 +00001354
Georg Brandl7f01a132009-09-16 15:58:14 +00001355 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001356
1357 Add a function to be called after :meth:`tearDown` to cleanup resources
1358 used during the test. Functions will be called in reverse order to the
1359 order they are added (LIFO). They are called with any arguments and
1360 keyword arguments passed into :meth:`addCleanup` when they are
1361 added.
1362
1363 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1364 then any cleanup functions added will still be called.
1365
Georg Brandl853947a2010-01-31 18:53:23 +00001366 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001367
1368
1369 .. method:: doCleanups()
1370
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001371 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001372 after :meth:`setUp` if :meth:`setUp` raises an exception.
1373
1374 It is responsible for calling all the cleanup functions added by
1375 :meth:`addCleanup`. If you need cleanup functions to be called
1376 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1377 yourself.
1378
1379 :meth:`doCleanups` pops methods off the stack of cleanup
1380 functions one at a time, so it can be called at any time.
1381
Georg Brandl853947a2010-01-31 18:53:23 +00001382 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001383
1384
Georg Brandl7f01a132009-09-16 15:58:14 +00001385.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001386
1387 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001388 allows the test runner to drive the test, but does not provide the methods
1389 which test code can use to check and report errors. This is used to create
1390 test cases using legacy test code, allowing it to be integrated into a
1391 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001392
1393
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001394Deprecated aliases
1395##################
1396
1397For historical reasons, some of the :class:`TestCase` methods had one or more
1398aliases that are now deprecated. The following table lists the correct names
1399along with their deprecated aliases:
1400
1401 ============================== ===============================
1402 Method Name Deprecated alias(es)
1403 ============================== ===============================
1404 :meth:`.assertEqual` failUnlessEqual, assertEquals
1405 :meth:`.assertNotEqual` failIfEqual
1406 :meth:`.assertTrue` failUnless, assert\_
1407 :meth:`.assertFalse` failIf
1408 :meth:`.assertRaises` failUnlessRaises
1409 :meth:`.assertAlmostEqual` failUnlessAlmostEqual
1410 :meth:`.assertNotAlmostEqual` failIfAlmostEqual
1411 ============================== ===============================
1412
1413 .. deprecated:: 3.1
1414 the aliases listed in the second column
1415
1416
1417
Benjamin Peterson52baa292009-03-24 00:56:30 +00001418.. _testsuite-objects:
1419
Benjamin Peterson52baa292009-03-24 00:56:30 +00001420Grouping tests
1421~~~~~~~~~~~~~~
1422
Georg Brandl7f01a132009-09-16 15:58:14 +00001423.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001424
1425 This class represents an aggregation of individual tests cases and test suites.
1426 The class presents the interface needed by the test runner to allow it to be run
1427 as any other test case. Running a :class:`TestSuite` instance is the same as
1428 iterating over the suite, running each test individually.
1429
1430 If *tests* is given, it must be an iterable of individual test cases or other
1431 test suites that will be used to build the suite initially. Additional methods
1432 are provided to add test cases and suites to the collection later on.
1433
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001434 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1435 they do not actually implement a test. Instead, they are used to aggregate
1436 tests into groups of tests that should be run together. Some additional
1437 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001438
1439
1440 .. method:: TestSuite.addTest(test)
1441
1442 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1443
1444
1445 .. method:: TestSuite.addTests(tests)
1446
1447 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1448 instances to this test suite.
1449
Benjamin Petersond2397752009-06-27 23:45:02 +00001450 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1451 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001452
1453 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1454
1455
1456 .. method:: run(result)
1457
1458 Run the tests associated with this suite, collecting the result into the
1459 test result object passed as *result*. Note that unlike
1460 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1461 be passed in.
1462
1463
1464 .. method:: debug()
1465
1466 Run the tests associated with this suite without collecting the
1467 result. This allows exceptions raised by the test to be propagated to the
1468 caller and can be used to support running tests under a debugger.
1469
1470
1471 .. method:: countTestCases()
1472
1473 Return the number of tests represented by this test object, including all
1474 individual tests and sub-suites.
1475
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001476
1477 .. method:: __iter__()
1478
1479 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1480 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1481 that this method maybe called several times on a single suite
1482 (for example when counting tests or comparing for equality)
1483 so the tests returned must be the same for repeated iterations.
1484
Georg Brandl853947a2010-01-31 18:53:23 +00001485 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001486 In earlier versions the :class:`TestSuite` accessed tests directly rather
1487 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1488 for providing tests.
1489
Benjamin Peterson52baa292009-03-24 00:56:30 +00001490 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1491 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1492
1493
Benjamin Peterson52baa292009-03-24 00:56:30 +00001494Loading and running tests
1495~~~~~~~~~~~~~~~~~~~~~~~~~
1496
Georg Brandl116aa622007-08-15 14:28:22 +00001497.. class:: TestLoader()
1498
Benjamin Peterson52baa292009-03-24 00:56:30 +00001499 The :class:`TestLoader` class is used to create test suites from classes and
1500 modules. Normally, there is no need to create an instance of this class; the
1501 :mod:`unittest` module provides an instance that can be shared as
1502 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1503 customization of some configurable properties.
1504
1505 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001506
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001507
Benjamin Peterson52baa292009-03-24 00:56:30 +00001508 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001509
Benjamin Peterson52baa292009-03-24 00:56:30 +00001510 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1511 :class:`testCaseClass`.
1512
1513
1514 .. method:: loadTestsFromModule(module)
1515
1516 Return a suite of all tests cases contained in the given module. This
1517 method searches *module* for classes derived from :class:`TestCase` and
1518 creates an instance of the class for each test method defined for the
1519 class.
1520
Georg Brandle720c0a2009-04-27 16:20:50 +00001521 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001522
1523 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1524 convenient in sharing fixtures and helper functions, defining test
1525 methods on base classes that are not intended to be instantiated
1526 directly does not play well with this method. Doing so, however, can
1527 be useful when the fixtures are different and defined in subclasses.
1528
Benjamin Petersond2397752009-06-27 23:45:02 +00001529 If a module provides a ``load_tests`` function it will be called to
1530 load the tests. This allows modules to customize test loading.
1531 This is the `load_tests protocol`_.
1532
Georg Brandl853947a2010-01-31 18:53:23 +00001533 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001534 Support for ``load_tests`` added.
1535
Benjamin Peterson52baa292009-03-24 00:56:30 +00001536
Georg Brandl7f01a132009-09-16 15:58:14 +00001537 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001538
1539 Return a suite of all tests cases given a string specifier.
1540
1541 The specifier *name* is a "dotted name" that may resolve either to a
1542 module, a test case class, a test method within a test case class, a
1543 :class:`TestSuite` instance, or a callable object which returns a
1544 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1545 applied in the order listed here; that is, a method on a possible test
1546 case class will be picked up as "a test method within a test case class",
1547 rather than "a callable object".
1548
1549 For example, if you have a module :mod:`SampleTests` containing a
1550 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1551 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001552 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1553 return a suite which will run all three test methods. Using the specifier
1554 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1555 suite which will run only the :meth:`test_two` test method. The specifier
1556 can refer to modules and packages which have not been imported; they will
1557 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001558
1559 The method optionally resolves *name* relative to the given *module*.
1560
1561
Georg Brandl7f01a132009-09-16 15:58:14 +00001562 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001563
1564 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1565 than a single name. The return value is a test suite which supports all
1566 the tests defined for each name.
1567
1568
1569 .. method:: getTestCaseNames(testCaseClass)
1570
1571 Return a sorted sequence of method names found within *testCaseClass*;
1572 this should be a subclass of :class:`TestCase`.
1573
Benjamin Petersond2397752009-06-27 23:45:02 +00001574
1575 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1576
1577 Find and return all test modules from the specified start directory,
1578 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001579 *pattern* will be loaded. (Using shell style pattern matching.) Only
1580 module names that are importable (i.e. are valid Python identifiers) will
1581 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001582
1583 All test modules must be importable from the top level of the project. If
1584 the start directory is not the top level directory then the top level
1585 directory must be specified separately.
1586
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001587 If importing a module fails, for example due to a syntax error, then this
1588 will be recorded as a single error and discovery will continue.
1589
Benjamin Petersond2397752009-06-27 23:45:02 +00001590 If a test package name (directory with :file:`__init__.py`) matches the
1591 pattern then the package will be checked for a ``load_tests``
1592 function. If this exists then it will be called with *loader*, *tests*,
1593 *pattern*.
1594
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001595 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001596 ``load_tests`` is responsible for loading all tests in the package.
1597
1598 The pattern is deliberately not stored as a loader attribute so that
1599 packages can continue discovery themselves. *top_level_dir* is stored so
1600 ``load_tests`` does not need to pass this argument in to
1601 ``loader.discover()``.
1602
Benjamin Petersonb48af542010-04-11 20:43:16 +00001603 *start_dir* can be a dotted module name as well as a directory.
1604
Georg Brandl853947a2010-01-31 18:53:23 +00001605 .. versionadded:: 3.2
1606
Benjamin Petersond2397752009-06-27 23:45:02 +00001607
Benjamin Peterson52baa292009-03-24 00:56:30 +00001608 The following attributes of a :class:`TestLoader` can be configured either by
1609 subclassing or assignment on an instance:
1610
1611
1612 .. attribute:: testMethodPrefix
1613
1614 String giving the prefix of method names which will be interpreted as test
1615 methods. The default value is ``'test'``.
1616
1617 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1618 methods.
1619
1620
1621 .. attribute:: sortTestMethodsUsing
1622
1623 Function to be used to compare method names when sorting them in
1624 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1625
1626
1627 .. attribute:: suiteClass
1628
1629 Callable object that constructs a test suite from a list of tests. No
1630 methods on the resulting object are needed. The default value is the
1631 :class:`TestSuite` class.
1632
1633 This affects all the :meth:`loadTestsFrom\*` methods.
1634
1635
Benjamin Peterson52baa292009-03-24 00:56:30 +00001636.. class:: TestResult
1637
1638 This class is used to compile information about which tests have succeeded
1639 and which have failed.
1640
1641 A :class:`TestResult` object stores the results of a set of tests. The
1642 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1643 properly recorded; test authors do not need to worry about recording the
1644 outcome of tests.
1645
1646 Testing frameworks built on top of :mod:`unittest` may want access to the
1647 :class:`TestResult` object generated by running a set of tests for reporting
1648 purposes; a :class:`TestResult` instance is returned by the
1649 :meth:`TestRunner.run` method for this purpose.
1650
1651 :class:`TestResult` instances have the following attributes that will be of
1652 interest when inspecting the results of running a set of tests:
1653
1654
1655 .. attribute:: errors
1656
1657 A list containing 2-tuples of :class:`TestCase` instances and strings
1658 holding formatted tracebacks. Each tuple represents a test which raised an
1659 unexpected exception.
1660
Benjamin Peterson52baa292009-03-24 00:56:30 +00001661 .. attribute:: failures
1662
1663 A list containing 2-tuples of :class:`TestCase` instances and strings
1664 holding formatted tracebacks. Each tuple represents a test where a failure
1665 was explicitly signalled using the :meth:`TestCase.fail\*` or
1666 :meth:`TestCase.assert\*` methods.
1667
Benjamin Peterson52baa292009-03-24 00:56:30 +00001668 .. attribute:: skipped
1669
1670 A list containing 2-tuples of :class:`TestCase` instances and strings
1671 holding the reason for skipping the test.
1672
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001673 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001674
1675 .. attribute:: expectedFailures
1676
Georg Brandl6faee4e2010-09-21 14:48:28 +00001677 A list containing 2-tuples of :class:`TestCase` instances and strings
1678 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001679 of the test case.
1680
1681 .. attribute:: unexpectedSuccesses
1682
1683 A list containing :class:`TestCase` instances that were marked as expected
1684 failures, but succeeded.
1685
1686 .. attribute:: shouldStop
1687
1688 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1689
1690
1691 .. attribute:: testsRun
1692
1693 The total number of tests run so far.
1694
1695
Benjamin Petersonb48af542010-04-11 20:43:16 +00001696 .. attribute:: buffer
1697
1698 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1699 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1700 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1701 fails or errors. Any output is also attached to the failure / error message.
1702
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001703 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001704
1705
1706 .. attribute:: failfast
1707
1708 If set to true :meth:`stop` will be called on the first failure or error,
1709 halting the test run.
1710
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001711 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001712
1713
Benjamin Peterson52baa292009-03-24 00:56:30 +00001714 .. method:: wasSuccessful()
1715
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001716 Return ``True`` if all tests run so far have passed, otherwise returns
1717 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001718
1719
1720 .. method:: stop()
1721
1722 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001723 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001724 :class:`TestRunner` objects should respect this flag and return without
1725 running any additional tests.
1726
1727 For example, this feature is used by the :class:`TextTestRunner` class to
1728 stop the test framework when the user signals an interrupt from the
1729 keyboard. Interactive tools which provide :class:`TestRunner`
1730 implementations can use this in a similar manner.
1731
1732 The following methods of the :class:`TestResult` class are used to maintain
1733 the internal data structures, and may be extended in subclasses to support
1734 additional reporting requirements. This is particularly useful in building
1735 tools which support interactive reporting while tests are being run.
1736
1737
1738 .. method:: startTest(test)
1739
1740 Called when the test case *test* is about to be run.
1741
Benjamin Peterson52baa292009-03-24 00:56:30 +00001742 .. method:: stopTest(test)
1743
1744 Called after the test case *test* has been executed, regardless of the
1745 outcome.
1746
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001747 .. method:: startTestRun(test)
1748
1749 Called once before any tests are executed.
1750
Georg Brandl853947a2010-01-31 18:53:23 +00001751 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001752
1753
1754 .. method:: stopTestRun(test)
1755
Ezio Melotti176d6c42010-01-27 20:58:07 +00001756 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001757
Georg Brandl853947a2010-01-31 18:53:23 +00001758 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001759
1760
Benjamin Peterson52baa292009-03-24 00:56:30 +00001761 .. method:: addError(test, err)
1762
1763 Called when the test case *test* raises an unexpected exception *err* is a
1764 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1765 traceback)``.
1766
1767 The default implementation appends a tuple ``(test, formatted_err)`` to
1768 the instance's :attr:`errors` attribute, where *formatted_err* is a
1769 formatted traceback derived from *err*.
1770
1771
1772 .. method:: addFailure(test, err)
1773
Benjamin Petersond2397752009-06-27 23:45:02 +00001774 Called when the test case *test* signals a failure. *err* is a tuple of
1775 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001776
1777 The default implementation appends a tuple ``(test, formatted_err)`` to
1778 the instance's :attr:`failures` attribute, where *formatted_err* is a
1779 formatted traceback derived from *err*.
1780
1781
1782 .. method:: addSuccess(test)
1783
1784 Called when the test case *test* succeeds.
1785
1786 The default implementation does nothing.
1787
1788
1789 .. method:: addSkip(test, reason)
1790
1791 Called when the test case *test* is skipped. *reason* is the reason the
1792 test gave for skipping.
1793
1794 The default implementation appends a tuple ``(test, reason)`` to the
1795 instance's :attr:`skipped` attribute.
1796
1797
1798 .. method:: addExpectedFailure(test, err)
1799
1800 Called when the test case *test* fails, but was marked with the
1801 :func:`expectedFailure` decorator.
1802
1803 The default implementation appends a tuple ``(test, formatted_err)`` to
1804 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1805 is a formatted traceback derived from *err*.
1806
1807
1808 .. method:: addUnexpectedSuccess(test)
1809
1810 Called when the test case *test* was marked with the
1811 :func:`expectedFailure` decorator, but succeeded.
1812
1813 The default implementation appends the test to the instance's
1814 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001815
Georg Brandl67b21b72010-08-17 15:07:14 +00001816
Michael Foord34c94622010-02-10 15:51:42 +00001817.. class:: TextTestResult(stream, descriptions, verbosity)
1818
Georg Brandl67b21b72010-08-17 15:07:14 +00001819 A concrete implementation of :class:`TestResult` used by the
1820 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001821
Georg Brandl67b21b72010-08-17 15:07:14 +00001822 .. versionadded:: 3.2
1823 This class was previously named ``_TextTestResult``. The old name still
1824 exists as an alias but is deprecated.
1825
Georg Brandl116aa622007-08-15 14:28:22 +00001826
1827.. data:: defaultTestLoader
1828
1829 Instance of the :class:`TestLoader` class intended to be shared. If no
1830 customization of the :class:`TestLoader` is needed, this instance can be used
1831 instead of repeatedly creating new instances.
1832
1833
Michael Foord34c94622010-02-10 15:51:42 +00001834.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001835
1836 A basic test runner implementation which prints results on standard error. It
1837 has a few configurable parameters, but is essentially very simple. Graphical
1838 applications which run test suites should provide alternate implementations.
1839
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001840 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001841
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001842 This method returns the instance of ``TestResult`` used by :meth:`run`.
1843 It is not intended to be called directly, but can be overridden in
1844 subclasses to provide a custom ``TestResult``.
1845
Michael Foord34c94622010-02-10 15:51:42 +00001846 ``_makeResult()`` instantiates the class or callable passed in the
1847 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001848 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001849 The result class is instantiated with the following arguments::
1850
1851 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001852
Benjamin Petersonb48af542010-04-11 20:43:16 +00001853.. 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 +00001854
1855 A command-line program that runs a set of tests; this is primarily for making
1856 test modules conveniently executable. The simplest use for this function is to
1857 include the following line at the end of a test script::
1858
1859 if __name__ == '__main__':
1860 unittest.main()
1861
Benjamin Petersond2397752009-06-27 23:45:02 +00001862 You can run tests with more detailed information by passing in the verbosity
1863 argument::
1864
1865 if __name__ == '__main__':
1866 unittest.main(verbosity=2)
1867
Georg Brandl116aa622007-08-15 14:28:22 +00001868 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001869 created instance of it. By default ``main`` calls :func:`sys.exit` with
1870 an exit code indicating success or failure of the tests run.
1871
1872 ``main`` supports being used from the interactive interpreter by passing in the
1873 argument ``exit=False``. This displays the result on standard output without
1874 calling :func:`sys.exit`::
1875
1876 >>> from unittest import main
1877 >>> main(module='test_module', exit=False)
1878
Benjamin Petersonb48af542010-04-11 20:43:16 +00001879 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
Éric Araujo713d3032010-11-18 16:38:46 +00001880 effect as the `failfast, catch and buffer command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001881
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001882 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1883 This stores the result of the tests run as the ``result`` attribute.
1884
Georg Brandl853947a2010-01-31 18:53:23 +00001885 .. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001886 The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
1887 parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001888
1889
1890load_tests Protocol
1891###################
1892
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001893
Georg Brandl853947a2010-01-31 18:53:23 +00001894.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001895
1896
Benjamin Petersond2397752009-06-27 23:45:02 +00001897Modules or packages can customize how tests are loaded from them during normal
1898test runs or test discovery by implementing a function called ``load_tests``.
1899
1900If a test module defines ``load_tests`` it will be called by
1901:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1902
1903 load_tests(loader, standard_tests, None)
1904
1905It should return a :class:`TestSuite`.
1906
1907*loader* is the instance of :class:`TestLoader` doing the loading.
1908*standard_tests* are the tests that would be loaded by default from the
1909module. It is common for test modules to only want to add or remove tests
1910from the standard set of tests.
1911The third argument is used when loading packages as part of test discovery.
1912
1913A typical ``load_tests`` function that loads tests from a specific set of
1914:class:`TestCase` classes may look like::
1915
1916 test_cases = (TestCase1, TestCase2, TestCase3)
1917
1918 def load_tests(loader, tests, pattern):
1919 suite = TestSuite()
1920 for test_class in test_cases:
1921 tests = loader.loadTestsFromTestCase(test_class)
1922 suite.addTests(tests)
1923 return suite
1924
1925If discovery is started, either from the command line or by calling
1926:meth:`TestLoader.discover`, with a pattern that matches a package
1927name then the package :file:`__init__.py` will be checked for ``load_tests``.
1928
1929.. note::
1930
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001931 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00001932 that start with 'test' but *won't* match any test directories.
1933
1934 A pattern like 'test*' will match test packages as well as
1935 modules.
1936
1937If the package :file:`__init__.py` defines ``load_tests`` then it will be
1938called and discovery not continued into the package. ``load_tests``
1939is called with the following arguments::
1940
1941 load_tests(loader, standard_tests, pattern)
1942
1943This should return a :class:`TestSuite` representing all the tests
1944from the package. (``standard_tests`` will only contain tests
1945collected from :file:`__init__.py`.)
1946
1947Because the pattern is passed into ``load_tests`` the package is free to
1948continue (and potentially modify) test discovery. A 'do nothing'
1949``load_tests`` function for a test package would look like::
1950
1951 def load_tests(loader, standard_tests, pattern):
1952 # top level directory cached on loader instance
1953 this_dir = os.path.dirname(__file__)
1954 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1955 standard_tests.addTests(package_tests)
1956 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00001957
1958
1959Class and Module Fixtures
1960-------------------------
1961
1962Class and module level fixtures are implemented in :class:`TestSuite`. When
1963the test suite encounters a test from a new class then :meth:`tearDownClass`
1964from the previous class (if there is one) is called, followed by
1965:meth:`setUpClass` from the new class.
1966
1967Similarly if a test is from a different module from the previous test then
1968``tearDownModule`` from the previous module is run, followed by
1969``setUpModule`` from the new module.
1970
1971After all the tests have run the final ``tearDownClass`` and
1972``tearDownModule`` are run.
1973
1974Note that shared fixtures do not play well with [potential] features like test
1975parallelization and they break test isolation. They should be used with care.
1976
1977The default ordering of tests created by the unittest test loaders is to group
1978all tests from the same modules and classes together. This will lead to
1979``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
1980module. If you randomize the order, so that tests from different modules and
1981classes are adjacent to each other, then these shared fixture functions may be
1982called multiple times in a single test run.
1983
1984Shared fixtures are not intended to work with suites with non-standard
1985ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
1986support shared fixtures.
1987
1988If there are any exceptions raised during one of the shared fixture functions
1989the test is reported as an error. Because there is no corresponding test
1990instance an ``_ErrorHolder`` object (that has the same interface as a
1991:class:`TestCase`) is created to represent the error. If you are just using
1992the standard unittest test runner then this detail doesn't matter, but if you
1993are a framework author it may be relevant.
1994
1995
1996setUpClass and tearDownClass
1997~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1998
1999These must be implemented as class methods::
2000
2001 import unittest
2002
2003 class Test(unittest.TestCase):
2004 @classmethod
2005 def setUpClass(cls):
2006 cls._connection = createExpensiveConnectionObject()
2007
2008 @classmethod
2009 def tearDownClass(cls):
2010 cls._connection.destroy()
2011
2012If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2013then you must call up to them yourself. The implementations in
2014:class:`TestCase` are empty.
2015
2016If an exception is raised during a ``setUpClass`` then the tests in the class
2017are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002018have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
2019``SkipTest`` exception then the class will be reported as having been skipped
2020instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002021
2022
2023setUpModule and tearDownModule
2024~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2025
2026These should be implemented as functions::
2027
2028 def setUpModule():
2029 createConnection()
2030
2031 def tearDownModule():
2032 closeConnection()
2033
2034If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002035module will be run and the ``tearDownModule`` will not be run. If the exception is a
2036``SkipTest`` exception then the module will be reported as having been skipped
2037instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002038
2039
2040Signal Handling
2041---------------
2042
Éric Araujo713d3032010-11-18 16:38:46 +00002043The :option:`-c` command-line option to unittest, along with the ``catchbreak``
Benjamin Petersonb48af542010-04-11 20:43:16 +00002044parameter to :func:`unittest.main()`, provide more friendly handling of
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002045control-C during a test run. With catch break behavior enabled control-C will
Benjamin Petersonb48af542010-04-11 20:43:16 +00002046allow the currently running test to complete, and the test run will then end
2047and report all the results so far. A second control-c will raise a
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002048:exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002049
Michael Foordde4ceab2010-04-25 19:53:49 +00002050The control-c handling signal handler attempts to remain compatible with code or
2051tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2052handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2053i.e. it has been replaced by the system under test and delegated to, then it
2054calls the default handler. This will normally be the expected behavior by code
2055that replaces an installed handler and delegates to it. For individual tests
2056that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2057decorator can be used.
2058
2059There are a few utility functions for framework authors to enable control-c
2060handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002061
2062.. function:: installHandler()
2063
2064 Install the control-c handler. When a :const:`signal.SIGINT` is received
2065 (usually in response to the user pressing control-c) all registered results
2066 have :meth:`~TestResult.stop` called.
2067
Michael Foord469b1f02010-04-26 23:41:26 +00002068 .. versionadded:: 3.2
2069
Benjamin Petersonb48af542010-04-11 20:43:16 +00002070.. function:: registerResult(result)
2071
2072 Register a :class:`TestResult` object for control-c handling. Registering a
2073 result stores a weak reference to it, so it doesn't prevent the result from
2074 being garbage collected.
2075
Michael Foordde4ceab2010-04-25 19:53:49 +00002076 Registering a :class:`TestResult` object has no side-effects if control-c
2077 handling is not enabled, so test frameworks can unconditionally register
2078 all results they create independently of whether or not handling is enabled.
2079
Michael Foord469b1f02010-04-26 23:41:26 +00002080 .. versionadded:: 3.2
2081
Benjamin Petersonb48af542010-04-11 20:43:16 +00002082.. function:: removeResult(result)
2083
2084 Remove a registered result. Once a result has been removed then
2085 :meth:`~TestResult.stop` will no longer be called on that result object in
2086 response to a control-c.
2087
Michael Foord469b1f02010-04-26 23:41:26 +00002088 .. versionadded:: 3.2
2089
Michael Foordde4ceab2010-04-25 19:53:49 +00002090.. function:: removeHandler(function=None)
2091
2092 When called without arguments this function removes the control-c handler
2093 if it has been installed. This function can also be used as a test decorator
2094 to temporarily remove the handler whilst the test is being executed::
2095
2096 @unittest.removeHandler
2097 def test_signal_handling(self):
2098 ...
2099
Michael Foord469b1f02010-04-26 23:41:26 +00002100 .. versionadded:: 3.2
2101