blob: 3b49ea0cb502cb7b13e6fc9842571f578a993f64 [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
Éric Araujo76338ec2010-11-26 23:46:18 +0000194Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000195----------------------
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
Michael Foord37d120a2010-12-04 01:11:21 +0000207Test modules can be specified by file path as well::
208
209 python -m unittest tests/test_something.py
210
211This allows you to use the shell filename completion to specify the test module.
212The file specified must still be importable as a module. The path is converted
213to a module name by removing the '.py' and converting path separators into '.'.
214If you want to execute a test file that isn't importable as a module you should
215execute the file directly instead.
216
Benjamin Petersonb48af542010-04-11 20:43:16 +0000217You can run tests with more detail (higher verbosity) by passing in the -v flag::
218
219 python -m unittest -v test_module
220
Michael Foord086f3082010-11-21 21:28:01 +0000221When executed without arguments :ref:`unittest-test-discovery` is started::
222
223 python -m unittest
224
Éric Araujo713d3032010-11-18 16:38:46 +0000225For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000226
227 python -m unittest -h
228
Georg Brandl67b21b72010-08-17 15:07:14 +0000229.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000230 In earlier versions it was only possible to run individual test methods and
231 not modules or classes.
232
233
Éric Araujo76338ec2010-11-26 23:46:18 +0000234Command-line options
235~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000236
Éric Araujod3309df2010-11-21 03:09:17 +0000237:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000238
Éric Araujo713d3032010-11-18 16:38:46 +0000239.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000240
Éric Araujo713d3032010-11-18 16:38:46 +0000241.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000242
Éric Araujo713d3032010-11-18 16:38:46 +0000243 The standard output and standard error streams are buffered during the test
244 run. Output during a passing test is discarded. Output is echoed normally
245 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000246
Éric Araujo713d3032010-11-18 16:38:46 +0000247.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000248
Éric Araujo713d3032010-11-18 16:38:46 +0000249 Control-C during the test run waits for the current test to end and then
250 reports all the results so far. A second control-C raises the normal
251 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000252
Éric Araujo713d3032010-11-18 16:38:46 +0000253 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000254
Éric Araujo713d3032010-11-18 16:38:46 +0000255.. cmdoption:: -f, --failfast
256
257 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000258
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000259.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000260 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000261
262The command line can also be used for test discovery, for running all of the
263tests in a project or just a subset.
264
265
266.. _unittest-test-discovery:
267
268Test Discovery
269--------------
270
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000271.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000272
273Unittest supports simple test discovery. For a project's tests to be
274compatible with test discovery they must all be importable from the top level
275directory of the project (in other words, they must all be in Python packages).
276
277Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000278used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000279
280 cd project_directory
281 python -m unittest discover
282
Michael Foord086f3082010-11-21 21:28:01 +0000283.. note::
284
285 As a shortcut, ``python -m unittest`` is the equivalent of
286 ``python -m unittest discover``. If you want to pass arguments to test
287 discovery the `discover` sub-command must be used explicitly.
288
Benjamin Petersonb48af542010-04-11 20:43:16 +0000289The ``discover`` sub-command has the following options:
290
Éric Araujo713d3032010-11-18 16:38:46 +0000291.. program:: unittest discover
292
293.. cmdoption:: -v, --verbose
294
295 Verbose output
296
297.. cmdoption:: -s directory
298
299 Directory to start discovery ('.' default)
300
301.. cmdoption:: -p pattern
302
303 Pattern to match test files ('test*.py' default)
304
305.. cmdoption:: -t directory
306
307 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000308
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000309The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
310as positional arguments in that order. The following two command lines
311are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000312
313 python -m unittest discover -s project_directory -p '*_test.py'
314 python -m unittest discover project_directory '*_test.py'
315
Michael Foord16f3e902010-05-08 15:13:42 +0000316As well as being a path it is possible to pass a package name, for example
317``myproject.subpackage.test``, as the start directory. The package name you
318supply will then be imported and its location on the filesystem will be used
319as the start directory.
320
321.. caution::
322
Senthil Kumaran916bd382010-10-15 12:55:19 +0000323 Test discovery loads tests by importing them. Once test discovery has found
324 all the test files from the start directory you specify it turns the paths
325 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000326 imported as ``foo.bar.baz``.
327
328 If you have a package installed globally and attempt test discovery on
329 a different copy of the package then the import *could* happen from the
330 wrong place. If this happens test discovery will warn you and exit.
331
332 If you supply the start directory as a package name rather than a
333 path to a directory then discover assumes that whichever location it
334 imports from is the location you intended, so you will not get the
335 warning.
336
Benjamin Petersonb48af542010-04-11 20:43:16 +0000337Test modules and packages can customize test loading and discovery by through
338the `load_tests protocol`_.
339
340
Georg Brandl116aa622007-08-15 14:28:22 +0000341.. _organizing-tests:
342
343Organizing test code
344--------------------
345
346The basic building blocks of unit testing are :dfn:`test cases` --- single
347scenarios that must be set up and checked for correctness. In :mod:`unittest`,
348test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
349class. To make your own test cases you must write subclasses of
350:class:`TestCase`, or use :class:`FunctionTestCase`.
351
352An instance of a :class:`TestCase`\ -derived class is an object that can
353completely run a single test method, together with optional set-up and tidy-up
354code.
355
356The testing code of a :class:`TestCase` instance should be entirely self
357contained, such that it can be run either in isolation or in arbitrary
358combination with any number of other test cases.
359
Benjamin Peterson52baa292009-03-24 00:56:30 +0000360The simplest :class:`TestCase` subclass will simply override the
361:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000362
363 import unittest
364
365 class DefaultWidgetSizeTestCase(unittest.TestCase):
366 def runTest(self):
367 widget = Widget('The widget')
368 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
369
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000370Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000371methods provided by the :class:`TestCase` base class. If the test fails, an
372exception will be raised, and :mod:`unittest` will identify the test case as a
373:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
374helps you identify where the problem is: :dfn:`failures` are caused by incorrect
375results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
376code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000377
378The way to run a test case will be described later. For now, note that to
379construct an instance of such a test case, we call its constructor without
380arguments::
381
382 testCase = DefaultWidgetSizeTestCase()
383
384Now, such test cases can be numerous, and their set-up can be repetitive. In
385the above case, constructing a :class:`Widget` in each of 100 Widget test case
386subclasses would mean unsightly duplication.
387
388Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000389:meth:`~TestCase.setUp`, which the testing framework will automatically call for
390us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000391
392 import unittest
393
394 class SimpleWidgetTestCase(unittest.TestCase):
395 def setUp(self):
396 self.widget = Widget('The widget')
397
398 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
399 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000400 self.assertEqual(self.widget.size(), (50,50),
401 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403 class WidgetResizeTestCase(SimpleWidgetTestCase):
404 def runTest(self):
405 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000406 self.assertEqual(self.widget.size(), (100,150),
407 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Benjamin Peterson52baa292009-03-24 00:56:30 +0000409If the :meth:`~TestCase.setUp` method raises an exception while the test is
410running, the framework will consider the test to have suffered an error, and the
411:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000412
Benjamin Peterson52baa292009-03-24 00:56:30 +0000413Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
414after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416 import unittest
417
418 class SimpleWidgetTestCase(unittest.TestCase):
419 def setUp(self):
420 self.widget = Widget('The widget')
421
422 def tearDown(self):
423 self.widget.dispose()
424 self.widget = None
425
Benjamin Peterson52baa292009-03-24 00:56:30 +0000426If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
427be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000428
429Such a working environment for the testing code is called a :dfn:`fixture`.
430
431Often, many small test cases will use the same fixture. In this case, we would
432end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
433classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000434discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
435mechanism::
436
437 import unittest
438
439 class WidgetTestCase(unittest.TestCase):
440 def setUp(self):
441 self.widget = Widget('The widget')
442
443 def tearDown(self):
444 self.widget.dispose()
445 self.widget = None
446
Ezio Melottid59e44a2010-02-28 03:46:13 +0000447 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000448 self.assertEqual(self.widget.size(), (50,50),
449 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000450
Ezio Melottid59e44a2010-02-28 03:46:13 +0000451 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000452 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000453 self.assertEqual(self.widget.size(), (100,150),
454 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000455
Benjamin Peterson52baa292009-03-24 00:56:30 +0000456Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
457provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000458the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000459separately for each instance. When creating an instance we must specify the
460test method it is to run. We do this by passing the method name in the
461constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000462
Ezio Melottid59e44a2010-02-28 03:46:13 +0000463 defaultSizeTestCase = WidgetTestCase('test_default_size')
464 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000465
466Test case instances are grouped together according to the features they test.
467:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
468represented by :mod:`unittest`'s :class:`TestSuite` class::
469
470 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000471 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
472 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000473
474For the ease of running tests, as we will see later, it is a good idea to
475provide in each test module a callable object that returns a pre-built test
476suite::
477
478 def suite():
479 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000480 suite.addTest(WidgetTestCase('test_default_size'))
481 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000482 return suite
483
484or even::
485
486 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000487 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489 return unittest.TestSuite(map(WidgetTestCase, tests))
490
491Since it is a common pattern to create a :class:`TestCase` subclass with many
492similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
493class that can be used to automate the process of creating a test suite and
494populating it with individual tests. For example, ::
495
496 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
497
Ezio Melottid59e44a2010-02-28 03:46:13 +0000498will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
499``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000500name prefix to identify test methods automatically.
501
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000502Note that the order in which the various test cases will be run is
503determined by sorting the test function names with respect to the
504built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000505
506Often it is desirable to group suites of test cases together, so as to run tests
507for the whole system at once. This is easy, since :class:`TestSuite` instances
508can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
509added to a :class:`TestSuite`::
510
511 suite1 = module1.TheTestSuite()
512 suite2 = module2.TheTestSuite()
513 alltests = unittest.TestSuite([suite1, suite2])
514
515You can place the definitions of test cases and test suites in the same modules
516as the code they are to test (such as :file:`widget.py`), but there are several
517advantages to placing the test code in a separate module, such as
518:file:`test_widget.py`:
519
520* The test module can be run standalone from the command line.
521
522* The test code can more easily be separated from shipped code.
523
524* There is less temptation to change test code to fit the code it tests without
525 a good reason.
526
527* Test code should be modified much less frequently than the code it tests.
528
529* Tested code can be refactored more easily.
530
531* Tests for modules written in C must be in separate modules anyway, so why not
532 be consistent?
533
534* If the testing strategy changes, there is no need to change the source code.
535
536
537.. _legacy-unit-tests:
538
539Re-using old test code
540----------------------
541
542Some users will find that they have existing test code that they would like to
543run from :mod:`unittest`, without converting every old test function to a
544:class:`TestCase` subclass.
545
546For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
547This subclass of :class:`TestCase` can be used to wrap an existing test
548function. Set-up and tear-down functions can also be provided.
549
550Given the following test function::
551
552 def testSomething():
553 something = makeSomething()
554 assert something.name is not None
555 # ...
556
557one can create an equivalent test case instance as follows::
558
559 testcase = unittest.FunctionTestCase(testSomething)
560
561If there are additional set-up and tear-down methods that should be called as
562part of the test case's operation, they can also be provided like so::
563
564 testcase = unittest.FunctionTestCase(testSomething,
565 setUp=makeSomethingDB,
566 tearDown=deleteSomethingDB)
567
568To make migrating existing test suites easier, :mod:`unittest` supports tests
569raising :exc:`AssertionError` to indicate test failure. However, it is
570recommended that you use the explicit :meth:`TestCase.fail\*` and
571:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
572may treat :exc:`AssertionError` differently.
573
574.. note::
575
Benjamin Petersond2397752009-06-27 23:45:02 +0000576 Even though :class:`FunctionTestCase` can be used to quickly convert an
577 existing test base over to a :mod:`unittest`\ -based system, this approach is
578 not recommended. Taking the time to set up proper :class:`TestCase`
579 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000580
Benjamin Peterson52baa292009-03-24 00:56:30 +0000581In some cases, the existing tests may have been written using the :mod:`doctest`
582module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
583automatically build :class:`unittest.TestSuite` instances from the existing
584:mod:`doctest`\ -based tests.
585
Georg Brandl116aa622007-08-15 14:28:22 +0000586
Benjamin Peterson5254c042009-03-23 22:25:03 +0000587.. _unittest-skipping:
588
589Skipping tests and expected failures
590------------------------------------
591
Michael Foordf5c851a2010-02-05 21:48:03 +0000592.. versionadded:: 3.1
593
Benjamin Peterson5254c042009-03-23 22:25:03 +0000594Unittest supports skipping individual test methods and even whole classes of
595tests. In addition, it supports marking a test as a "expected failure," a test
596that is broken and will fail, but shouldn't be counted as a failure on a
597:class:`TestResult`.
598
599Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
600or one of its conditional variants.
601
602Basic skipping looks like this: ::
603
604 class MyTestCase(unittest.TestCase):
605
606 @unittest.skip("demonstrating skipping")
607 def test_nothing(self):
608 self.fail("shouldn't happen")
609
Benjamin Petersond2397752009-06-27 23:45:02 +0000610 @unittest.skipIf(mylib.__version__ < (1, 3),
611 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000612 def test_format(self):
613 # Tests that work for only a certain version of the library.
614 pass
615
616 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
617 def test_windows_support(self):
618 # windows specific testing code
619 pass
620
Benjamin Peterson5254c042009-03-23 22:25:03 +0000621This is the output of running the example above in verbose mode: ::
622
Benjamin Petersonded31c42009-03-30 15:04:16 +0000623 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000624 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000625 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000626
627 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000628 Ran 3 tests in 0.005s
629
630 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000631
632Classes can be skipped just like methods: ::
633
634 @skip("showing class skipping")
635 class MySkippedTestCase(unittest.TestCase):
636 def test_not_run(self):
637 pass
638
Benjamin Peterson52baa292009-03-24 00:56:30 +0000639:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
640that needs to be set up is not available.
641
Benjamin Peterson5254c042009-03-23 22:25:03 +0000642Expected failures use the :func:`expectedFailure` decorator. ::
643
644 class ExpectedFailureTestCase(unittest.TestCase):
645 @unittest.expectedFailure
646 def test_fail(self):
647 self.assertEqual(1, 0, "broken")
648
649It's easy to roll your own skipping decorators by making a decorator that calls
650:func:`skip` on the test when it wants it to be skipped. This decorator skips
651the test unless the passed object has a certain attribute: ::
652
653 def skipUnlessHasattr(obj, attr):
654 if hasattr(obj, attr):
655 return lambda func: func
656 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
657
658The following decorators implement test skipping and expected failures:
659
Georg Brandl8a1caa22010-07-29 16:01:11 +0000660.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000661
662 Unconditionally skip the decorated test. *reason* should describe why the
663 test is being skipped.
664
Georg Brandl8a1caa22010-07-29 16:01:11 +0000665.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000666
667 Skip the decorated test if *condition* is true.
668
Georg Brandl8a1caa22010-07-29 16:01:11 +0000669.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000670
Georg Brandl6faee4e2010-09-21 14:48:28 +0000671 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000672
Georg Brandl8a1caa22010-07-29 16:01:11 +0000673.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000674
675 Mark the test as an expected failure. If the test fails when run, the test
676 is not counted as a failure.
677
Benjamin Petersonb48af542010-04-11 20:43:16 +0000678Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
679Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
680
Benjamin Peterson5254c042009-03-23 22:25:03 +0000681
Georg Brandl116aa622007-08-15 14:28:22 +0000682.. _unittest-contents:
683
684Classes and functions
685---------------------
686
Benjamin Peterson52baa292009-03-24 00:56:30 +0000687This section describes in depth the API of :mod:`unittest`.
688
689
690.. _testcase-objects:
691
692Test cases
693~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000694
Georg Brandl7f01a132009-09-16 15:58:14 +0000695.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000696
697 Instances of the :class:`TestCase` class represent the smallest testable units
698 in the :mod:`unittest` universe. This class is intended to be used as a base
699 class, with specific tests being implemented by concrete subclasses. This class
700 implements the interface needed by the test runner to allow it to drive the
701 test, and methods that the test code can use to check for and report various
702 kinds of failure.
703
704 Each instance of :class:`TestCase` will run a single test method: the method
705 named *methodName*. If you remember, we had an earlier example that went
706 something like this::
707
708 def suite():
709 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000710 suite.addTest(WidgetTestCase('test_default_size'))
711 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000712 return suite
713
714 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
715 single test.
716
Benjamin Peterson52baa292009-03-24 00:56:30 +0000717 *methodName* defaults to :meth:`runTest`.
718
719 :class:`TestCase` instances provide three groups of methods: one group used
720 to run the test, another used by the test implementation to check conditions
721 and report failures, and some inquiry methods allowing information about the
722 test itself to be gathered.
723
724 Methods in the first group (running the test) are:
725
726
727 .. method:: setUp()
728
729 Method called to prepare the test fixture. This is called immediately
730 before calling the test method; any exception raised by this method will
731 be considered an error rather than a test failure. The default
732 implementation does nothing.
733
734
735 .. method:: tearDown()
736
737 Method called immediately after the test method has been called and the
738 result recorded. This is called even if the test method raised an
739 exception, so the implementation in subclasses may need to be particularly
740 careful about checking internal state. Any exception raised by this
741 method will be considered an error rather than a test failure. This
742 method will only be called if the :meth:`setUp` succeeds, regardless of
743 the outcome of the test method. The default implementation does nothing.
744
745
Benjamin Petersonb48af542010-04-11 20:43:16 +0000746 .. method:: setUpClass()
747
748 A class method called before tests in an individual class run.
749 ``setUpClass`` is called with the class as the only argument
750 and must be decorated as a :func:`classmethod`::
751
752 @classmethod
753 def setUpClass(cls):
754 ...
755
756 See `Class and Module Fixtures`_ for more details.
757
758 .. versionadded:: 3.2
759
760
761 .. method:: tearDownClass()
762
763 A class method called after tests in an individual class have run.
764 ``tearDownClass`` is called with the class as the only argument
765 and must be decorated as a :meth:`classmethod`::
766
767 @classmethod
768 def tearDownClass(cls):
769 ...
770
771 See `Class and Module Fixtures`_ for more details.
772
773 .. versionadded:: 3.2
774
775
Georg Brandl7f01a132009-09-16 15:58:14 +0000776 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000777
778 Run the test, collecting the result into the test result object passed as
Ezio Melotti75b2a5e2010-11-20 10:13:45 +0000779 *result*. If *result* is omitted or ``None``, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000780 object is created (by calling the :meth:`defaultTestResult` method) and
781 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000782
783 The same effect may be had by simply calling the :class:`TestCase`
784 instance.
785
786
Benjamin Petersone549ead2009-03-28 21:42:05 +0000787 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000788
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000789 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000790 test. See :ref:`unittest-skipping` for more information.
791
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000792 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000793
Benjamin Peterson52baa292009-03-24 00:56:30 +0000794
795 .. method:: debug()
796
797 Run the test without collecting the result. This allows exceptions raised
798 by the test to be propagated to the caller, and can be used to support
799 running tests under a debugger.
800
Ezio Melotti22170ed2010-11-20 09:57:27 +0000801 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000802
Ezio Melotti4370b302010-11-03 20:39:14 +0000803 The :class:`TestCase` class provides a number of methods to check for and
804 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000805
Ezio Melotti4370b302010-11-03 20:39:14 +0000806 +-----------------------------------------+-----------------------------+---------------+
807 | Method | Checks that | New in |
808 +=========================================+=============================+===============+
809 | :meth:`assertEqual(a, b) | ``a == b`` | |
810 | <TestCase.assertEqual>` | | |
811 +-----------------------------------------+-----------------------------+---------------+
812 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
813 | <TestCase.assertNotEqual>` | | |
814 +-----------------------------------------+-----------------------------+---------------+
815 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
816 | <TestCase.assertTrue>` | | |
817 +-----------------------------------------+-----------------------------+---------------+
818 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
819 | <TestCase.assertFalse>` | | |
820 +-----------------------------------------+-----------------------------+---------------+
821 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
822 | <TestCase.assertIs>` | | |
823 +-----------------------------------------+-----------------------------+---------------+
824 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
825 | <TestCase.assertIsNot>` | | |
826 +-----------------------------------------+-----------------------------+---------------+
827 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
828 | <TestCase.assertIsNone>` | | |
829 +-----------------------------------------+-----------------------------+---------------+
830 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
831 | <TestCase.assertIsNotNone>` | | |
832 +-----------------------------------------+-----------------------------+---------------+
833 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
834 | <TestCase.assertIn>` | | |
835 +-----------------------------------------+-----------------------------+---------------+
836 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
837 | <TestCase.assertNotIn>` | | |
838 +-----------------------------------------+-----------------------------+---------------+
839 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
840 | <TestCase.assertIsInstance>` | | |
841 +-----------------------------------------+-----------------------------+---------------+
842 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
843 | <TestCase.assertNotIsInstance>` | | |
844 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000845
Ezio Melotti22170ed2010-11-20 09:57:27 +0000846 All the assert methods (except :meth:`assertRaises`,
Ezio Melottied3a7d22010-12-01 02:32:32 +0000847 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`)
Ezio Melotti22170ed2010-11-20 09:57:27 +0000848 accept a *msg* argument that, if specified, is used as the error message on
849 failure (see also :data:`longMessage`).
Benjamin Peterson52baa292009-03-24 00:56:30 +0000850
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000851 .. method:: assertEqual(actual, expected, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000852
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000853 Test that *actual* and *expected* are equal. If the values do not
854 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000855
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000856 In addition, if *actual* and *expected* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000857 list, tuple, dict, set, frozenset or str or any type that a subclass
858 registers with :meth:`addTypeEqualityFunc` the type specific equality
859 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000860 error message (see also the :ref:`list of type-specific methods
861 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000862
Raymond Hettinger35a88362009-04-09 00:08:24 +0000863 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000864 Added the automatic calling of type specific equality function.
865
Michael Foord28a817e2010-02-09 00:03:57 +0000866 .. versionchanged:: 3.2
867 :meth:`assertMultiLineEqual` added as the default type equality
868 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000869
Benjamin Peterson52baa292009-03-24 00:56:30 +0000870
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000871 .. method:: assertNotEqual(actual, expected, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000872
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000873 Test that *actual* and *expected* are not equal. If the values do
874 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000875
Ezio Melotti4370b302010-11-03 20:39:14 +0000876 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000877 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000878
Ezio Melotti4841fd62010-11-05 15:43:40 +0000879 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000880
Ezio Melotti4841fd62010-11-05 15:43:40 +0000881 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
882 is True`` (use ``assertIs(expr, True)`` for the latter). This method
883 should also be avoided when more specific methods are available (e.g.
884 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
885 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000886
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000887
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000888 .. method:: assertIs(actual, expected, msg=None)
889 assertIsNot(actual, expected, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000890
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000891 Test that *actual* and *expected* evaluate (or don't evaluate) to the
892 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000893
Raymond Hettinger35a88362009-04-09 00:08:24 +0000894 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000895
896
Ezio Melotti4370b302010-11-03 20:39:14 +0000897 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000898 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000899
Ezio Melotti9794a262010-11-04 14:52:13 +0000900 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000901
Ezio Melotti4370b302010-11-03 20:39:14 +0000902 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000903
904
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000905 .. method:: assertIn(first, second, msg=None)
906 assertNotIn(first, second, msg=None)
907
Ezio Melotti4841fd62010-11-05 15:43:40 +0000908 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000909
Raymond Hettinger35a88362009-04-09 00:08:24 +0000910 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000911
912
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000913 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000914 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000915
Ezio Melotti9794a262010-11-04 14:52:13 +0000916 Test that *obj* is (or is not) an instance of *cls* (which can be a
917 class or a tuple of classes, as supported by :func:`isinstance`).
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000918
Ezio Melotti4370b302010-11-03 20:39:14 +0000919 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000920
921
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000922
Ezio Melotti4370b302010-11-03 20:39:14 +0000923 It is also possible to check that exceptions and warnings are raised using
924 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000925
Ezio Melotti4370b302010-11-03 20:39:14 +0000926 +---------------------------------------------------------+--------------------------------------+------------+
927 | Method | Checks that | New in |
928 +=========================================================+======================================+============+
929 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | |
930 | <TestCase.assertRaises>` | | |
931 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +0000932 | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
933 | <TestCase.assertRaisesRegex>` | and the message matches `re` | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000934 +---------------------------------------------------------+--------------------------------------+------------+
935 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
936 | <TestCase.assertWarns>` | | |
937 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +0000938 | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
939 | <TestCase.assertWarnsRegex>` | and the message matches `re` | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000940 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000941
Georg Brandl7f01a132009-09-16 15:58:14 +0000942 .. method:: assertRaises(exception, callable, *args, **kwds)
Georg Brandl7f01a132009-09-16 15:58:14 +0000943 assertRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000944
945 Test that an exception is raised when *callable* is called with any
946 positional or keyword arguments that are also passed to
947 :meth:`assertRaises`. The test passes if *exception* is raised, is an
948 error if another exception is raised, or fails if no exception is raised.
949 To catch any of a group of exceptions, a tuple containing the exception
950 classes may be passed as *exception*.
951
Georg Brandl7f01a132009-09-16 15:58:14 +0000952 If only the *exception* argument is given, returns a context manager so
953 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000954
Michael Foord41531f22010-02-05 21:13:40 +0000955 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000956 do_something()
957
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000958 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000959 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000960 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000961
Georg Brandl8a1caa22010-07-29 16:01:11 +0000962 with self.assertRaises(SomeException) as cm:
963 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000964
Georg Brandl8a1caa22010-07-29 16:01:11 +0000965 the_exception = cm.exception
966 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000967
Ezio Melotti49008232010-02-08 21:57:48 +0000968 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000969 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000970
Ezio Melotti49008232010-02-08 21:57:48 +0000971 .. versionchanged:: 3.2
972 Added the :attr:`exception` attribute.
973
Benjamin Peterson52baa292009-03-24 00:56:30 +0000974
Ezio Melottied3a7d22010-12-01 02:32:32 +0000975 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
976 assertRaisesRegex(exception, regex)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000977
Ezio Melottied3a7d22010-12-01 02:32:32 +0000978 Like :meth:`assertRaises` but also tests that *regex* matches
979 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000980 a regular expression object or a string containing a regular expression
981 suitable for use by :func:`re.search`. Examples::
982
Ezio Melottied3a7d22010-12-01 02:32:32 +0000983 self.assertRaisesRegex(ValueError, 'invalid literal for.*XYZ$',
984 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000985
986 or::
987
Ezio Melottied3a7d22010-12-01 02:32:32 +0000988 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000989 int('XYZ')
990
Georg Brandl419e3de2010-12-01 15:44:25 +0000991 .. versionadded:: 3.1
992 under the name ``assertRaisesRegexp``.
Ezio Melottied3a7d22010-12-01 02:32:32 +0000993 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +0000994 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000995
996
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000997 .. method:: assertWarns(warning, callable, *args, **kwds)
998 assertWarns(warning)
999
1000 Test that a warning is triggered when *callable* is called with any
1001 positional or keyword arguments that are also passed to
1002 :meth:`assertWarns`. The test passes if *warning* is triggered and
1003 fails if it isn't. Also, any unexpected exception is an error.
1004 To catch any of a group of warnings, a tuple containing the warning
1005 classes may be passed as *warnings*.
1006
1007 If only the *warning* argument is given, returns a context manager so
1008 that the code under test can be written inline rather than as a function::
1009
1010 with self.assertWarns(SomeWarning):
1011 do_something()
1012
1013 The context manager will store the caught warning object in its
1014 :attr:`warning` attribute, and the source line which triggered the
1015 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1016 This can be useful if the intention is to perform additional checks
1017 on the exception raised::
1018
1019 with self.assertWarns(SomeWarning) as cm:
1020 do_something()
1021
1022 self.assertIn('myfile.py', cm.filename)
1023 self.assertEqual(320, cm.lineno)
1024
1025 This method works regardless of the warning filters in place when it
1026 is called.
1027
1028 .. versionadded:: 3.2
1029
1030
Ezio Melottied3a7d22010-12-01 02:32:32 +00001031 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
1032 assertWarnsRegex(warning, regex)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001033
Ezio Melottied3a7d22010-12-01 02:32:32 +00001034 Like :meth:`assertWarns` but also tests that *regex* matches on the
1035 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001036 object or a string containing a regular expression suitable for use
1037 by :func:`re.search`. Example::
1038
Ezio Melottied3a7d22010-12-01 02:32:32 +00001039 self.assertWarnsRegex(DeprecationWarning,
1040 r'legacy_function\(\) is deprecated',
1041 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001042
1043 or::
1044
Ezio Melottied3a7d22010-12-01 02:32:32 +00001045 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001046 frobnicate('/etc/passwd')
1047
1048 .. versionadded:: 3.2
1049
1050
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001051
Ezio Melotti4370b302010-11-03 20:39:14 +00001052 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001053
Ezio Melotti4370b302010-11-03 20:39:14 +00001054 +---------------------------------------+--------------------------------+--------------+
1055 | Method | Checks that | New in |
1056 +=======================================+================================+==============+
1057 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1058 | <TestCase.assertAlmostEqual>` | | |
1059 +---------------------------------------+--------------------------------+--------------+
1060 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1061 | <TestCase.assertNotAlmostEqual>` | | |
1062 +---------------------------------------+--------------------------------+--------------+
1063 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1064 | <TestCase.assertGreater>` | | |
1065 +---------------------------------------+--------------------------------+--------------+
1066 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1067 | <TestCase.assertGreaterEqual>` | | |
1068 +---------------------------------------+--------------------------------+--------------+
1069 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1070 | <TestCase.assertLess>` | | |
1071 +---------------------------------------+--------------------------------+--------------+
1072 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1073 | <TestCase.assertLessEqual>` | | |
1074 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001075 | :meth:`assertRegex(s, re) | ``regex.search(s)`` | 3.1 |
1076 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001077 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001078 | :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 |
1079 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001080 +---------------------------------------+--------------------------------+--------------+
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001081 | :meth:`assertCountEqual(a, b) | `a` and `b` have the same | 3.2 |
1082 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001083 | | regardless of their order | |
1084 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001085
1086
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001087 .. method:: assertAlmostEqual(actual, expected, places=7, msg=None, delta=None)
1088 assertNotAlmostEqual(actual, expected, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001089
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001090 Test that *actual* and *expected* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001091 equal by computing the difference, rounding to the given number of
1092 decimal *places* (default 7), and comparing to zero. Note that these
1093 methods round the values to the given number of *decimal places* (i.e.
1094 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001095
Ezio Melotti4370b302010-11-03 20:39:14 +00001096 If *delta* is supplied instead of *places* then the difference
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001097 between *actual* and *expected* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001098
Ezio Melotti4370b302010-11-03 20:39:14 +00001099 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001100
Ezio Melotti4370b302010-11-03 20:39:14 +00001101 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001102 :meth:`assertAlmostEqual` automatically considers almost equal objects
1103 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1104 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001105
Ezio Melotti4370b302010-11-03 20:39:14 +00001106
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001107 .. method:: assertGreater(actual, expected, msg=None)
1108 assertGreaterEqual(actual, expected, msg=None)
1109 assertLess(actual, expected, msg=None)
1110 assertLessEqual(actual, expected, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001111
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001112 Test that *actual* is respectively >, >=, < or <= than *expected* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001113 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001114
1115 >>> self.assertGreaterEqual(3, 4)
1116 AssertionError: "3" unexpectedly not greater than or equal to "4"
1117
1118 .. versionadded:: 3.1
1119
1120
Ezio Melottied3a7d22010-12-01 02:32:32 +00001121 .. method:: assertRegex(text, regex, msg=None)
1122 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001123
Ezio Melottied3a7d22010-12-01 02:32:32 +00001124 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001125 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001126 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001127 may be a regular expression object or a string containing a regular
1128 expression suitable for use by :func:`re.search`.
1129
Georg Brandl419e3de2010-12-01 15:44:25 +00001130 .. versionadded:: 3.1
1131 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001132 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001133 The method ``assertRegexpMatches()`` has been renamed to
1134 :meth:`.assertRegex`.
1135 .. versionadded:: 3.2
1136 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001137
1138
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001139 .. method:: assertDictContainsSubset(subset, dictionary, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001140
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001141 Tests whether the key/value pairs in *dictionary* are a superset of
1142 those in *subset*. If not, an error message listing the missing keys
1143 and mismatched values is generated.
Ezio Melotti4370b302010-11-03 20:39:14 +00001144
Raymond Hettinger8ebe27f2010-12-21 19:24:26 +00001145 Note, the arguments are in the opposite order of what the method name
1146 dictates. Instead, consider using the set-methods on :ref:`dictionary
1147 views <dict-views>`, for example: ``d.keys() <= e.keys()`` or
1148 ``d.items() <= d.items()``.
1149
Ezio Melotti4370b302010-11-03 20:39:14 +00001150 .. versionadded:: 3.1
Raymond Hettinger8ebe27f2010-12-21 19:24:26 +00001151 .. deprecated:: 3.2
Ezio Melotti4370b302010-11-03 20:39:14 +00001152
1153
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001154 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001155
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001156 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001157 regardless of their order. When they don't, an error message listing the
1158 differences between the sequences will be generated.
1159
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001160 Duplicate elements are *not* ignored when comparing *first* and
1161 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001162 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001163 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001164 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001165
Ezio Melotti4370b302010-11-03 20:39:14 +00001166 .. versionadded:: 3.2
1167
Ezio Melotti4370b302010-11-03 20:39:14 +00001168 .. method:: assertSameElements(actual, expected, msg=None)
1169
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001170 Test that sequence *actual* contains the same elements as *expected*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001171 regardless of their order. When they don't, an error message listing
1172 the differences between the sequences will be generated.
1173
1174 Duplicate elements are ignored when comparing *actual* and *expected*.
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001175 It is the equivalent of ``assertEqual(set(actual), set(expected))``
Ezio Melotti4370b302010-11-03 20:39:14 +00001176 but it works with sequences of unhashable objects as well. Because
1177 duplicates are ignored, this method has been deprecated in favour of
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001178 :meth:`assertCountEqual`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001179
Ezio Melotti4370b302010-11-03 20:39:14 +00001180 .. versionadded:: 3.1
1181 .. deprecated:: 3.2
1182
1183
Ezio Melotti22170ed2010-11-20 09:57:27 +00001184 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001185
Ezio Melotti22170ed2010-11-20 09:57:27 +00001186 The :meth:`assertEqual` method dispatches the equality check for objects of
1187 the same type to different type-specific methods. These methods are already
1188 implemented for most of the built-in types, but it's also possible to
1189 register new methods using :meth:`addTypeEqualityFunc`:
1190
1191 .. method:: addTypeEqualityFunc(typeobj, function)
1192
1193 Registers a type-specific method called by :meth:`assertEqual` to check
1194 if two objects of exactly the same *typeobj* (not subclasses) compare
1195 equal. *function* must take two positional arguments and a third msg=None
1196 keyword argument just as :meth:`assertEqual` does. It must raise
1197 :data:`self.failureException(msg) <failureException>` when inequality
1198 between the first two parameters is detected -- possibly providing useful
1199 information and explaining the inequalities in details in the error
1200 message.
1201
1202 .. versionadded:: 3.1
1203
1204 The list of type-specific methods automatically used by
1205 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1206 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001207
1208 +-----------------------------------------+-----------------------------+--------------+
1209 | Method | Used to compare | New in |
1210 +=========================================+=============================+==============+
1211 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1212 | <TestCase.assertMultiLineEqual>` | | |
1213 +-----------------------------------------+-----------------------------+--------------+
1214 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1215 | <TestCase.assertSequenceEqual>` | | |
1216 +-----------------------------------------+-----------------------------+--------------+
1217 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1218 | <TestCase.assertListEqual>` | | |
1219 +-----------------------------------------+-----------------------------+--------------+
1220 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1221 | <TestCase.assertTupleEqual>` | | |
1222 +-----------------------------------------+-----------------------------+--------------+
1223 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1224 | <TestCase.assertSetEqual>` | | |
1225 +-----------------------------------------+-----------------------------+--------------+
1226 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1227 | <TestCase.assertDictEqual>` | | |
1228 +-----------------------------------------+-----------------------------+--------------+
1229
1230
1231
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001232 .. method:: assertMultiLineEqual(actual, expected, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001233
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001234 Test that the multiline string *actual* is equal to the string *expected*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001235 When not equal a diff of the two strings highlighting the differences
1236 will be included in the error message. This method is used by default
1237 when comparing strings with :meth:`assertEqual`.
1238
Ezio Melotti4370b302010-11-03 20:39:14 +00001239 .. versionadded:: 3.1
1240
1241
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001242 .. method:: assertSequenceEqual(actual, expected, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001243
1244 Tests that two sequences are equal. If a *seq_type* is supplied, both
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001245 *actual* and *expected* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001246 be raised. If the sequences are different an error message is
1247 constructed that shows the difference between the two.
1248
Ezio Melotti22170ed2010-11-20 09:57:27 +00001249 This method is not called directly by :meth:`assertEqual`, but
1250 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001251 :meth:`assertTupleEqual`.
1252
1253 .. versionadded:: 3.1
1254
1255
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001256 .. method:: assertListEqual(actual, expected, msg=None)
1257 assertTupleEqual(actual, expected, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001258
1259 Tests that two lists or tuples are equal. If not an error message is
1260 constructed that shows only the differences between the two. An error
1261 is also raised if either of the parameters are of the wrong type.
1262 These methods are used by default when comparing lists or tuples with
1263 :meth:`assertEqual`.
1264
Ezio Melotti4370b302010-11-03 20:39:14 +00001265 .. versionadded:: 3.1
1266
1267
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001268 .. method:: assertSetEqual(actual, expected, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001269
1270 Tests that two sets are equal. If not, an error message is constructed
1271 that lists the differences between the sets. This method is used by
1272 default when comparing sets or frozensets with :meth:`assertEqual`.
1273
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001274 Fails if either of *actual* or *expected* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001275 method.
1276
Ezio Melotti4370b302010-11-03 20:39:14 +00001277 .. versionadded:: 3.1
1278
1279
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001280 .. method:: assertDictEqual(actual, expected, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001281
1282 Test that two dictionaries are equal. If not, an error message is
1283 constructed that shows the differences in the dictionaries. This
1284 method will be used by default to compare dictionaries in
1285 calls to :meth:`assertEqual`.
1286
Ezio Melotti4370b302010-11-03 20:39:14 +00001287 .. versionadded:: 3.1
1288
1289
1290
Ezio Melotti22170ed2010-11-20 09:57:27 +00001291 .. _other-methods-and-attrs:
1292
Ezio Melotti4370b302010-11-03 20:39:14 +00001293 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001294
Benjamin Peterson52baa292009-03-24 00:56:30 +00001295
Georg Brandl7f01a132009-09-16 15:58:14 +00001296 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001297
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001298 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001299 the error message.
1300
1301
1302 .. attribute:: failureException
1303
1304 This class attribute gives the exception raised by the test method. If a
1305 test framework needs to use a specialized exception, possibly to carry
1306 additional information, it must subclass this exception in order to "play
1307 fair" with the framework. The initial value of this attribute is
1308 :exc:`AssertionError`.
1309
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001310
1311 .. attribute:: longMessage
1312
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001313 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001314 :ref:`assert methods <assert-methods>` will be appended to the end of the
1315 normal failure message. The normal messages contain useful information
1316 about the objects involved, for example the message from assertEqual
1317 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001318 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001319 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001320
Michael Foord5074df62010-12-03 00:53:09 +00001321 This attribute defaults to ``True``. If set to False then a custom message
1322 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001323
1324 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001325 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001326
Raymond Hettinger35a88362009-04-09 00:08:24 +00001327 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001328
1329
Michael Foord98b3e762010-06-05 21:59:55 +00001330 .. attribute:: maxDiff
1331
1332 This attribute controls the maximum length of diffs output by assert
1333 methods that report diffs on failure. It defaults to 80*8 characters.
1334 Assert methods affected by this attribute are
1335 :meth:`assertSequenceEqual` (including all the sequence comparison
1336 methods that delegate to it), :meth:`assertDictEqual` and
1337 :meth:`assertMultiLineEqual`.
1338
1339 Setting ``maxDiff`` to None means that there is no maximum length of
1340 diffs.
1341
1342 .. versionadded:: 3.2
1343
1344
Benjamin Peterson52baa292009-03-24 00:56:30 +00001345 Testing frameworks can use the following methods to collect information on
1346 the test:
1347
1348
1349 .. method:: countTestCases()
1350
1351 Return the number of tests represented by this test object. For
1352 :class:`TestCase` instances, this will always be ``1``.
1353
1354
1355 .. method:: defaultTestResult()
1356
1357 Return an instance of the test result class that should be used for this
1358 test case class (if no other result instance is provided to the
1359 :meth:`run` method).
1360
1361 For :class:`TestCase` instances, this will always be an instance of
1362 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1363 as necessary.
1364
1365
1366 .. method:: id()
1367
1368 Return a string identifying the specific test case. This is usually the
1369 full name of the test method, including the module and class name.
1370
1371
1372 .. method:: shortDescription()
1373
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001374 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001375 has been provided. The default implementation of this method
1376 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001377 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001378
Georg Brandl419e3de2010-12-01 15:44:25 +00001379 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001380 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001381 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001382 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001383 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001384
Georg Brandl116aa622007-08-15 14:28:22 +00001385
Georg Brandl7f01a132009-09-16 15:58:14 +00001386 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001387
1388 Add a function to be called after :meth:`tearDown` to cleanup resources
1389 used during the test. Functions will be called in reverse order to the
1390 order they are added (LIFO). They are called with any arguments and
1391 keyword arguments passed into :meth:`addCleanup` when they are
1392 added.
1393
1394 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1395 then any cleanup functions added will still be called.
1396
Georg Brandl853947a2010-01-31 18:53:23 +00001397 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001398
1399
1400 .. method:: doCleanups()
1401
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001402 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001403 after :meth:`setUp` if :meth:`setUp` raises an exception.
1404
1405 It is responsible for calling all the cleanup functions added by
1406 :meth:`addCleanup`. If you need cleanup functions to be called
1407 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1408 yourself.
1409
1410 :meth:`doCleanups` pops methods off the stack of cleanup
1411 functions one at a time, so it can be called at any time.
1412
Georg Brandl853947a2010-01-31 18:53:23 +00001413 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001414
1415
Georg Brandl7f01a132009-09-16 15:58:14 +00001416.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001417
1418 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001419 allows the test runner to drive the test, but does not provide the methods
1420 which test code can use to check and report errors. This is used to create
1421 test cases using legacy test code, allowing it to be integrated into a
1422 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001423
1424
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001425.. _deprecated-aliases:
1426
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001427Deprecated aliases
1428##################
1429
1430For historical reasons, some of the :class:`TestCase` methods had one or more
1431aliases that are now deprecated. The following table lists the correct names
1432along with their deprecated aliases:
1433
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001434 ============================== ====================== ======================
1435 Method Name Deprecated alias Deprecated alias
1436 ============================== ====================== ======================
1437 :meth:`.assertEqual` failUnlessEqual assertEquals
1438 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1439 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001440 :meth:`.assertFalse` failIf
1441 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001442 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1443 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001444 :meth:`.assertRegex` assertRegexpMatches
1445 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001446 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001447
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001448 .. deprecated-removed:: 3.1 3.3
1449 the fail* aliases listed in the second column.
1450 .. deprecated:: 3.2
1451 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001452 .. deprecated:: 3.2
1453 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1454 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001455
1456
Benjamin Peterson52baa292009-03-24 00:56:30 +00001457.. _testsuite-objects:
1458
Benjamin Peterson52baa292009-03-24 00:56:30 +00001459Grouping tests
1460~~~~~~~~~~~~~~
1461
Georg Brandl7f01a132009-09-16 15:58:14 +00001462.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001463
1464 This class represents an aggregation of individual tests cases and test suites.
1465 The class presents the interface needed by the test runner to allow it to be run
1466 as any other test case. Running a :class:`TestSuite` instance is the same as
1467 iterating over the suite, running each test individually.
1468
1469 If *tests* is given, it must be an iterable of individual test cases or other
1470 test suites that will be used to build the suite initially. Additional methods
1471 are provided to add test cases and suites to the collection later on.
1472
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001473 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1474 they do not actually implement a test. Instead, they are used to aggregate
1475 tests into groups of tests that should be run together. Some additional
1476 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001477
1478
1479 .. method:: TestSuite.addTest(test)
1480
1481 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1482
1483
1484 .. method:: TestSuite.addTests(tests)
1485
1486 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1487 instances to this test suite.
1488
Benjamin Petersond2397752009-06-27 23:45:02 +00001489 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1490 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001491
1492 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1493
1494
1495 .. method:: run(result)
1496
1497 Run the tests associated with this suite, collecting the result into the
1498 test result object passed as *result*. Note that unlike
1499 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1500 be passed in.
1501
1502
1503 .. method:: debug()
1504
1505 Run the tests associated with this suite without collecting the
1506 result. This allows exceptions raised by the test to be propagated to the
1507 caller and can be used to support running tests under a debugger.
1508
1509
1510 .. method:: countTestCases()
1511
1512 Return the number of tests represented by this test object, including all
1513 individual tests and sub-suites.
1514
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001515
1516 .. method:: __iter__()
1517
1518 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1519 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1520 that this method maybe called several times on a single suite
1521 (for example when counting tests or comparing for equality)
1522 so the tests returned must be the same for repeated iterations.
1523
Georg Brandl853947a2010-01-31 18:53:23 +00001524 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001525 In earlier versions the :class:`TestSuite` accessed tests directly rather
1526 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1527 for providing tests.
1528
Benjamin Peterson52baa292009-03-24 00:56:30 +00001529 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1530 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1531
1532
Benjamin Peterson52baa292009-03-24 00:56:30 +00001533Loading and running tests
1534~~~~~~~~~~~~~~~~~~~~~~~~~
1535
Georg Brandl116aa622007-08-15 14:28:22 +00001536.. class:: TestLoader()
1537
Benjamin Peterson52baa292009-03-24 00:56:30 +00001538 The :class:`TestLoader` class is used to create test suites from classes and
1539 modules. Normally, there is no need to create an instance of this class; the
1540 :mod:`unittest` module provides an instance that can be shared as
1541 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1542 customization of some configurable properties.
1543
1544 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001545
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001546
Benjamin Peterson52baa292009-03-24 00:56:30 +00001547 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001548
Benjamin Peterson52baa292009-03-24 00:56:30 +00001549 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1550 :class:`testCaseClass`.
1551
1552
1553 .. method:: loadTestsFromModule(module)
1554
1555 Return a suite of all tests cases contained in the given module. This
1556 method searches *module* for classes derived from :class:`TestCase` and
1557 creates an instance of the class for each test method defined for the
1558 class.
1559
Georg Brandle720c0a2009-04-27 16:20:50 +00001560 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001561
1562 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1563 convenient in sharing fixtures and helper functions, defining test
1564 methods on base classes that are not intended to be instantiated
1565 directly does not play well with this method. Doing so, however, can
1566 be useful when the fixtures are different and defined in subclasses.
1567
Benjamin Petersond2397752009-06-27 23:45:02 +00001568 If a module provides a ``load_tests`` function it will be called to
1569 load the tests. This allows modules to customize test loading.
1570 This is the `load_tests protocol`_.
1571
Georg Brandl853947a2010-01-31 18:53:23 +00001572 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001573 Support for ``load_tests`` added.
1574
Benjamin Peterson52baa292009-03-24 00:56:30 +00001575
Georg Brandl7f01a132009-09-16 15:58:14 +00001576 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001577
1578 Return a suite of all tests cases given a string specifier.
1579
1580 The specifier *name* is a "dotted name" that may resolve either to a
1581 module, a test case class, a test method within a test case class, a
1582 :class:`TestSuite` instance, or a callable object which returns a
1583 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1584 applied in the order listed here; that is, a method on a possible test
1585 case class will be picked up as "a test method within a test case class",
1586 rather than "a callable object".
1587
1588 For example, if you have a module :mod:`SampleTests` containing a
1589 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1590 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001591 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1592 return a suite which will run all three test methods. Using the specifier
1593 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1594 suite which will run only the :meth:`test_two` test method. The specifier
1595 can refer to modules and packages which have not been imported; they will
1596 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001597
1598 The method optionally resolves *name* relative to the given *module*.
1599
1600
Georg Brandl7f01a132009-09-16 15:58:14 +00001601 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001602
1603 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1604 than a single name. The return value is a test suite which supports all
1605 the tests defined for each name.
1606
1607
1608 .. method:: getTestCaseNames(testCaseClass)
1609
1610 Return a sorted sequence of method names found within *testCaseClass*;
1611 this should be a subclass of :class:`TestCase`.
1612
Benjamin Petersond2397752009-06-27 23:45:02 +00001613
1614 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1615
1616 Find and return all test modules from the specified start directory,
1617 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001618 *pattern* will be loaded. (Using shell style pattern matching.) Only
1619 module names that are importable (i.e. are valid Python identifiers) will
1620 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001621
1622 All test modules must be importable from the top level of the project. If
1623 the start directory is not the top level directory then the top level
1624 directory must be specified separately.
1625
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001626 If importing a module fails, for example due to a syntax error, then this
1627 will be recorded as a single error and discovery will continue.
1628
Benjamin Petersond2397752009-06-27 23:45:02 +00001629 If a test package name (directory with :file:`__init__.py`) matches the
1630 pattern then the package will be checked for a ``load_tests``
1631 function. If this exists then it will be called with *loader*, *tests*,
1632 *pattern*.
1633
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001634 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001635 ``load_tests`` is responsible for loading all tests in the package.
1636
1637 The pattern is deliberately not stored as a loader attribute so that
1638 packages can continue discovery themselves. *top_level_dir* is stored so
1639 ``load_tests`` does not need to pass this argument in to
1640 ``loader.discover()``.
1641
Benjamin Petersonb48af542010-04-11 20:43:16 +00001642 *start_dir* can be a dotted module name as well as a directory.
1643
Georg Brandl853947a2010-01-31 18:53:23 +00001644 .. versionadded:: 3.2
1645
Benjamin Petersond2397752009-06-27 23:45:02 +00001646
Benjamin Peterson52baa292009-03-24 00:56:30 +00001647 The following attributes of a :class:`TestLoader` can be configured either by
1648 subclassing or assignment on an instance:
1649
1650
1651 .. attribute:: testMethodPrefix
1652
1653 String giving the prefix of method names which will be interpreted as test
1654 methods. The default value is ``'test'``.
1655
1656 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1657 methods.
1658
1659
1660 .. attribute:: sortTestMethodsUsing
1661
1662 Function to be used to compare method names when sorting them in
1663 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1664
1665
1666 .. attribute:: suiteClass
1667
1668 Callable object that constructs a test suite from a list of tests. No
1669 methods on the resulting object are needed. The default value is the
1670 :class:`TestSuite` class.
1671
1672 This affects all the :meth:`loadTestsFrom\*` methods.
1673
1674
Benjamin Peterson52baa292009-03-24 00:56:30 +00001675.. class:: TestResult
1676
1677 This class is used to compile information about which tests have succeeded
1678 and which have failed.
1679
1680 A :class:`TestResult` object stores the results of a set of tests. The
1681 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1682 properly recorded; test authors do not need to worry about recording the
1683 outcome of tests.
1684
1685 Testing frameworks built on top of :mod:`unittest` may want access to the
1686 :class:`TestResult` object generated by running a set of tests for reporting
1687 purposes; a :class:`TestResult` instance is returned by the
1688 :meth:`TestRunner.run` method for this purpose.
1689
1690 :class:`TestResult` instances have the following attributes that will be of
1691 interest when inspecting the results of running a set of tests:
1692
1693
1694 .. attribute:: errors
1695
1696 A list containing 2-tuples of :class:`TestCase` instances and strings
1697 holding formatted tracebacks. Each tuple represents a test which raised an
1698 unexpected exception.
1699
Benjamin Peterson52baa292009-03-24 00:56:30 +00001700 .. attribute:: failures
1701
1702 A list containing 2-tuples of :class:`TestCase` instances and strings
1703 holding formatted tracebacks. Each tuple represents a test where a failure
1704 was explicitly signalled using the :meth:`TestCase.fail\*` or
1705 :meth:`TestCase.assert\*` methods.
1706
Benjamin Peterson52baa292009-03-24 00:56:30 +00001707 .. attribute:: skipped
1708
1709 A list containing 2-tuples of :class:`TestCase` instances and strings
1710 holding the reason for skipping the test.
1711
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001712 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001713
1714 .. attribute:: expectedFailures
1715
Georg Brandl6faee4e2010-09-21 14:48:28 +00001716 A list containing 2-tuples of :class:`TestCase` instances and strings
1717 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001718 of the test case.
1719
1720 .. attribute:: unexpectedSuccesses
1721
1722 A list containing :class:`TestCase` instances that were marked as expected
1723 failures, but succeeded.
1724
1725 .. attribute:: shouldStop
1726
1727 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1728
1729
1730 .. attribute:: testsRun
1731
1732 The total number of tests run so far.
1733
1734
Georg Brandl12037202010-12-02 22:35:25 +00001735 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001736
1737 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1738 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1739 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1740 fails or errors. Any output is also attached to the failure / error message.
1741
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001742 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001743
1744
1745 .. attribute:: failfast
1746
1747 If set to true :meth:`stop` will be called on the first failure or error,
1748 halting the test run.
1749
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001750 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001751
1752
Benjamin Peterson52baa292009-03-24 00:56:30 +00001753 .. method:: wasSuccessful()
1754
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001755 Return ``True`` if all tests run so far have passed, otherwise returns
1756 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001757
1758
1759 .. method:: stop()
1760
1761 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001762 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001763 :class:`TestRunner` objects should respect this flag and return without
1764 running any additional tests.
1765
1766 For example, this feature is used by the :class:`TextTestRunner` class to
1767 stop the test framework when the user signals an interrupt from the
1768 keyboard. Interactive tools which provide :class:`TestRunner`
1769 implementations can use this in a similar manner.
1770
1771 The following methods of the :class:`TestResult` class are used to maintain
1772 the internal data structures, and may be extended in subclasses to support
1773 additional reporting requirements. This is particularly useful in building
1774 tools which support interactive reporting while tests are being run.
1775
1776
1777 .. method:: startTest(test)
1778
1779 Called when the test case *test* is about to be run.
1780
Benjamin Peterson52baa292009-03-24 00:56:30 +00001781 .. method:: stopTest(test)
1782
1783 Called after the test case *test* has been executed, regardless of the
1784 outcome.
1785
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001786 .. method:: startTestRun(test)
1787
1788 Called once before any tests are executed.
1789
Georg Brandl853947a2010-01-31 18:53:23 +00001790 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001791
1792
1793 .. method:: stopTestRun(test)
1794
Ezio Melotti176d6c42010-01-27 20:58:07 +00001795 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001796
Georg Brandl853947a2010-01-31 18:53:23 +00001797 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001798
1799
Benjamin Peterson52baa292009-03-24 00:56:30 +00001800 .. method:: addError(test, err)
1801
1802 Called when the test case *test* raises an unexpected exception *err* is a
1803 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1804 traceback)``.
1805
1806 The default implementation appends a tuple ``(test, formatted_err)`` to
1807 the instance's :attr:`errors` attribute, where *formatted_err* is a
1808 formatted traceback derived from *err*.
1809
1810
1811 .. method:: addFailure(test, err)
1812
Benjamin Petersond2397752009-06-27 23:45:02 +00001813 Called when the test case *test* signals a failure. *err* is a tuple of
1814 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001815
1816 The default implementation appends a tuple ``(test, formatted_err)`` to
1817 the instance's :attr:`failures` attribute, where *formatted_err* is a
1818 formatted traceback derived from *err*.
1819
1820
1821 .. method:: addSuccess(test)
1822
1823 Called when the test case *test* succeeds.
1824
1825 The default implementation does nothing.
1826
1827
1828 .. method:: addSkip(test, reason)
1829
1830 Called when the test case *test* is skipped. *reason* is the reason the
1831 test gave for skipping.
1832
1833 The default implementation appends a tuple ``(test, reason)`` to the
1834 instance's :attr:`skipped` attribute.
1835
1836
1837 .. method:: addExpectedFailure(test, err)
1838
1839 Called when the test case *test* fails, but was marked with the
1840 :func:`expectedFailure` decorator.
1841
1842 The default implementation appends a tuple ``(test, formatted_err)`` to
1843 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1844 is a formatted traceback derived from *err*.
1845
1846
1847 .. method:: addUnexpectedSuccess(test)
1848
1849 Called when the test case *test* was marked with the
1850 :func:`expectedFailure` decorator, but succeeded.
1851
1852 The default implementation appends the test to the instance's
1853 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001854
Georg Brandl67b21b72010-08-17 15:07:14 +00001855
Michael Foord34c94622010-02-10 15:51:42 +00001856.. class:: TextTestResult(stream, descriptions, verbosity)
1857
Georg Brandl67b21b72010-08-17 15:07:14 +00001858 A concrete implementation of :class:`TestResult` used by the
1859 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001860
Georg Brandl67b21b72010-08-17 15:07:14 +00001861 .. versionadded:: 3.2
1862 This class was previously named ``_TextTestResult``. The old name still
1863 exists as an alias but is deprecated.
1864
Georg Brandl116aa622007-08-15 14:28:22 +00001865
1866.. data:: defaultTestLoader
1867
1868 Instance of the :class:`TestLoader` class intended to be shared. If no
1869 customization of the :class:`TestLoader` is needed, this instance can be used
1870 instead of repeatedly creating new instances.
1871
1872
Michael Foordd218e952011-01-03 12:55:11 +00001873.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, runnerclass=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001874
Michael Foordd218e952011-01-03 12:55:11 +00001875 A basic test runner implementation that outputs results to a stream. If *stream*
1876 is `None`, the default, `sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001877 has a few configurable parameters, but is essentially very simple. Graphical
1878 applications which run test suites should provide alternate implementations.
1879
Ezio Melotti60901872010-12-01 00:56:10 +00001880 By default this runner shows :exc:`DeprecationWarning`,
1881 :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` even if they are
1882 :ref:`ignored by default <warning-ignored>`. Deprecation warnings caused by
1883 :ref:`deprecated unittest methods <deprecated-aliases>` are also
1884 special-cased and, when the warning filters are ``'default'`` or ``'always'``,
1885 they will appear only once per-module, in order to avoid too many warning
Georg Brandl46402372010-12-04 19:06:18 +00001886 messages. This behavior can be overridden using the :option:`-Wd` or
Ezio Melotti60901872010-12-01 00:56:10 +00001887 :option:`-Wa` options and leaving *warnings* to ``None``.
1888
Michael Foordd218e952011-01-03 12:55:11 +00001889 .. versionchanged:: 3.2
1890 Added the ``warnings`` argument.
1891
1892 .. versionchanged:: 3.2
1893 The default stream is set to `sys.stderr` at instantiation time rather
1894 than import time.
1895
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001896 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001897
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001898 This method returns the instance of ``TestResult`` used by :meth:`run`.
1899 It is not intended to be called directly, but can be overridden in
1900 subclasses to provide a custom ``TestResult``.
1901
Michael Foord34c94622010-02-10 15:51:42 +00001902 ``_makeResult()`` instantiates the class or callable passed in the
1903 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001904 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001905 The result class is instantiated with the following arguments::
1906
1907 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001908
Ezio Melotti60901872010-12-01 00:56:10 +00001909
Georg Brandl419e3de2010-12-01 15:44:25 +00001910.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
1911 testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1, \
1912 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001913
1914 A command-line program that runs a set of tests; this is primarily for making
1915 test modules conveniently executable. The simplest use for this function is to
1916 include the following line at the end of a test script::
1917
1918 if __name__ == '__main__':
1919 unittest.main()
1920
Benjamin Petersond2397752009-06-27 23:45:02 +00001921 You can run tests with more detailed information by passing in the verbosity
1922 argument::
1923
1924 if __name__ == '__main__':
1925 unittest.main(verbosity=2)
1926
Georg Brandl116aa622007-08-15 14:28:22 +00001927 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001928 created instance of it. By default ``main`` calls :func:`sys.exit` with
1929 an exit code indicating success or failure of the tests run.
1930
1931 ``main`` supports being used from the interactive interpreter by passing in the
1932 argument ``exit=False``. This displays the result on standard output without
1933 calling :func:`sys.exit`::
1934
1935 >>> from unittest import main
1936 >>> main(module='test_module', exit=False)
1937
Benjamin Petersonb48af542010-04-11 20:43:16 +00001938 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00001939 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001940
Ezio Melotti60901872010-12-01 00:56:10 +00001941 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
1942 that should be used while running the tests. If it's not specified, it will
1943 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
1944 otherwise it will be set to ``'default'``.
1945
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001946 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1947 This stores the result of the tests run as the ``result`` attribute.
1948
Éric Araujo971dc012010-12-16 03:13:05 +00001949 .. versionchanged:: 3.1
1950 The ``exit`` parameter was added.
1951
Georg Brandl853947a2010-01-31 18:53:23 +00001952 .. versionchanged:: 3.2
Éric Araujo971dc012010-12-16 03:13:05 +00001953 The ``verbosity``, ``failfast``, ``catchbreak``, ``buffer``
Ezio Melotti60901872010-12-01 00:56:10 +00001954 and ``warnings`` parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001955
1956
1957load_tests Protocol
1958###################
1959
Georg Brandl853947a2010-01-31 18:53:23 +00001960.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001961
Benjamin Petersond2397752009-06-27 23:45:02 +00001962Modules or packages can customize how tests are loaded from them during normal
1963test runs or test discovery by implementing a function called ``load_tests``.
1964
1965If a test module defines ``load_tests`` it will be called by
1966:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1967
1968 load_tests(loader, standard_tests, None)
1969
1970It should return a :class:`TestSuite`.
1971
1972*loader* is the instance of :class:`TestLoader` doing the loading.
1973*standard_tests* are the tests that would be loaded by default from the
1974module. It is common for test modules to only want to add or remove tests
1975from the standard set of tests.
1976The third argument is used when loading packages as part of test discovery.
1977
1978A typical ``load_tests`` function that loads tests from a specific set of
1979:class:`TestCase` classes may look like::
1980
1981 test_cases = (TestCase1, TestCase2, TestCase3)
1982
1983 def load_tests(loader, tests, pattern):
1984 suite = TestSuite()
1985 for test_class in test_cases:
1986 tests = loader.loadTestsFromTestCase(test_class)
1987 suite.addTests(tests)
1988 return suite
1989
1990If discovery is started, either from the command line or by calling
1991:meth:`TestLoader.discover`, with a pattern that matches a package
1992name then the package :file:`__init__.py` will be checked for ``load_tests``.
1993
1994.. note::
1995
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001996 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00001997 that start with 'test' but *won't* match any test directories.
1998
1999 A pattern like 'test*' will match test packages as well as
2000 modules.
2001
2002If the package :file:`__init__.py` defines ``load_tests`` then it will be
2003called and discovery not continued into the package. ``load_tests``
2004is called with the following arguments::
2005
2006 load_tests(loader, standard_tests, pattern)
2007
2008This should return a :class:`TestSuite` representing all the tests
2009from the package. (``standard_tests`` will only contain tests
2010collected from :file:`__init__.py`.)
2011
2012Because the pattern is passed into ``load_tests`` the package is free to
2013continue (and potentially modify) test discovery. A 'do nothing'
2014``load_tests`` function for a test package would look like::
2015
2016 def load_tests(loader, standard_tests, pattern):
2017 # top level directory cached on loader instance
2018 this_dir = os.path.dirname(__file__)
2019 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2020 standard_tests.addTests(package_tests)
2021 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002022
2023
2024Class and Module Fixtures
2025-------------------------
2026
2027Class and module level fixtures are implemented in :class:`TestSuite`. When
2028the test suite encounters a test from a new class then :meth:`tearDownClass`
2029from the previous class (if there is one) is called, followed by
2030:meth:`setUpClass` from the new class.
2031
2032Similarly if a test is from a different module from the previous test then
2033``tearDownModule`` from the previous module is run, followed by
2034``setUpModule`` from the new module.
2035
2036After all the tests have run the final ``tearDownClass`` and
2037``tearDownModule`` are run.
2038
2039Note that shared fixtures do not play well with [potential] features like test
2040parallelization and they break test isolation. They should be used with care.
2041
2042The default ordering of tests created by the unittest test loaders is to group
2043all tests from the same modules and classes together. This will lead to
2044``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2045module. If you randomize the order, so that tests from different modules and
2046classes are adjacent to each other, then these shared fixture functions may be
2047called multiple times in a single test run.
2048
2049Shared fixtures are not intended to work with suites with non-standard
2050ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2051support shared fixtures.
2052
2053If there are any exceptions raised during one of the shared fixture functions
2054the test is reported as an error. Because there is no corresponding test
2055instance an ``_ErrorHolder`` object (that has the same interface as a
2056:class:`TestCase`) is created to represent the error. If you are just using
2057the standard unittest test runner then this detail doesn't matter, but if you
2058are a framework author it may be relevant.
2059
2060
2061setUpClass and tearDownClass
2062~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2063
2064These must be implemented as class methods::
2065
2066 import unittest
2067
2068 class Test(unittest.TestCase):
2069 @classmethod
2070 def setUpClass(cls):
2071 cls._connection = createExpensiveConnectionObject()
2072
2073 @classmethod
2074 def tearDownClass(cls):
2075 cls._connection.destroy()
2076
2077If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2078then you must call up to them yourself. The implementations in
2079:class:`TestCase` are empty.
2080
2081If an exception is raised during a ``setUpClass`` then the tests in the class
2082are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002083have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
2084``SkipTest`` exception then the class will be reported as having been skipped
2085instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002086
2087
2088setUpModule and tearDownModule
2089~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2090
2091These should be implemented as functions::
2092
2093 def setUpModule():
2094 createConnection()
2095
2096 def tearDownModule():
2097 closeConnection()
2098
2099If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002100module will be run and the ``tearDownModule`` will not be run. If the exception is a
2101``SkipTest`` exception then the module will be reported as having been skipped
2102instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002103
2104
2105Signal Handling
2106---------------
2107
Georg Brandl419e3de2010-12-01 15:44:25 +00002108.. versionadded:: 3.2
2109
Éric Araujo8acb67c2010-11-26 23:31:07 +00002110The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002111along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2112more friendly handling of control-C during a test run. With catch break
2113behavior enabled control-C will allow the currently running test to complete,
2114and the test run will then end and report all the results so far. A second
2115control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002116
Michael Foordde4ceab2010-04-25 19:53:49 +00002117The control-c handling signal handler attempts to remain compatible with code or
2118tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2119handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2120i.e. it has been replaced by the system under test and delegated to, then it
2121calls the default handler. This will normally be the expected behavior by code
2122that replaces an installed handler and delegates to it. For individual tests
2123that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2124decorator can be used.
2125
2126There are a few utility functions for framework authors to enable control-c
2127handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002128
2129.. function:: installHandler()
2130
2131 Install the control-c handler. When a :const:`signal.SIGINT` is received
2132 (usually in response to the user pressing control-c) all registered results
2133 have :meth:`~TestResult.stop` called.
2134
Michael Foord469b1f02010-04-26 23:41:26 +00002135
Benjamin Petersonb48af542010-04-11 20:43:16 +00002136.. function:: registerResult(result)
2137
2138 Register a :class:`TestResult` object for control-c handling. Registering a
2139 result stores a weak reference to it, so it doesn't prevent the result from
2140 being garbage collected.
2141
Michael Foordde4ceab2010-04-25 19:53:49 +00002142 Registering a :class:`TestResult` object has no side-effects if control-c
2143 handling is not enabled, so test frameworks can unconditionally register
2144 all results they create independently of whether or not handling is enabled.
2145
Michael Foord469b1f02010-04-26 23:41:26 +00002146
Benjamin Petersonb48af542010-04-11 20:43:16 +00002147.. function:: removeResult(result)
2148
2149 Remove a registered result. Once a result has been removed then
2150 :meth:`~TestResult.stop` will no longer be called on that result object in
2151 response to a control-c.
2152
Michael Foord469b1f02010-04-26 23:41:26 +00002153
Michael Foordde4ceab2010-04-25 19:53:49 +00002154.. function:: removeHandler(function=None)
2155
2156 When called without arguments this function removes the control-c handler
2157 if it has been installed. This function can also be used as a test decorator
2158 to temporarily remove the handler whilst the test is being executed::
2159
2160 @unittest.removeHandler
2161 def test_signal_handling(self):
2162 ...