blob: 047d458d29bcf9a6373fb9787159259a99ca50bc [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
Michael Foord90efac72011-01-03 15:39:49 +0000100 The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is
101 a GUI tool for test discovery and execution. This is intended largely for ease of use
102 for those new to unit testing. For production environments it is recommended that
103 tests be driven by a continuous integration system such as `Hudson <http://hudson-ci.org/>`_
104 or `Buildbot <http://buildbot.net/trac>`_.
105
106
Georg Brandl116aa622007-08-15 14:28:22 +0000107.. _unittest-minimal-example:
108
109Basic example
110-------------
111
112The :mod:`unittest` module provides a rich set of tools for constructing and
113running tests. This section demonstrates that a small subset of the tools
114suffice to meet the needs of most users.
115
116Here is a short script to test three functions from the :mod:`random` module::
117
118 import random
119 import unittest
120
121 class TestSequenceFunctions(unittest.TestCase):
122
123 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000124 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +0000125
Benjamin Peterson52baa292009-03-24 00:56:30 +0000126 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000127 # make sure the shuffled sequence does not lose any elements
128 random.shuffle(self.seq)
129 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000130 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +0000131
Benjamin Peterson847a4112010-03-14 15:04:17 +0000132 # should raise an exception for an immutable sequence
133 self.assertRaises(TypeError, random.shuffle, (1,2,3))
134
Benjamin Peterson52baa292009-03-24 00:56:30 +0000135 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000136 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000137 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Benjamin Peterson52baa292009-03-24 00:56:30 +0000139 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000140 with self.assertRaises(ValueError):
141 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000142 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000143 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145 if __name__ == '__main__':
146 unittest.main()
147
Benjamin Peterson52baa292009-03-24 00:56:30 +0000148A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000149individual tests are defined with methods whose names start with the letters
150``test``. This naming convention informs the test runner about which methods
151represent tests.
152
Benjamin Peterson52baa292009-03-24 00:56:30 +0000153The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000154expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000155:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
156These methods are used instead of the :keyword:`assert` statement so the test
157runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000158
Benjamin Peterson52baa292009-03-24 00:56:30 +0000159When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
160method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
161defined, the test runner will invoke that method after each test. In the
162example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
163test.
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000166provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000167line, the above script produces an output that looks like this::
168
169 ...
170 ----------------------------------------------------------------------
171 Ran 3 tests in 0.000s
172
173 OK
174
175Instead of :func:`unittest.main`, there are other ways to run the tests with a
176finer level of control, less terse output, and no requirement to be run from the
177command line. For example, the last two lines may be replaced with::
178
179 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
180 unittest.TextTestRunner(verbosity=2).run(suite)
181
182Running the revised script from the interpreter or another script produces the
183following output::
184
Ezio Melottid59e44a2010-02-28 03:46:13 +0000185 test_choice (__main__.TestSequenceFunctions) ... ok
186 test_sample (__main__.TestSequenceFunctions) ... ok
187 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189 ----------------------------------------------------------------------
190 Ran 3 tests in 0.110s
191
192 OK
193
194The above examples show the most commonly used :mod:`unittest` features which
195are sufficient to meet many everyday testing needs. The remainder of the
196documentation explores the full feature set from first principles.
197
Benjamin Petersonb48af542010-04-11 20:43:16 +0000198
199.. _unittest-command-line-interface:
200
Éric Araujo76338ec2010-11-26 23:46:18 +0000201Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000202----------------------
203
204The unittest module can be used from the command line to run tests from
205modules, classes or even individual test methods::
206
207 python -m unittest test_module1 test_module2
208 python -m unittest test_module.TestClass
209 python -m unittest test_module.TestClass.test_method
210
211You can pass in a list with any combination of module names, and fully
212qualified class or method names.
213
Michael Foord37d120a2010-12-04 01:11:21 +0000214Test modules can be specified by file path as well::
215
216 python -m unittest tests/test_something.py
217
218This allows you to use the shell filename completion to specify the test module.
219The file specified must still be importable as a module. The path is converted
220to a module name by removing the '.py' and converting path separators into '.'.
221If you want to execute a test file that isn't importable as a module you should
222execute the file directly instead.
223
Benjamin Petersonb48af542010-04-11 20:43:16 +0000224You can run tests with more detail (higher verbosity) by passing in the -v flag::
225
226 python -m unittest -v test_module
227
Michael Foord086f3082010-11-21 21:28:01 +0000228When executed without arguments :ref:`unittest-test-discovery` is started::
229
230 python -m unittest
231
Éric Araujo713d3032010-11-18 16:38:46 +0000232For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000233
234 python -m unittest -h
235
Georg Brandl67b21b72010-08-17 15:07:14 +0000236.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000237 In earlier versions it was only possible to run individual test methods and
238 not modules or classes.
239
240
Éric Araujo76338ec2010-11-26 23:46:18 +0000241Command-line options
242~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000243
Éric Araujod3309df2010-11-21 03:09:17 +0000244:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000245
Éric Araujo713d3032010-11-18 16:38:46 +0000246.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000247
Éric Araujo713d3032010-11-18 16:38:46 +0000248.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000249
Éric Araujo713d3032010-11-18 16:38:46 +0000250 The standard output and standard error streams are buffered during the test
251 run. Output during a passing test is discarded. Output is echoed normally
252 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000253
Éric Araujo713d3032010-11-18 16:38:46 +0000254.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000255
Éric Araujo713d3032010-11-18 16:38:46 +0000256 Control-C during the test run waits for the current test to end and then
257 reports all the results so far. A second control-C raises the normal
258 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000259
Éric Araujo713d3032010-11-18 16:38:46 +0000260 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000261
Éric Araujo713d3032010-11-18 16:38:46 +0000262.. cmdoption:: -f, --failfast
263
264 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000265
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000266.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000267 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000268
269The command line can also be used for test discovery, for running all of the
270tests in a project or just a subset.
271
272
273.. _unittest-test-discovery:
274
275Test Discovery
276--------------
277
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000278.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000279
280Unittest supports simple test discovery. For a project's tests to be
281compatible with test discovery they must all be importable from the top level
282directory of the project (in other words, they must all be in Python packages).
283
284Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000285used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000286
287 cd project_directory
288 python -m unittest discover
289
Michael Foord086f3082010-11-21 21:28:01 +0000290.. note::
291
292 As a shortcut, ``python -m unittest`` is the equivalent of
293 ``python -m unittest discover``. If you want to pass arguments to test
294 discovery the `discover` sub-command must be used explicitly.
295
Benjamin Petersonb48af542010-04-11 20:43:16 +0000296The ``discover`` sub-command has the following options:
297
Éric Araujo713d3032010-11-18 16:38:46 +0000298.. program:: unittest discover
299
300.. cmdoption:: -v, --verbose
301
302 Verbose output
303
304.. cmdoption:: -s directory
305
306 Directory to start discovery ('.' default)
307
308.. cmdoption:: -p pattern
309
310 Pattern to match test files ('test*.py' default)
311
312.. cmdoption:: -t directory
313
314 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000315
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000316The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
317as positional arguments in that order. The following two command lines
318are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000319
320 python -m unittest discover -s project_directory -p '*_test.py'
321 python -m unittest discover project_directory '*_test.py'
322
Michael Foord16f3e902010-05-08 15:13:42 +0000323As well as being a path it is possible to pass a package name, for example
324``myproject.subpackage.test``, as the start directory. The package name you
325supply will then be imported and its location on the filesystem will be used
326as the start directory.
327
328.. caution::
329
Senthil Kumaran916bd382010-10-15 12:55:19 +0000330 Test discovery loads tests by importing them. Once test discovery has found
331 all the test files from the start directory you specify it turns the paths
332 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000333 imported as ``foo.bar.baz``.
334
335 If you have a package installed globally and attempt test discovery on
336 a different copy of the package then the import *could* happen from the
337 wrong place. If this happens test discovery will warn you and exit.
338
339 If you supply the start directory as a package name rather than a
340 path to a directory then discover assumes that whichever location it
341 imports from is the location you intended, so you will not get the
342 warning.
343
Benjamin Petersonb48af542010-04-11 20:43:16 +0000344Test modules and packages can customize test loading and discovery by through
345the `load_tests protocol`_.
346
347
Georg Brandl116aa622007-08-15 14:28:22 +0000348.. _organizing-tests:
349
350Organizing test code
351--------------------
352
353The basic building blocks of unit testing are :dfn:`test cases` --- single
354scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000355test cases are represented by :class:`unittest.TestCase` instances.
356To make your own test cases you must write subclasses of
357:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359An instance of a :class:`TestCase`\ -derived class is an object that can
360completely run a single test method, together with optional set-up and tidy-up
361code.
362
363The testing code of a :class:`TestCase` instance should be entirely self
364contained, such that it can be run either in isolation or in arbitrary
365combination with any number of other test cases.
366
Benjamin Peterson52baa292009-03-24 00:56:30 +0000367The simplest :class:`TestCase` subclass will simply override the
368:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000369
370 import unittest
371
372 class DefaultWidgetSizeTestCase(unittest.TestCase):
373 def runTest(self):
374 widget = Widget('The widget')
375 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
376
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000377Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000378methods provided by the :class:`TestCase` base class. If the test fails, an
379exception will be raised, and :mod:`unittest` will identify the test case as a
380:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
381helps you identify where the problem is: :dfn:`failures` are caused by incorrect
382results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
383code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385The way to run a test case will be described later. For now, note that to
386construct an instance of such a test case, we call its constructor without
387arguments::
388
389 testCase = DefaultWidgetSizeTestCase()
390
391Now, such test cases can be numerous, and their set-up can be repetitive. In
392the above case, constructing a :class:`Widget` in each of 100 Widget test case
393subclasses would mean unsightly duplication.
394
395Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000396:meth:`~TestCase.setUp`, which the testing framework will automatically call for
397us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399 import unittest
400
401 class SimpleWidgetTestCase(unittest.TestCase):
402 def setUp(self):
403 self.widget = Widget('The widget')
404
405 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
406 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000407 self.assertEqual(self.widget.size(), (50,50),
408 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410 class WidgetResizeTestCase(SimpleWidgetTestCase):
411 def runTest(self):
412 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000413 self.assertEqual(self.widget.size(), (100,150),
414 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Benjamin Peterson52baa292009-03-24 00:56:30 +0000416If the :meth:`~TestCase.setUp` method raises an exception while the test is
417running, the framework will consider the test to have suffered an error, and the
418:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Benjamin Peterson52baa292009-03-24 00:56:30 +0000420Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
421after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000422
423 import unittest
424
425 class SimpleWidgetTestCase(unittest.TestCase):
426 def setUp(self):
427 self.widget = Widget('The widget')
428
429 def tearDown(self):
430 self.widget.dispose()
431 self.widget = None
432
Benjamin Peterson52baa292009-03-24 00:56:30 +0000433If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
434be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000435
436Such a working environment for the testing code is called a :dfn:`fixture`.
437
438Often, many small test cases will use the same fixture. In this case, we would
439end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
440classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000441discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
442mechanism::
443
444 import unittest
445
446 class WidgetTestCase(unittest.TestCase):
447 def setUp(self):
448 self.widget = Widget('The widget')
449
450 def tearDown(self):
451 self.widget.dispose()
452 self.widget = None
453
Ezio Melottid59e44a2010-02-28 03:46:13 +0000454 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000455 self.assertEqual(self.widget.size(), (50,50),
456 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000457
Ezio Melottid59e44a2010-02-28 03:46:13 +0000458 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000459 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000460 self.assertEqual(self.widget.size(), (100,150),
461 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000462
Benjamin Peterson52baa292009-03-24 00:56:30 +0000463Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
464provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000465the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000466separately for each instance. When creating an instance we must specify the
467test method it is to run. We do this by passing the method name in the
468constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000469
Ezio Melottid59e44a2010-02-28 03:46:13 +0000470 defaultSizeTestCase = WidgetTestCase('test_default_size')
471 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000472
473Test case instances are grouped together according to the features they test.
474:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
475represented by :mod:`unittest`'s :class:`TestSuite` class::
476
477 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000478 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
479 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000480
481For the ease of running tests, as we will see later, it is a good idea to
482provide in each test module a callable object that returns a pre-built test
483suite::
484
485 def suite():
486 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000487 suite.addTest(WidgetTestCase('test_default_size'))
488 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000489 return suite
490
491or even::
492
493 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000494 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496 return unittest.TestSuite(map(WidgetTestCase, tests))
497
498Since it is a common pattern to create a :class:`TestCase` subclass with many
499similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
500class that can be used to automate the process of creating a test suite and
501populating it with individual tests. For example, ::
502
503 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
504
Ezio Melottid59e44a2010-02-28 03:46:13 +0000505will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
506``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000507name prefix to identify test methods automatically.
508
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000509Note that the order in which the various test cases will be run is
510determined by sorting the test function names with respect to the
511built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513Often it is desirable to group suites of test cases together, so as to run tests
514for the whole system at once. This is easy, since :class:`TestSuite` instances
515can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
516added to a :class:`TestSuite`::
517
518 suite1 = module1.TheTestSuite()
519 suite2 = module2.TheTestSuite()
520 alltests = unittest.TestSuite([suite1, suite2])
521
522You can place the definitions of test cases and test suites in the same modules
523as the code they are to test (such as :file:`widget.py`), but there are several
524advantages to placing the test code in a separate module, such as
525:file:`test_widget.py`:
526
527* The test module can be run standalone from the command line.
528
529* The test code can more easily be separated from shipped code.
530
531* There is less temptation to change test code to fit the code it tests without
532 a good reason.
533
534* Test code should be modified much less frequently than the code it tests.
535
536* Tested code can be refactored more easily.
537
538* Tests for modules written in C must be in separate modules anyway, so why not
539 be consistent?
540
541* If the testing strategy changes, there is no need to change the source code.
542
543
544.. _legacy-unit-tests:
545
546Re-using old test code
547----------------------
548
549Some users will find that they have existing test code that they would like to
550run from :mod:`unittest`, without converting every old test function to a
551:class:`TestCase` subclass.
552
553For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
554This subclass of :class:`TestCase` can be used to wrap an existing test
555function. Set-up and tear-down functions can also be provided.
556
557Given the following test function::
558
559 def testSomething():
560 something = makeSomething()
561 assert something.name is not None
562 # ...
563
564one can create an equivalent test case instance as follows::
565
566 testcase = unittest.FunctionTestCase(testSomething)
567
568If there are additional set-up and tear-down methods that should be called as
569part of the test case's operation, they can also be provided like so::
570
571 testcase = unittest.FunctionTestCase(testSomething,
572 setUp=makeSomethingDB,
573 tearDown=deleteSomethingDB)
574
575To make migrating existing test suites easier, :mod:`unittest` supports tests
576raising :exc:`AssertionError` to indicate test failure. However, it is
577recommended that you use the explicit :meth:`TestCase.fail\*` and
578:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
579may treat :exc:`AssertionError` differently.
580
581.. note::
582
Benjamin Petersond2397752009-06-27 23:45:02 +0000583 Even though :class:`FunctionTestCase` can be used to quickly convert an
584 existing test base over to a :mod:`unittest`\ -based system, this approach is
585 not recommended. Taking the time to set up proper :class:`TestCase`
586 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000587
Benjamin Peterson52baa292009-03-24 00:56:30 +0000588In some cases, the existing tests may have been written using the :mod:`doctest`
589module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
590automatically build :class:`unittest.TestSuite` instances from the existing
591:mod:`doctest`\ -based tests.
592
Georg Brandl116aa622007-08-15 14:28:22 +0000593
Benjamin Peterson5254c042009-03-23 22:25:03 +0000594.. _unittest-skipping:
595
596Skipping tests and expected failures
597------------------------------------
598
Michael Foordf5c851a2010-02-05 21:48:03 +0000599.. versionadded:: 3.1
600
Benjamin Peterson5254c042009-03-23 22:25:03 +0000601Unittest supports skipping individual test methods and even whole classes of
602tests. In addition, it supports marking a test as a "expected failure," a test
603that is broken and will fail, but shouldn't be counted as a failure on a
604:class:`TestResult`.
605
606Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
607or one of its conditional variants.
608
609Basic skipping looks like this: ::
610
611 class MyTestCase(unittest.TestCase):
612
613 @unittest.skip("demonstrating skipping")
614 def test_nothing(self):
615 self.fail("shouldn't happen")
616
Benjamin Petersond2397752009-06-27 23:45:02 +0000617 @unittest.skipIf(mylib.__version__ < (1, 3),
618 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000619 def test_format(self):
620 # Tests that work for only a certain version of the library.
621 pass
622
623 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
624 def test_windows_support(self):
625 # windows specific testing code
626 pass
627
Benjamin Peterson5254c042009-03-23 22:25:03 +0000628This is the output of running the example above in verbose mode: ::
629
Benjamin Petersonded31c42009-03-30 15:04:16 +0000630 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000631 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000632 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000633
634 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000635 Ran 3 tests in 0.005s
636
637 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000638
639Classes can be skipped just like methods: ::
640
641 @skip("showing class skipping")
642 class MySkippedTestCase(unittest.TestCase):
643 def test_not_run(self):
644 pass
645
Benjamin Peterson52baa292009-03-24 00:56:30 +0000646:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
647that needs to be set up is not available.
648
Benjamin Peterson5254c042009-03-23 22:25:03 +0000649Expected failures use the :func:`expectedFailure` decorator. ::
650
651 class ExpectedFailureTestCase(unittest.TestCase):
652 @unittest.expectedFailure
653 def test_fail(self):
654 self.assertEqual(1, 0, "broken")
655
656It's easy to roll your own skipping decorators by making a decorator that calls
657:func:`skip` on the test when it wants it to be skipped. This decorator skips
658the test unless the passed object has a certain attribute: ::
659
660 def skipUnlessHasattr(obj, attr):
661 if hasattr(obj, attr):
662 return lambda func: func
663 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
664
665The following decorators implement test skipping and expected failures:
666
Georg Brandl8a1caa22010-07-29 16:01:11 +0000667.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000668
669 Unconditionally skip the decorated test. *reason* should describe why the
670 test is being skipped.
671
Georg Brandl8a1caa22010-07-29 16:01:11 +0000672.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000673
674 Skip the decorated test if *condition* is true.
675
Georg Brandl8a1caa22010-07-29 16:01:11 +0000676.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000677
Georg Brandl6faee4e2010-09-21 14:48:28 +0000678 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000679
Georg Brandl8a1caa22010-07-29 16:01:11 +0000680.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000681
682 Mark the test as an expected failure. If the test fails when run, the test
683 is not counted as a failure.
684
Benjamin Petersonb48af542010-04-11 20:43:16 +0000685Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
686Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
687
Benjamin Peterson5254c042009-03-23 22:25:03 +0000688
Georg Brandl116aa622007-08-15 14:28:22 +0000689.. _unittest-contents:
690
691Classes and functions
692---------------------
693
Benjamin Peterson52baa292009-03-24 00:56:30 +0000694This section describes in depth the API of :mod:`unittest`.
695
696
697.. _testcase-objects:
698
699Test cases
700~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Georg Brandl7f01a132009-09-16 15:58:14 +0000702.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000703
704 Instances of the :class:`TestCase` class represent the smallest testable units
705 in the :mod:`unittest` universe. This class is intended to be used as a base
706 class, with specific tests being implemented by concrete subclasses. This class
707 implements the interface needed by the test runner to allow it to drive the
708 test, and methods that the test code can use to check for and report various
709 kinds of failure.
710
711 Each instance of :class:`TestCase` will run a single test method: the method
712 named *methodName*. If you remember, we had an earlier example that went
713 something like this::
714
715 def suite():
716 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000717 suite.addTest(WidgetTestCase('test_default_size'))
718 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000719 return suite
720
721 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
722 single test.
723
Michael Foord32e1d832011-01-03 17:00:11 +0000724 .. versionchanged::
725 `TestCase` can be instantiated successfully without providing a method
726 name. This makes it easier to experiment with `TestCase` from the
727 interactive interpreter.
728
Benjamin Peterson52baa292009-03-24 00:56:30 +0000729 *methodName* defaults to :meth:`runTest`.
730
731 :class:`TestCase` instances provide three groups of methods: one group used
732 to run the test, another used by the test implementation to check conditions
733 and report failures, and some inquiry methods allowing information about the
734 test itself to be gathered.
735
736 Methods in the first group (running the test) are:
737
738
739 .. method:: setUp()
740
741 Method called to prepare the test fixture. This is called immediately
742 before calling the test method; any exception raised by this method will
743 be considered an error rather than a test failure. The default
744 implementation does nothing.
745
746
747 .. method:: tearDown()
748
749 Method called immediately after the test method has been called and the
750 result recorded. This is called even if the test method raised an
751 exception, so the implementation in subclasses may need to be particularly
752 careful about checking internal state. Any exception raised by this
753 method will be considered an error rather than a test failure. This
754 method will only be called if the :meth:`setUp` succeeds, regardless of
755 the outcome of the test method. The default implementation does nothing.
756
757
Benjamin Petersonb48af542010-04-11 20:43:16 +0000758 .. method:: setUpClass()
759
760 A class method called before tests in an individual class run.
761 ``setUpClass`` is called with the class as the only argument
762 and must be decorated as a :func:`classmethod`::
763
764 @classmethod
765 def setUpClass(cls):
766 ...
767
768 See `Class and Module Fixtures`_ for more details.
769
770 .. versionadded:: 3.2
771
772
773 .. method:: tearDownClass()
774
775 A class method called after tests in an individual class have run.
776 ``tearDownClass`` is called with the class as the only argument
777 and must be decorated as a :meth:`classmethod`::
778
779 @classmethod
780 def tearDownClass(cls):
781 ...
782
783 See `Class and Module Fixtures`_ for more details.
784
785 .. versionadded:: 3.2
786
787
Georg Brandl7f01a132009-09-16 15:58:14 +0000788 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000789
790 Run the test, collecting the result into the test result object passed as
Ezio Melotti75b2a5e2010-11-20 10:13:45 +0000791 *result*. If *result* is omitted or ``None``, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000792 object is created (by calling the :meth:`defaultTestResult` method) and
793 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000794
795 The same effect may be had by simply calling the :class:`TestCase`
796 instance.
797
798
Benjamin Petersone549ead2009-03-28 21:42:05 +0000799 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000800
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000801 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000802 test. See :ref:`unittest-skipping` for more information.
803
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000804 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000805
Benjamin Peterson52baa292009-03-24 00:56:30 +0000806
807 .. method:: debug()
808
809 Run the test without collecting the result. This allows exceptions raised
810 by the test to be propagated to the caller, and can be used to support
811 running tests under a debugger.
812
Ezio Melotti22170ed2010-11-20 09:57:27 +0000813 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000814
Ezio Melotti4370b302010-11-03 20:39:14 +0000815 The :class:`TestCase` class provides a number of methods to check for and
816 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000817
Ezio Melotti4370b302010-11-03 20:39:14 +0000818 +-----------------------------------------+-----------------------------+---------------+
819 | Method | Checks that | New in |
820 +=========================================+=============================+===============+
821 | :meth:`assertEqual(a, b) | ``a == b`` | |
822 | <TestCase.assertEqual>` | | |
823 +-----------------------------------------+-----------------------------+---------------+
824 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
825 | <TestCase.assertNotEqual>` | | |
826 +-----------------------------------------+-----------------------------+---------------+
827 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
828 | <TestCase.assertTrue>` | | |
829 +-----------------------------------------+-----------------------------+---------------+
830 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
831 | <TestCase.assertFalse>` | | |
832 +-----------------------------------------+-----------------------------+---------------+
833 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
834 | <TestCase.assertIs>` | | |
835 +-----------------------------------------+-----------------------------+---------------+
836 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
837 | <TestCase.assertIsNot>` | | |
838 +-----------------------------------------+-----------------------------+---------------+
839 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
840 | <TestCase.assertIsNone>` | | |
841 +-----------------------------------------+-----------------------------+---------------+
842 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
843 | <TestCase.assertIsNotNone>` | | |
844 +-----------------------------------------+-----------------------------+---------------+
845 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
846 | <TestCase.assertIn>` | | |
847 +-----------------------------------------+-----------------------------+---------------+
848 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
849 | <TestCase.assertNotIn>` | | |
850 +-----------------------------------------+-----------------------------+---------------+
851 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
852 | <TestCase.assertIsInstance>` | | |
853 +-----------------------------------------+-----------------------------+---------------+
854 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
855 | <TestCase.assertNotIsInstance>` | | |
856 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000857
Ezio Melotti22170ed2010-11-20 09:57:27 +0000858 All the assert methods (except :meth:`assertRaises`,
Ezio Melottied3a7d22010-12-01 02:32:32 +0000859 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`)
Ezio Melotti22170ed2010-11-20 09:57:27 +0000860 accept a *msg* argument that, if specified, is used as the error message on
861 failure (see also :data:`longMessage`).
Benjamin Peterson52baa292009-03-24 00:56:30 +0000862
Michael Foorde180d392011-01-28 19:51:48 +0000863 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000864
Michael Foorde180d392011-01-28 19:51:48 +0000865 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000866 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000867
Michael Foorde180d392011-01-28 19:51:48 +0000868 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000869 list, tuple, dict, set, frozenset or str or any type that a subclass
870 registers with :meth:`addTypeEqualityFunc` the type specific equality
871 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000872 error message (see also the :ref:`list of type-specific methods
873 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000874
Raymond Hettinger35a88362009-04-09 00:08:24 +0000875 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000876 Added the automatic calling of type specific equality function.
877
Michael Foord28a817e2010-02-09 00:03:57 +0000878 .. versionchanged:: 3.2
879 :meth:`assertMultiLineEqual` added as the default type equality
880 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000881
Benjamin Peterson52baa292009-03-24 00:56:30 +0000882
Michael Foorde180d392011-01-28 19:51:48 +0000883 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000884
Michael Foorde180d392011-01-28 19:51:48 +0000885 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000886 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000887
Ezio Melotti4370b302010-11-03 20:39:14 +0000888 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000889 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000890
Ezio Melotti4841fd62010-11-05 15:43:40 +0000891 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000892
Ezio Melotti4841fd62010-11-05 15:43:40 +0000893 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
894 is True`` (use ``assertIs(expr, True)`` for the latter). This method
895 should also be avoided when more specific methods are available (e.g.
896 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
897 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000898
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000899
Michael Foorde180d392011-01-28 19:51:48 +0000900 .. method:: assertIs(first, second, msg=None)
901 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000902
Michael Foorde180d392011-01-28 19:51:48 +0000903 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000904 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000905
Raymond Hettinger35a88362009-04-09 00:08:24 +0000906 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000907
908
Ezio Melotti4370b302010-11-03 20:39:14 +0000909 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000910 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000911
Ezio Melotti9794a262010-11-04 14:52:13 +0000912 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000913
Ezio Melotti4370b302010-11-03 20:39:14 +0000914 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000915
916
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000917 .. method:: assertIn(first, second, msg=None)
918 assertNotIn(first, second, msg=None)
919
Ezio Melotti4841fd62010-11-05 15:43:40 +0000920 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000921
Raymond Hettinger35a88362009-04-09 00:08:24 +0000922 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000923
924
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000925 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000926 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000927
Ezio Melotti9794a262010-11-04 14:52:13 +0000928 Test that *obj* is (or is not) an instance of *cls* (which can be a
929 class or a tuple of classes, as supported by :func:`isinstance`).
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000930
Ezio Melotti4370b302010-11-03 20:39:14 +0000931 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000932
933
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000934
Ezio Melotti4370b302010-11-03 20:39:14 +0000935 It is also possible to check that exceptions and warnings are raised using
936 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000937
Ezio Melotti4370b302010-11-03 20:39:14 +0000938 +---------------------------------------------------------+--------------------------------------+------------+
939 | Method | Checks that | New in |
940 +=========================================================+======================================+============+
941 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | |
942 | <TestCase.assertRaises>` | | |
943 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +0000944 | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
945 | <TestCase.assertRaisesRegex>` | and the message matches `re` | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000946 +---------------------------------------------------------+--------------------------------------+------------+
947 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
948 | <TestCase.assertWarns>` | | |
949 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +0000950 | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
951 | <TestCase.assertWarnsRegex>` | and the message matches `re` | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000952 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000953
Georg Brandl7f01a132009-09-16 15:58:14 +0000954 .. method:: assertRaises(exception, callable, *args, **kwds)
Georg Brandl7f01a132009-09-16 15:58:14 +0000955 assertRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000956
957 Test that an exception is raised when *callable* is called with any
958 positional or keyword arguments that are also passed to
959 :meth:`assertRaises`. The test passes if *exception* is raised, is an
960 error if another exception is raised, or fails if no exception is raised.
961 To catch any of a group of exceptions, a tuple containing the exception
962 classes may be passed as *exception*.
963
Georg Brandl7f01a132009-09-16 15:58:14 +0000964 If only the *exception* argument is given, returns a context manager so
965 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000966
Michael Foord41531f22010-02-05 21:13:40 +0000967 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000968 do_something()
969
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000970 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000971 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000972 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000973
Georg Brandl8a1caa22010-07-29 16:01:11 +0000974 with self.assertRaises(SomeException) as cm:
975 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000976
Georg Brandl8a1caa22010-07-29 16:01:11 +0000977 the_exception = cm.exception
978 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000979
Ezio Melotti49008232010-02-08 21:57:48 +0000980 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000981 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000982
Ezio Melotti49008232010-02-08 21:57:48 +0000983 .. versionchanged:: 3.2
984 Added the :attr:`exception` attribute.
985
Benjamin Peterson52baa292009-03-24 00:56:30 +0000986
Ezio Melottied3a7d22010-12-01 02:32:32 +0000987 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
988 assertRaisesRegex(exception, regex)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000989
Ezio Melottied3a7d22010-12-01 02:32:32 +0000990 Like :meth:`assertRaises` but also tests that *regex* matches
991 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000992 a regular expression object or a string containing a regular expression
993 suitable for use by :func:`re.search`. Examples::
994
Ezio Melottied3a7d22010-12-01 02:32:32 +0000995 self.assertRaisesRegex(ValueError, 'invalid literal for.*XYZ$',
996 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000997
998 or::
999
Ezio Melottied3a7d22010-12-01 02:32:32 +00001000 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001001 int('XYZ')
1002
Georg Brandl419e3de2010-12-01 15:44:25 +00001003 .. versionadded:: 3.1
1004 under the name ``assertRaisesRegexp``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001005 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001006 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001007
1008
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001009 .. method:: assertWarns(warning, callable, *args, **kwds)
1010 assertWarns(warning)
1011
1012 Test that a warning is triggered when *callable* is called with any
1013 positional or keyword arguments that are also passed to
1014 :meth:`assertWarns`. The test passes if *warning* is triggered and
1015 fails if it isn't. Also, any unexpected exception is an error.
1016 To catch any of a group of warnings, a tuple containing the warning
1017 classes may be passed as *warnings*.
1018
1019 If only the *warning* argument is given, returns a context manager so
1020 that the code under test can be written inline rather than as a function::
1021
1022 with self.assertWarns(SomeWarning):
1023 do_something()
1024
1025 The context manager will store the caught warning object in its
1026 :attr:`warning` attribute, and the source line which triggered the
1027 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1028 This can be useful if the intention is to perform additional checks
1029 on the exception raised::
1030
1031 with self.assertWarns(SomeWarning) as cm:
1032 do_something()
1033
1034 self.assertIn('myfile.py', cm.filename)
1035 self.assertEqual(320, cm.lineno)
1036
1037 This method works regardless of the warning filters in place when it
1038 is called.
1039
1040 .. versionadded:: 3.2
1041
1042
Ezio Melottied3a7d22010-12-01 02:32:32 +00001043 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
1044 assertWarnsRegex(warning, regex)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001045
Ezio Melottied3a7d22010-12-01 02:32:32 +00001046 Like :meth:`assertWarns` but also tests that *regex* matches on the
1047 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001048 object or a string containing a regular expression suitable for use
1049 by :func:`re.search`. Example::
1050
Ezio Melottied3a7d22010-12-01 02:32:32 +00001051 self.assertWarnsRegex(DeprecationWarning,
1052 r'legacy_function\(\) is deprecated',
1053 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001054
1055 or::
1056
Ezio Melottied3a7d22010-12-01 02:32:32 +00001057 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001058 frobnicate('/etc/passwd')
1059
1060 .. versionadded:: 3.2
1061
1062
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001063
Ezio Melotti4370b302010-11-03 20:39:14 +00001064 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001065
Ezio Melotti4370b302010-11-03 20:39:14 +00001066 +---------------------------------------+--------------------------------+--------------+
1067 | Method | Checks that | New in |
1068 +=======================================+================================+==============+
1069 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1070 | <TestCase.assertAlmostEqual>` | | |
1071 +---------------------------------------+--------------------------------+--------------+
1072 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1073 | <TestCase.assertNotAlmostEqual>` | | |
1074 +---------------------------------------+--------------------------------+--------------+
1075 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1076 | <TestCase.assertGreater>` | | |
1077 +---------------------------------------+--------------------------------+--------------+
1078 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1079 | <TestCase.assertGreaterEqual>` | | |
1080 +---------------------------------------+--------------------------------+--------------+
1081 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1082 | <TestCase.assertLess>` | | |
1083 +---------------------------------------+--------------------------------+--------------+
1084 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1085 | <TestCase.assertLessEqual>` | | |
1086 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001087 | :meth:`assertRegex(s, re) | ``regex.search(s)`` | 3.1 |
1088 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001089 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001090 | :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 |
1091 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001092 +---------------------------------------+--------------------------------+--------------+
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001093 | :meth:`assertCountEqual(a, b) | `a` and `b` have the same | 3.2 |
1094 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001095 | | regardless of their order | |
1096 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001097
1098
Michael Foorde180d392011-01-28 19:51:48 +00001099 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1100 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001101
Michael Foorde180d392011-01-28 19:51:48 +00001102 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001103 equal by computing the difference, rounding to the given number of
1104 decimal *places* (default 7), and comparing to zero. Note that these
1105 methods round the values to the given number of *decimal places* (i.e.
1106 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001107
Ezio Melotti4370b302010-11-03 20:39:14 +00001108 If *delta* is supplied instead of *places* then the difference
Michael Foorde180d392011-01-28 19:51:48 +00001109 between *first* and *second* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001110
Ezio Melotti4370b302010-11-03 20:39:14 +00001111 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001112
Ezio Melotti4370b302010-11-03 20:39:14 +00001113 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001114 :meth:`assertAlmostEqual` automatically considers almost equal objects
1115 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1116 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001117
Ezio Melotti4370b302010-11-03 20:39:14 +00001118
Michael Foorde180d392011-01-28 19:51:48 +00001119 .. method:: assertGreater(first, second, msg=None)
1120 assertGreaterEqual(first, second, msg=None)
1121 assertLess(first, second, msg=None)
1122 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001123
Michael Foorde180d392011-01-28 19:51:48 +00001124 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001125 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001126
1127 >>> self.assertGreaterEqual(3, 4)
1128 AssertionError: "3" unexpectedly not greater than or equal to "4"
1129
1130 .. versionadded:: 3.1
1131
1132
Ezio Melottied3a7d22010-12-01 02:32:32 +00001133 .. method:: assertRegex(text, regex, msg=None)
1134 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001135
Ezio Melottied3a7d22010-12-01 02:32:32 +00001136 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001137 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001138 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001139 may be a regular expression object or a string containing a regular
1140 expression suitable for use by :func:`re.search`.
1141
Georg Brandl419e3de2010-12-01 15:44:25 +00001142 .. versionadded:: 3.1
1143 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001144 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001145 The method ``assertRegexpMatches()`` has been renamed to
1146 :meth:`.assertRegex`.
1147 .. versionadded:: 3.2
1148 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001149
1150
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001151 .. method:: assertDictContainsSubset(subset, dictionary, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001152
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001153 Tests whether the key/value pairs in *dictionary* are a superset of
1154 those in *subset*. If not, an error message listing the missing keys
1155 and mismatched values is generated.
Ezio Melotti4370b302010-11-03 20:39:14 +00001156
Raymond Hettinger8ebe27f2010-12-21 19:24:26 +00001157 Note, the arguments are in the opposite order of what the method name
1158 dictates. Instead, consider using the set-methods on :ref:`dictionary
1159 views <dict-views>`, for example: ``d.keys() <= e.keys()`` or
1160 ``d.items() <= d.items()``.
1161
Ezio Melotti4370b302010-11-03 20:39:14 +00001162 .. versionadded:: 3.1
Raymond Hettinger8ebe27f2010-12-21 19:24:26 +00001163 .. deprecated:: 3.2
Ezio Melotti4370b302010-11-03 20:39:14 +00001164
1165
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001166 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001167
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001168 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001169 regardless of their order. When they don't, an error message listing the
1170 differences between the sequences will be generated.
1171
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001172 Duplicate elements are *not* ignored when comparing *first* and
1173 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001174 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001175 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001176 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001177
Ezio Melotti4370b302010-11-03 20:39:14 +00001178 .. versionadded:: 3.2
1179
Michael Foorde180d392011-01-28 19:51:48 +00001180 .. method:: assertSameElements(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001181
Michael Foorde180d392011-01-28 19:51:48 +00001182 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001183 regardless of their order. When they don't, an error message listing
1184 the differences between the sequences will be generated.
1185
Michael Foorde180d392011-01-28 19:51:48 +00001186 Duplicate elements are ignored when comparing *first* and *second*.
1187 It is the equivalent of ``assertEqual(set(first), set(second))``
Ezio Melotti4370b302010-11-03 20:39:14 +00001188 but it works with sequences of unhashable objects as well. Because
1189 duplicates are ignored, this method has been deprecated in favour of
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001190 :meth:`assertCountEqual`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001191
Ezio Melotti4370b302010-11-03 20:39:14 +00001192 .. versionadded:: 3.1
1193 .. deprecated:: 3.2
1194
1195
Ezio Melotti22170ed2010-11-20 09:57:27 +00001196 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001197
Ezio Melotti22170ed2010-11-20 09:57:27 +00001198 The :meth:`assertEqual` method dispatches the equality check for objects of
1199 the same type to different type-specific methods. These methods are already
1200 implemented for most of the built-in types, but it's also possible to
1201 register new methods using :meth:`addTypeEqualityFunc`:
1202
1203 .. method:: addTypeEqualityFunc(typeobj, function)
1204
1205 Registers a type-specific method called by :meth:`assertEqual` to check
1206 if two objects of exactly the same *typeobj* (not subclasses) compare
1207 equal. *function* must take two positional arguments and a third msg=None
1208 keyword argument just as :meth:`assertEqual` does. It must raise
1209 :data:`self.failureException(msg) <failureException>` when inequality
1210 between the first two parameters is detected -- possibly providing useful
1211 information and explaining the inequalities in details in the error
1212 message.
1213
1214 .. versionadded:: 3.1
1215
1216 The list of type-specific methods automatically used by
1217 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1218 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001219
1220 +-----------------------------------------+-----------------------------+--------------+
1221 | Method | Used to compare | New in |
1222 +=========================================+=============================+==============+
1223 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1224 | <TestCase.assertMultiLineEqual>` | | |
1225 +-----------------------------------------+-----------------------------+--------------+
1226 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1227 | <TestCase.assertSequenceEqual>` | | |
1228 +-----------------------------------------+-----------------------------+--------------+
1229 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1230 | <TestCase.assertListEqual>` | | |
1231 +-----------------------------------------+-----------------------------+--------------+
1232 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1233 | <TestCase.assertTupleEqual>` | | |
1234 +-----------------------------------------+-----------------------------+--------------+
1235 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1236 | <TestCase.assertSetEqual>` | | |
1237 +-----------------------------------------+-----------------------------+--------------+
1238 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1239 | <TestCase.assertDictEqual>` | | |
1240 +-----------------------------------------+-----------------------------+--------------+
1241
1242
1243
Michael Foorde180d392011-01-28 19:51:48 +00001244 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001245
Michael Foorde180d392011-01-28 19:51:48 +00001246 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001247 When not equal a diff of the two strings highlighting the differences
1248 will be included in the error message. This method is used by default
1249 when comparing strings with :meth:`assertEqual`.
1250
Ezio Melotti4370b302010-11-03 20:39:14 +00001251 .. versionadded:: 3.1
1252
1253
Michael Foorde180d392011-01-28 19:51:48 +00001254 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001255
1256 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001257 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001258 be raised. If the sequences are different an error message is
1259 constructed that shows the difference between the two.
1260
Ezio Melotti22170ed2010-11-20 09:57:27 +00001261 This method is not called directly by :meth:`assertEqual`, but
1262 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001263 :meth:`assertTupleEqual`.
1264
1265 .. versionadded:: 3.1
1266
1267
Michael Foorde180d392011-01-28 19:51:48 +00001268 .. method:: assertListEqual(first, second, msg=None)
1269 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001270
1271 Tests that two lists or tuples are equal. If not an error message is
1272 constructed that shows only the differences between the two. An error
1273 is also raised if either of the parameters are of the wrong type.
1274 These methods are used by default when comparing lists or tuples with
1275 :meth:`assertEqual`.
1276
Ezio Melotti4370b302010-11-03 20:39:14 +00001277 .. versionadded:: 3.1
1278
1279
Michael Foorde180d392011-01-28 19:51:48 +00001280 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001281
1282 Tests that two sets are equal. If not, an error message is constructed
1283 that lists the differences between the sets. This method is used by
1284 default when comparing sets or frozensets with :meth:`assertEqual`.
1285
Michael Foorde180d392011-01-28 19:51:48 +00001286 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001287 method.
1288
Ezio Melotti4370b302010-11-03 20:39:14 +00001289 .. versionadded:: 3.1
1290
1291
Michael Foorde180d392011-01-28 19:51:48 +00001292 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001293
1294 Test that two dictionaries are equal. If not, an error message is
1295 constructed that shows the differences in the dictionaries. This
1296 method will be used by default to compare dictionaries in
1297 calls to :meth:`assertEqual`.
1298
Ezio Melotti4370b302010-11-03 20:39:14 +00001299 .. versionadded:: 3.1
1300
1301
1302
Ezio Melotti22170ed2010-11-20 09:57:27 +00001303 .. _other-methods-and-attrs:
1304
Ezio Melotti4370b302010-11-03 20:39:14 +00001305 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001306
Benjamin Peterson52baa292009-03-24 00:56:30 +00001307
Georg Brandl7f01a132009-09-16 15:58:14 +00001308 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001309
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001310 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001311 the error message.
1312
1313
1314 .. attribute:: failureException
1315
1316 This class attribute gives the exception raised by the test method. If a
1317 test framework needs to use a specialized exception, possibly to carry
1318 additional information, it must subclass this exception in order to "play
1319 fair" with the framework. The initial value of this attribute is
1320 :exc:`AssertionError`.
1321
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001322
1323 .. attribute:: longMessage
1324
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001325 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001326 :ref:`assert methods <assert-methods>` will be appended to the end of the
1327 normal failure message. The normal messages contain useful information
1328 about the objects involved, for example the message from assertEqual
1329 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001330 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001331 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001332
Michael Foord5074df62010-12-03 00:53:09 +00001333 This attribute defaults to ``True``. If set to False then a custom message
1334 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001335
1336 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001337 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001338
Raymond Hettinger35a88362009-04-09 00:08:24 +00001339 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001340
1341
Michael Foord98b3e762010-06-05 21:59:55 +00001342 .. attribute:: maxDiff
1343
1344 This attribute controls the maximum length of diffs output by assert
1345 methods that report diffs on failure. It defaults to 80*8 characters.
1346 Assert methods affected by this attribute are
1347 :meth:`assertSequenceEqual` (including all the sequence comparison
1348 methods that delegate to it), :meth:`assertDictEqual` and
1349 :meth:`assertMultiLineEqual`.
1350
1351 Setting ``maxDiff`` to None means that there is no maximum length of
1352 diffs.
1353
1354 .. versionadded:: 3.2
1355
1356
Benjamin Peterson52baa292009-03-24 00:56:30 +00001357 Testing frameworks can use the following methods to collect information on
1358 the test:
1359
1360
1361 .. method:: countTestCases()
1362
1363 Return the number of tests represented by this test object. For
1364 :class:`TestCase` instances, this will always be ``1``.
1365
1366
1367 .. method:: defaultTestResult()
1368
1369 Return an instance of the test result class that should be used for this
1370 test case class (if no other result instance is provided to the
1371 :meth:`run` method).
1372
1373 For :class:`TestCase` instances, this will always be an instance of
1374 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1375 as necessary.
1376
1377
1378 .. method:: id()
1379
1380 Return a string identifying the specific test case. This is usually the
1381 full name of the test method, including the module and class name.
1382
1383
1384 .. method:: shortDescription()
1385
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001386 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001387 has been provided. The default implementation of this method
1388 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001389 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001390
Georg Brandl419e3de2010-12-01 15:44:25 +00001391 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001392 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001393 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001394 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001395 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001396
Georg Brandl116aa622007-08-15 14:28:22 +00001397
Georg Brandl7f01a132009-09-16 15:58:14 +00001398 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001399
1400 Add a function to be called after :meth:`tearDown` to cleanup resources
1401 used during the test. Functions will be called in reverse order to the
1402 order they are added (LIFO). They are called with any arguments and
1403 keyword arguments passed into :meth:`addCleanup` when they are
1404 added.
1405
1406 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1407 then any cleanup functions added will still be called.
1408
Georg Brandl853947a2010-01-31 18:53:23 +00001409 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001410
1411
1412 .. method:: doCleanups()
1413
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001414 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001415 after :meth:`setUp` if :meth:`setUp` raises an exception.
1416
1417 It is responsible for calling all the cleanup functions added by
1418 :meth:`addCleanup`. If you need cleanup functions to be called
1419 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1420 yourself.
1421
1422 :meth:`doCleanups` pops methods off the stack of cleanup
1423 functions one at a time, so it can be called at any time.
1424
Georg Brandl853947a2010-01-31 18:53:23 +00001425 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001426
1427
Georg Brandl7f01a132009-09-16 15:58:14 +00001428.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001429
1430 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001431 allows the test runner to drive the test, but does not provide the methods
1432 which test code can use to check and report errors. This is used to create
1433 test cases using legacy test code, allowing it to be integrated into a
1434 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001435
1436
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001437.. _deprecated-aliases:
1438
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001439Deprecated aliases
1440##################
1441
1442For historical reasons, some of the :class:`TestCase` methods had one or more
1443aliases that are now deprecated. The following table lists the correct names
1444along with their deprecated aliases:
1445
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001446 ============================== ====================== ======================
1447 Method Name Deprecated alias Deprecated alias
1448 ============================== ====================== ======================
1449 :meth:`.assertEqual` failUnlessEqual assertEquals
1450 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1451 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001452 :meth:`.assertFalse` failIf
1453 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001454 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1455 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001456 :meth:`.assertRegex` assertRegexpMatches
1457 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001458 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001459
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001460 .. deprecated-removed:: 3.1 3.3
1461 the fail* aliases listed in the second column.
1462 .. deprecated:: 3.2
1463 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001464 .. deprecated:: 3.2
1465 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1466 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001467
1468
Benjamin Peterson52baa292009-03-24 00:56:30 +00001469.. _testsuite-objects:
1470
Benjamin Peterson52baa292009-03-24 00:56:30 +00001471Grouping tests
1472~~~~~~~~~~~~~~
1473
Georg Brandl7f01a132009-09-16 15:58:14 +00001474.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001475
1476 This class represents an aggregation of individual tests cases and test suites.
1477 The class presents the interface needed by the test runner to allow it to be run
1478 as any other test case. Running a :class:`TestSuite` instance is the same as
1479 iterating over the suite, running each test individually.
1480
1481 If *tests* is given, it must be an iterable of individual test cases or other
1482 test suites that will be used to build the suite initially. Additional methods
1483 are provided to add test cases and suites to the collection later on.
1484
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001485 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1486 they do not actually implement a test. Instead, they are used to aggregate
1487 tests into groups of tests that should be run together. Some additional
1488 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001489
1490
1491 .. method:: TestSuite.addTest(test)
1492
1493 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1494
1495
1496 .. method:: TestSuite.addTests(tests)
1497
1498 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1499 instances to this test suite.
1500
Benjamin Petersond2397752009-06-27 23:45:02 +00001501 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1502 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001503
1504 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1505
1506
1507 .. method:: run(result)
1508
1509 Run the tests associated with this suite, collecting the result into the
1510 test result object passed as *result*. Note that unlike
1511 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1512 be passed in.
1513
1514
1515 .. method:: debug()
1516
1517 Run the tests associated with this suite without collecting the
1518 result. This allows exceptions raised by the test to be propagated to the
1519 caller and can be used to support running tests under a debugger.
1520
1521
1522 .. method:: countTestCases()
1523
1524 Return the number of tests represented by this test object, including all
1525 individual tests and sub-suites.
1526
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001527
1528 .. method:: __iter__()
1529
1530 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1531 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1532 that this method maybe called several times on a single suite
1533 (for example when counting tests or comparing for equality)
1534 so the tests returned must be the same for repeated iterations.
1535
Georg Brandl853947a2010-01-31 18:53:23 +00001536 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001537 In earlier versions the :class:`TestSuite` accessed tests directly rather
1538 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1539 for providing tests.
1540
Benjamin Peterson52baa292009-03-24 00:56:30 +00001541 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1542 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1543
1544
Benjamin Peterson52baa292009-03-24 00:56:30 +00001545Loading and running tests
1546~~~~~~~~~~~~~~~~~~~~~~~~~
1547
Georg Brandl116aa622007-08-15 14:28:22 +00001548.. class:: TestLoader()
1549
Benjamin Peterson52baa292009-03-24 00:56:30 +00001550 The :class:`TestLoader` class is used to create test suites from classes and
1551 modules. Normally, there is no need to create an instance of this class; the
1552 :mod:`unittest` module provides an instance that can be shared as
1553 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1554 customization of some configurable properties.
1555
1556 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001557
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001558
Benjamin Peterson52baa292009-03-24 00:56:30 +00001559 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001560
Benjamin Peterson52baa292009-03-24 00:56:30 +00001561 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1562 :class:`testCaseClass`.
1563
1564
1565 .. method:: loadTestsFromModule(module)
1566
1567 Return a suite of all tests cases contained in the given module. This
1568 method searches *module* for classes derived from :class:`TestCase` and
1569 creates an instance of the class for each test method defined for the
1570 class.
1571
Georg Brandle720c0a2009-04-27 16:20:50 +00001572 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001573
1574 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1575 convenient in sharing fixtures and helper functions, defining test
1576 methods on base classes that are not intended to be instantiated
1577 directly does not play well with this method. Doing so, however, can
1578 be useful when the fixtures are different and defined in subclasses.
1579
Benjamin Petersond2397752009-06-27 23:45:02 +00001580 If a module provides a ``load_tests`` function it will be called to
1581 load the tests. This allows modules to customize test loading.
1582 This is the `load_tests protocol`_.
1583
Georg Brandl853947a2010-01-31 18:53:23 +00001584 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001585 Support for ``load_tests`` added.
1586
Benjamin Peterson52baa292009-03-24 00:56:30 +00001587
Georg Brandl7f01a132009-09-16 15:58:14 +00001588 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001589
1590 Return a suite of all tests cases given a string specifier.
1591
1592 The specifier *name* is a "dotted name" that may resolve either to a
1593 module, a test case class, a test method within a test case class, a
1594 :class:`TestSuite` instance, or a callable object which returns a
1595 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1596 applied in the order listed here; that is, a method on a possible test
1597 case class will be picked up as "a test method within a test case class",
1598 rather than "a callable object".
1599
1600 For example, if you have a module :mod:`SampleTests` containing a
1601 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1602 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001603 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1604 return a suite which will run all three test methods. Using the specifier
1605 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1606 suite which will run only the :meth:`test_two` test method. The specifier
1607 can refer to modules and packages which have not been imported; they will
1608 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001609
1610 The method optionally resolves *name* relative to the given *module*.
1611
1612
Georg Brandl7f01a132009-09-16 15:58:14 +00001613 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001614
1615 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1616 than a single name. The return value is a test suite which supports all
1617 the tests defined for each name.
1618
1619
1620 .. method:: getTestCaseNames(testCaseClass)
1621
1622 Return a sorted sequence of method names found within *testCaseClass*;
1623 this should be a subclass of :class:`TestCase`.
1624
Benjamin Petersond2397752009-06-27 23:45:02 +00001625
1626 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1627
1628 Find and return all test modules from the specified start directory,
1629 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001630 *pattern* will be loaded. (Using shell style pattern matching.) Only
1631 module names that are importable (i.e. are valid Python identifiers) will
1632 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001633
1634 All test modules must be importable from the top level of the project. If
1635 the start directory is not the top level directory then the top level
1636 directory must be specified separately.
1637
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001638 If importing a module fails, for example due to a syntax error, then this
1639 will be recorded as a single error and discovery will continue.
1640
Benjamin Petersond2397752009-06-27 23:45:02 +00001641 If a test package name (directory with :file:`__init__.py`) matches the
1642 pattern then the package will be checked for a ``load_tests``
1643 function. If this exists then it will be called with *loader*, *tests*,
1644 *pattern*.
1645
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001646 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001647 ``load_tests`` is responsible for loading all tests in the package.
1648
1649 The pattern is deliberately not stored as a loader attribute so that
1650 packages can continue discovery themselves. *top_level_dir* is stored so
1651 ``load_tests`` does not need to pass this argument in to
1652 ``loader.discover()``.
1653
Benjamin Petersonb48af542010-04-11 20:43:16 +00001654 *start_dir* can be a dotted module name as well as a directory.
1655
Georg Brandl853947a2010-01-31 18:53:23 +00001656 .. versionadded:: 3.2
1657
Benjamin Petersond2397752009-06-27 23:45:02 +00001658
Benjamin Peterson52baa292009-03-24 00:56:30 +00001659 The following attributes of a :class:`TestLoader` can be configured either by
1660 subclassing or assignment on an instance:
1661
1662
1663 .. attribute:: testMethodPrefix
1664
1665 String giving the prefix of method names which will be interpreted as test
1666 methods. The default value is ``'test'``.
1667
1668 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1669 methods.
1670
1671
1672 .. attribute:: sortTestMethodsUsing
1673
1674 Function to be used to compare method names when sorting them in
1675 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1676
1677
1678 .. attribute:: suiteClass
1679
1680 Callable object that constructs a test suite from a list of tests. No
1681 methods on the resulting object are needed. The default value is the
1682 :class:`TestSuite` class.
1683
1684 This affects all the :meth:`loadTestsFrom\*` methods.
1685
1686
Benjamin Peterson52baa292009-03-24 00:56:30 +00001687.. class:: TestResult
1688
1689 This class is used to compile information about which tests have succeeded
1690 and which have failed.
1691
1692 A :class:`TestResult` object stores the results of a set of tests. The
1693 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1694 properly recorded; test authors do not need to worry about recording the
1695 outcome of tests.
1696
1697 Testing frameworks built on top of :mod:`unittest` may want access to the
1698 :class:`TestResult` object generated by running a set of tests for reporting
1699 purposes; a :class:`TestResult` instance is returned by the
1700 :meth:`TestRunner.run` method for this purpose.
1701
1702 :class:`TestResult` instances have the following attributes that will be of
1703 interest when inspecting the results of running a set of tests:
1704
1705
1706 .. attribute:: errors
1707
1708 A list containing 2-tuples of :class:`TestCase` instances and strings
1709 holding formatted tracebacks. Each tuple represents a test which raised an
1710 unexpected exception.
1711
Benjamin Peterson52baa292009-03-24 00:56:30 +00001712 .. attribute:: failures
1713
1714 A list containing 2-tuples of :class:`TestCase` instances and strings
1715 holding formatted tracebacks. Each tuple represents a test where a failure
1716 was explicitly signalled using the :meth:`TestCase.fail\*` or
1717 :meth:`TestCase.assert\*` methods.
1718
Benjamin Peterson52baa292009-03-24 00:56:30 +00001719 .. attribute:: skipped
1720
1721 A list containing 2-tuples of :class:`TestCase` instances and strings
1722 holding the reason for skipping the test.
1723
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001724 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001725
1726 .. attribute:: expectedFailures
1727
Georg Brandl6faee4e2010-09-21 14:48:28 +00001728 A list containing 2-tuples of :class:`TestCase` instances and strings
1729 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001730 of the test case.
1731
1732 .. attribute:: unexpectedSuccesses
1733
1734 A list containing :class:`TestCase` instances that were marked as expected
1735 failures, but succeeded.
1736
1737 .. attribute:: shouldStop
1738
1739 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1740
1741
1742 .. attribute:: testsRun
1743
1744 The total number of tests run so far.
1745
1746
Georg Brandl12037202010-12-02 22:35:25 +00001747 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001748
1749 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1750 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1751 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1752 fails or errors. Any output is also attached to the failure / error message.
1753
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001754 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001755
1756
1757 .. attribute:: failfast
1758
1759 If set to true :meth:`stop` will be called on the first failure or error,
1760 halting the test run.
1761
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001762 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001763
1764
Benjamin Peterson52baa292009-03-24 00:56:30 +00001765 .. method:: wasSuccessful()
1766
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001767 Return ``True`` if all tests run so far have passed, otherwise returns
1768 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001769
1770
1771 .. method:: stop()
1772
1773 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001774 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001775 :class:`TestRunner` objects should respect this flag and return without
1776 running any additional tests.
1777
1778 For example, this feature is used by the :class:`TextTestRunner` class to
1779 stop the test framework when the user signals an interrupt from the
1780 keyboard. Interactive tools which provide :class:`TestRunner`
1781 implementations can use this in a similar manner.
1782
1783 The following methods of the :class:`TestResult` class are used to maintain
1784 the internal data structures, and may be extended in subclasses to support
1785 additional reporting requirements. This is particularly useful in building
1786 tools which support interactive reporting while tests are being run.
1787
1788
1789 .. method:: startTest(test)
1790
1791 Called when the test case *test* is about to be run.
1792
Benjamin Peterson52baa292009-03-24 00:56:30 +00001793 .. method:: stopTest(test)
1794
1795 Called after the test case *test* has been executed, regardless of the
1796 outcome.
1797
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001798 .. method:: startTestRun(test)
1799
1800 Called once before any tests are executed.
1801
Georg Brandl853947a2010-01-31 18:53:23 +00001802 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001803
1804
1805 .. method:: stopTestRun(test)
1806
Ezio Melotti176d6c42010-01-27 20:58:07 +00001807 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001808
Georg Brandl853947a2010-01-31 18:53:23 +00001809 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001810
1811
Benjamin Peterson52baa292009-03-24 00:56:30 +00001812 .. method:: addError(test, err)
1813
1814 Called when the test case *test* raises an unexpected exception *err* is a
1815 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1816 traceback)``.
1817
1818 The default implementation appends a tuple ``(test, formatted_err)`` to
1819 the instance's :attr:`errors` attribute, where *formatted_err* is a
1820 formatted traceback derived from *err*.
1821
1822
1823 .. method:: addFailure(test, err)
1824
Benjamin Petersond2397752009-06-27 23:45:02 +00001825 Called when the test case *test* signals a failure. *err* is a tuple of
1826 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001827
1828 The default implementation appends a tuple ``(test, formatted_err)`` to
1829 the instance's :attr:`failures` attribute, where *formatted_err* is a
1830 formatted traceback derived from *err*.
1831
1832
1833 .. method:: addSuccess(test)
1834
1835 Called when the test case *test* succeeds.
1836
1837 The default implementation does nothing.
1838
1839
1840 .. method:: addSkip(test, reason)
1841
1842 Called when the test case *test* is skipped. *reason* is the reason the
1843 test gave for skipping.
1844
1845 The default implementation appends a tuple ``(test, reason)`` to the
1846 instance's :attr:`skipped` attribute.
1847
1848
1849 .. method:: addExpectedFailure(test, err)
1850
1851 Called when the test case *test* fails, but was marked with the
1852 :func:`expectedFailure` decorator.
1853
1854 The default implementation appends a tuple ``(test, formatted_err)`` to
1855 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1856 is a formatted traceback derived from *err*.
1857
1858
1859 .. method:: addUnexpectedSuccess(test)
1860
1861 Called when the test case *test* was marked with the
1862 :func:`expectedFailure` decorator, but succeeded.
1863
1864 The default implementation appends the test to the instance's
1865 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001866
Georg Brandl67b21b72010-08-17 15:07:14 +00001867
Michael Foord34c94622010-02-10 15:51:42 +00001868.. class:: TextTestResult(stream, descriptions, verbosity)
1869
Georg Brandl67b21b72010-08-17 15:07:14 +00001870 A concrete implementation of :class:`TestResult` used by the
1871 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001872
Georg Brandl67b21b72010-08-17 15:07:14 +00001873 .. versionadded:: 3.2
1874 This class was previously named ``_TextTestResult``. The old name still
1875 exists as an alias but is deprecated.
1876
Georg Brandl116aa622007-08-15 14:28:22 +00001877
1878.. data:: defaultTestLoader
1879
1880 Instance of the :class:`TestLoader` class intended to be shared. If no
1881 customization of the :class:`TestLoader` is needed, this instance can be used
1882 instead of repeatedly creating new instances.
1883
1884
Michael Foordd218e952011-01-03 12:55:11 +00001885.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, runnerclass=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001886
Michael Foordd218e952011-01-03 12:55:11 +00001887 A basic test runner implementation that outputs results to a stream. If *stream*
1888 is `None`, the default, `sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001889 has a few configurable parameters, but is essentially very simple. Graphical
1890 applications which run test suites should provide alternate implementations.
1891
Ezio Melotti60901872010-12-01 00:56:10 +00001892 By default this runner shows :exc:`DeprecationWarning`,
1893 :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` even if they are
1894 :ref:`ignored by default <warning-ignored>`. Deprecation warnings caused by
1895 :ref:`deprecated unittest methods <deprecated-aliases>` are also
1896 special-cased and, when the warning filters are ``'default'`` or ``'always'``,
1897 they will appear only once per-module, in order to avoid too many warning
Georg Brandl46402372010-12-04 19:06:18 +00001898 messages. This behavior can be overridden using the :option:`-Wd` or
Ezio Melotti60901872010-12-01 00:56:10 +00001899 :option:`-Wa` options and leaving *warnings* to ``None``.
1900
Michael Foordd218e952011-01-03 12:55:11 +00001901 .. versionchanged:: 3.2
1902 Added the ``warnings`` argument.
1903
1904 .. versionchanged:: 3.2
1905 The default stream is set to `sys.stderr` at instantiation time rather
1906 than import time.
1907
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001908 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001909
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001910 This method returns the instance of ``TestResult`` used by :meth:`run`.
1911 It is not intended to be called directly, but can be overridden in
1912 subclasses to provide a custom ``TestResult``.
1913
Michael Foord34c94622010-02-10 15:51:42 +00001914 ``_makeResult()`` instantiates the class or callable passed in the
1915 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001916 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001917 The result class is instantiated with the following arguments::
1918
1919 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001920
Ezio Melotti60901872010-12-01 00:56:10 +00001921
Georg Brandl419e3de2010-12-01 15:44:25 +00001922.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
1923 testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1, \
1924 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001925
1926 A command-line program that runs a set of tests; this is primarily for making
1927 test modules conveniently executable. The simplest use for this function is to
1928 include the following line at the end of a test script::
1929
1930 if __name__ == '__main__':
1931 unittest.main()
1932
Benjamin Petersond2397752009-06-27 23:45:02 +00001933 You can run tests with more detailed information by passing in the verbosity
1934 argument::
1935
1936 if __name__ == '__main__':
1937 unittest.main(verbosity=2)
1938
Georg Brandl116aa622007-08-15 14:28:22 +00001939 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001940 created instance of it. By default ``main`` calls :func:`sys.exit` with
1941 an exit code indicating success or failure of the tests run.
1942
1943 ``main`` supports being used from the interactive interpreter by passing in the
1944 argument ``exit=False``. This displays the result on standard output without
1945 calling :func:`sys.exit`::
1946
1947 >>> from unittest import main
1948 >>> main(module='test_module', exit=False)
1949
Benjamin Petersonb48af542010-04-11 20:43:16 +00001950 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00001951 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001952
Ezio Melotti60901872010-12-01 00:56:10 +00001953 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
1954 that should be used while running the tests. If it's not specified, it will
1955 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
1956 otherwise it will be set to ``'default'``.
1957
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001958 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1959 This stores the result of the tests run as the ``result`` attribute.
1960
Éric Araujo971dc012010-12-16 03:13:05 +00001961 .. versionchanged:: 3.1
1962 The ``exit`` parameter was added.
1963
Georg Brandl853947a2010-01-31 18:53:23 +00001964 .. versionchanged:: 3.2
Éric Araujo971dc012010-12-16 03:13:05 +00001965 The ``verbosity``, ``failfast``, ``catchbreak``, ``buffer``
Ezio Melotti60901872010-12-01 00:56:10 +00001966 and ``warnings`` parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001967
1968
1969load_tests Protocol
1970###################
1971
Georg Brandl853947a2010-01-31 18:53:23 +00001972.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001973
Benjamin Petersond2397752009-06-27 23:45:02 +00001974Modules or packages can customize how tests are loaded from them during normal
1975test runs or test discovery by implementing a function called ``load_tests``.
1976
1977If a test module defines ``load_tests`` it will be called by
1978:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1979
1980 load_tests(loader, standard_tests, None)
1981
1982It should return a :class:`TestSuite`.
1983
1984*loader* is the instance of :class:`TestLoader` doing the loading.
1985*standard_tests* are the tests that would be loaded by default from the
1986module. It is common for test modules to only want to add or remove tests
1987from the standard set of tests.
1988The third argument is used when loading packages as part of test discovery.
1989
1990A typical ``load_tests`` function that loads tests from a specific set of
1991:class:`TestCase` classes may look like::
1992
1993 test_cases = (TestCase1, TestCase2, TestCase3)
1994
1995 def load_tests(loader, tests, pattern):
1996 suite = TestSuite()
1997 for test_class in test_cases:
1998 tests = loader.loadTestsFromTestCase(test_class)
1999 suite.addTests(tests)
2000 return suite
2001
2002If discovery is started, either from the command line or by calling
2003:meth:`TestLoader.discover`, with a pattern that matches a package
2004name then the package :file:`__init__.py` will be checked for ``load_tests``.
2005
2006.. note::
2007
Ezio Melotti0639d5a2009-12-19 23:26:38 +00002008 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00002009 that start with 'test' but *won't* match any test directories.
2010
2011 A pattern like 'test*' will match test packages as well as
2012 modules.
2013
2014If the package :file:`__init__.py` defines ``load_tests`` then it will be
2015called and discovery not continued into the package. ``load_tests``
2016is called with the following arguments::
2017
2018 load_tests(loader, standard_tests, pattern)
2019
2020This should return a :class:`TestSuite` representing all the tests
2021from the package. (``standard_tests`` will only contain tests
2022collected from :file:`__init__.py`.)
2023
2024Because the pattern is passed into ``load_tests`` the package is free to
2025continue (and potentially modify) test discovery. A 'do nothing'
2026``load_tests`` function for a test package would look like::
2027
2028 def load_tests(loader, standard_tests, pattern):
2029 # top level directory cached on loader instance
2030 this_dir = os.path.dirname(__file__)
2031 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2032 standard_tests.addTests(package_tests)
2033 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002034
2035
2036Class and Module Fixtures
2037-------------------------
2038
2039Class and module level fixtures are implemented in :class:`TestSuite`. When
2040the test suite encounters a test from a new class then :meth:`tearDownClass`
2041from the previous class (if there is one) is called, followed by
2042:meth:`setUpClass` from the new class.
2043
2044Similarly if a test is from a different module from the previous test then
2045``tearDownModule`` from the previous module is run, followed by
2046``setUpModule`` from the new module.
2047
2048After all the tests have run the final ``tearDownClass`` and
2049``tearDownModule`` are run.
2050
2051Note that shared fixtures do not play well with [potential] features like test
2052parallelization and they break test isolation. They should be used with care.
2053
2054The default ordering of tests created by the unittest test loaders is to group
2055all tests from the same modules and classes together. This will lead to
2056``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2057module. If you randomize the order, so that tests from different modules and
2058classes are adjacent to each other, then these shared fixture functions may be
2059called multiple times in a single test run.
2060
2061Shared fixtures are not intended to work with suites with non-standard
2062ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2063support shared fixtures.
2064
2065If there are any exceptions raised during one of the shared fixture functions
2066the test is reported as an error. Because there is no corresponding test
2067instance an ``_ErrorHolder`` object (that has the same interface as a
2068:class:`TestCase`) is created to represent the error. If you are just using
2069the standard unittest test runner then this detail doesn't matter, but if you
2070are a framework author it may be relevant.
2071
2072
2073setUpClass and tearDownClass
2074~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2075
2076These must be implemented as class methods::
2077
2078 import unittest
2079
2080 class Test(unittest.TestCase):
2081 @classmethod
2082 def setUpClass(cls):
2083 cls._connection = createExpensiveConnectionObject()
2084
2085 @classmethod
2086 def tearDownClass(cls):
2087 cls._connection.destroy()
2088
2089If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2090then you must call up to them yourself. The implementations in
2091:class:`TestCase` are empty.
2092
2093If an exception is raised during a ``setUpClass`` then the tests in the class
2094are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002095have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
2096``SkipTest`` exception then the class will be reported as having been skipped
2097instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002098
2099
2100setUpModule and tearDownModule
2101~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2102
2103These should be implemented as functions::
2104
2105 def setUpModule():
2106 createConnection()
2107
2108 def tearDownModule():
2109 closeConnection()
2110
2111If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002112module will be run and the ``tearDownModule`` will not be run. If the exception is a
2113``SkipTest`` exception then the module will be reported as having been skipped
2114instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002115
2116
2117Signal Handling
2118---------------
2119
Georg Brandl419e3de2010-12-01 15:44:25 +00002120.. versionadded:: 3.2
2121
Éric Araujo8acb67c2010-11-26 23:31:07 +00002122The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002123along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2124more friendly handling of control-C during a test run. With catch break
2125behavior enabled control-C will allow the currently running test to complete,
2126and the test run will then end and report all the results so far. A second
2127control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002128
Michael Foordde4ceab2010-04-25 19:53:49 +00002129The control-c handling signal handler attempts to remain compatible with code or
2130tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2131handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2132i.e. it has been replaced by the system under test and delegated to, then it
2133calls the default handler. This will normally be the expected behavior by code
2134that replaces an installed handler and delegates to it. For individual tests
2135that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2136decorator can be used.
2137
2138There are a few utility functions for framework authors to enable control-c
2139handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002140
2141.. function:: installHandler()
2142
2143 Install the control-c handler. When a :const:`signal.SIGINT` is received
2144 (usually in response to the user pressing control-c) all registered results
2145 have :meth:`~TestResult.stop` called.
2146
Michael Foord469b1f02010-04-26 23:41:26 +00002147
Benjamin Petersonb48af542010-04-11 20:43:16 +00002148.. function:: registerResult(result)
2149
2150 Register a :class:`TestResult` object for control-c handling. Registering a
2151 result stores a weak reference to it, so it doesn't prevent the result from
2152 being garbage collected.
2153
Michael Foordde4ceab2010-04-25 19:53:49 +00002154 Registering a :class:`TestResult` object has no side-effects if control-c
2155 handling is not enabled, so test frameworks can unconditionally register
2156 all results they create independently of whether or not handling is enabled.
2157
Michael Foord469b1f02010-04-26 23:41:26 +00002158
Benjamin Petersonb48af542010-04-11 20:43:16 +00002159.. function:: removeResult(result)
2160
2161 Remove a registered result. Once a result has been removed then
2162 :meth:`~TestResult.stop` will no longer be called on that result object in
2163 response to a control-c.
2164
Michael Foord469b1f02010-04-26 23:41:26 +00002165
Michael Foordde4ceab2010-04-25 19:53:49 +00002166.. function:: removeHandler(function=None)
2167
2168 When called without arguments this function removes the control-c handler
2169 if it has been installed. This function can also be used as a test decorator
2170 to temporarily remove the handler whilst the test is being executed::
2171
2172 @unittest.removeHandler
2173 def test_signal_handling(self):
2174 ...