blob: 698ff6b5bc0d73b038c82b546a2f26c687f0c9ec [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`unittest` --- Unit testing framework
2==========================================
3
4.. module:: unittest
5 :synopsis: Unit testing framework for Python.
6.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
7.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9.. sectionauthor:: Raymond Hettinger <python@rcn.com>
10
Ezio Melotti22170ed2010-11-20 09:57:27 +000011(If you are already familiar with the basic concepts of testing, you might want
12to skip to :ref:`the list of assert methods <assert-methods>`.)
Georg Brandl116aa622007-08-15 14:28:22 +000013
Georg Brandl116aa622007-08-15 14:28:22 +000014The Python unit testing framework, sometimes referred to as "PyUnit," is a
15Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
16turn, a Java version of Kent's Smalltalk testing framework. Each is the de
17facto standard unit testing framework for its respective language.
18
19:mod:`unittest` supports test automation, sharing of setup and shutdown code for
20tests, aggregation of tests into collections, and independence of the tests from
21the reporting framework. The :mod:`unittest` module provides classes that make
22it easy to support these qualities for a set of tests.
23
24To achieve this, :mod:`unittest` supports some important concepts:
25
26test fixture
27 A :dfn:`test fixture` represents the preparation needed to perform one or more
28 tests, and any associate cleanup actions. This may involve, for example,
29 creating temporary or proxy databases, directories, or starting a server
30 process.
31
32test case
33 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
34 response to a particular set of inputs. :mod:`unittest` provides a base class,
35 :class:`TestCase`, which may be used to create new test cases.
36
37test suite
38 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
39 used to aggregate tests that should be executed together.
40
41test runner
42 A :dfn:`test runner` is a component which orchestrates the execution of tests
43 and provides the outcome to the user. The runner may use a graphical interface,
44 a textual interface, or return a special value to indicate the results of
45 executing the tests.
46
47The test case and test fixture concepts are supported through the
48:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
49used when creating new tests, and the latter can be used when integrating
50existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson52baa292009-03-24 00:56:30 +000051fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
52:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
53and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
54can be passed to the constructor for these purposes. When the test is run, the
55fixture initialization is run first; if it succeeds, the cleanup method is run
56after the test has been executed, regardless of the outcome of the test. Each
57instance of the :class:`TestCase` will only be used to run a single test method,
58so a new fixture is created for each test.
Georg Brandl116aa622007-08-15 14:28:22 +000059
60Test suites are implemented by the :class:`TestSuite` class. This class allows
61individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson14a3dd72009-05-25 00:51:58 +000062all tests added directly to the suite and in "child" test suites are run.
Georg Brandl116aa622007-08-15 14:28:22 +000063
Benjamin Peterson52baa292009-03-24 00:56:30 +000064A test runner is an object that provides a single method,
65:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
66object as a parameter, and returns a result object. The class
67:class:`TestResult` is provided for use as the result object. :mod:`unittest`
68provides the :class:`TextTestRunner` as an example test runner which reports
69test results on the standard error stream by default. Alternate runners can be
70implemented for other environments (such as graphical environments) without any
71need to derive from a specific class.
Georg Brandl116aa622007-08-15 14:28:22 +000072
73
74.. seealso::
75
76 Module :mod:`doctest`
77 Another test-support module with a very different flavor.
78
Benjamin Petersonb48af542010-04-11 20:43:16 +000079 `unittest2: A backport of new unittest features for Python 2.4-2.6 <http://pypi.python.org/pypi/unittest2>`_
80 Many new features were added to unittest in Python 2.7, including test
81 discovery. unittest2 allows you to use these features with earlier
82 versions of Python.
83
Georg Brandl116aa622007-08-15 14:28:22 +000084 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000085 Kent Beck's original paper on testing frameworks using the pattern shared
86 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000087
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000088 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000089 Third-party unittest frameworks with a lighter-weight syntax for writing
90 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000091
Benjamin Petersonb48af542010-04-11 20:43:16 +000092 `The Python Testing Tools Taxonomy <http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy>`_
93 An extensive list of Python testing tools including functional testing
94 frameworks and mock object libraries.
Benjamin Petersond2397752009-06-27 23:45:02 +000095
Benjamin Petersonb48af542010-04-11 20:43:16 +000096 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
97 A special-interest-group for discussion of testing, and testing tools,
98 in Python.
Benjamin Petersond2397752009-06-27 23:45:02 +000099
Georg Brandl116aa622007-08-15 14:28:22 +0000100.. _unittest-minimal-example:
101
102Basic example
103-------------
104
105The :mod:`unittest` module provides a rich set of tools for constructing and
106running tests. This section demonstrates that a small subset of the tools
107suffice to meet the needs of most users.
108
109Here is a short script to test three functions from the :mod:`random` module::
110
111 import random
112 import unittest
113
114 class TestSequenceFunctions(unittest.TestCase):
115
116 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000117 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Benjamin Peterson52baa292009-03-24 00:56:30 +0000119 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000120 # make sure the shuffled sequence does not lose any elements
121 random.shuffle(self.seq)
122 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000123 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +0000124
Benjamin Peterson847a4112010-03-14 15:04:17 +0000125 # should raise an exception for an immutable sequence
126 self.assertRaises(TypeError, random.shuffle, (1,2,3))
127
Benjamin Peterson52baa292009-03-24 00:56:30 +0000128 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000129 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000130 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000131
Benjamin Peterson52baa292009-03-24 00:56:30 +0000132 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000133 with self.assertRaises(ValueError):
134 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000135 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000136 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138 if __name__ == '__main__':
139 unittest.main()
140
Benjamin Peterson52baa292009-03-24 00:56:30 +0000141A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000142individual tests are defined with methods whose names start with the letters
143``test``. This naming convention informs the test runner about which methods
144represent tests.
145
Benjamin Peterson52baa292009-03-24 00:56:30 +0000146The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000147expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000148:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
149These methods are used instead of the :keyword:`assert` statement so the test
150runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000151
Benjamin Peterson52baa292009-03-24 00:56:30 +0000152When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
153method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
154defined, the test runner will invoke that method after each test. In the
155example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
156test.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000159provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000160line, the above script produces an output that looks like this::
161
162 ...
163 ----------------------------------------------------------------------
164 Ran 3 tests in 0.000s
165
166 OK
167
168Instead of :func:`unittest.main`, there are other ways to run the tests with a
169finer level of control, less terse output, and no requirement to be run from the
170command line. For example, the last two lines may be replaced with::
171
172 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
173 unittest.TextTestRunner(verbosity=2).run(suite)
174
175Running the revised script from the interpreter or another script produces the
176following output::
177
Ezio Melottid59e44a2010-02-28 03:46:13 +0000178 test_choice (__main__.TestSequenceFunctions) ... ok
179 test_sample (__main__.TestSequenceFunctions) ... ok
180 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182 ----------------------------------------------------------------------
183 Ran 3 tests in 0.110s
184
185 OK
186
187The above examples show the most commonly used :mod:`unittest` features which
188are sufficient to meet many everyday testing needs. The remainder of the
189documentation explores the full feature set from first principles.
190
Benjamin Petersonb48af542010-04-11 20:43:16 +0000191
192.. _unittest-command-line-interface:
193
Éric Araujo76338ec2010-11-26 23:46:18 +0000194Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000195----------------------
196
197The unittest module can be used from the command line to run tests from
198modules, classes or even individual test methods::
199
200 python -m unittest test_module1 test_module2
201 python -m unittest test_module.TestClass
202 python -m unittest test_module.TestClass.test_method
203
204You can pass in a list with any combination of module names, and fully
205qualified class or method names.
206
207You can run tests with more detail (higher verbosity) by passing in the -v flag::
208
209 python -m unittest -v test_module
210
Michael Foord086f3082010-11-21 21:28:01 +0000211When executed without arguments :ref:`unittest-test-discovery` is started::
212
213 python -m unittest
214
Éric Araujo713d3032010-11-18 16:38:46 +0000215For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000216
217 python -m unittest -h
218
Georg Brandl67b21b72010-08-17 15:07:14 +0000219.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000220 In earlier versions it was only possible to run individual test methods and
221 not modules or classes.
222
223
Éric Araujo76338ec2010-11-26 23:46:18 +0000224Command-line options
225~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000226
Éric Araujod3309df2010-11-21 03:09:17 +0000227:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000228
Éric Araujo713d3032010-11-18 16:38:46 +0000229.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000230
Éric Araujo713d3032010-11-18 16:38:46 +0000231.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000232
Éric Araujo713d3032010-11-18 16:38:46 +0000233 The standard output and standard error streams are buffered during the test
234 run. Output during a passing test is discarded. Output is echoed normally
235 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000236
Éric Araujo713d3032010-11-18 16:38:46 +0000237.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000238
Éric Araujo713d3032010-11-18 16:38:46 +0000239 Control-C during the test run waits for the current test to end and then
240 reports all the results so far. A second control-C raises the normal
241 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000242
Éric Araujo713d3032010-11-18 16:38:46 +0000243 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000244
Éric Araujo713d3032010-11-18 16:38:46 +0000245.. cmdoption:: -f, --failfast
246
247 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000248
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000249.. versionadded:: 3.2
Éric Araujo76338ec2010-11-26 23:46:18 +0000250 The command-line options :option:`-b`, :option:`-c` and :option:`-f`
251 were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000252
253The command line can also be used for test discovery, for running all of the
254tests in a project or just a subset.
255
256
257.. _unittest-test-discovery:
258
259Test Discovery
260--------------
261
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000262.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000263
264Unittest supports simple test discovery. For a project's tests to be
265compatible with test discovery they must all be importable from the top level
266directory of the project (in other words, they must all be in Python packages).
267
268Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000269used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000270
271 cd project_directory
272 python -m unittest discover
273
Michael Foord086f3082010-11-21 21:28:01 +0000274.. note::
275
276 As a shortcut, ``python -m unittest`` is the equivalent of
277 ``python -m unittest discover``. If you want to pass arguments to test
278 discovery the `discover` sub-command must be used explicitly.
279
Benjamin Petersonb48af542010-04-11 20:43:16 +0000280The ``discover`` sub-command has the following options:
281
Éric Araujo713d3032010-11-18 16:38:46 +0000282.. program:: unittest discover
283
284.. cmdoption:: -v, --verbose
285
286 Verbose output
287
288.. cmdoption:: -s directory
289
290 Directory to start discovery ('.' default)
291
292.. cmdoption:: -p pattern
293
294 Pattern to match test files ('test*.py' default)
295
296.. cmdoption:: -t directory
297
298 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000299
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000300The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
301as positional arguments in that order. The following two command lines
302are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000303
304 python -m unittest discover -s project_directory -p '*_test.py'
305 python -m unittest discover project_directory '*_test.py'
306
Michael Foord16f3e902010-05-08 15:13:42 +0000307As well as being a path it is possible to pass a package name, for example
308``myproject.subpackage.test``, as the start directory. The package name you
309supply will then be imported and its location on the filesystem will be used
310as the start directory.
311
312.. caution::
313
Senthil Kumaran916bd382010-10-15 12:55:19 +0000314 Test discovery loads tests by importing them. Once test discovery has found
315 all the test files from the start directory you specify it turns the paths
316 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000317 imported as ``foo.bar.baz``.
318
319 If you have a package installed globally and attempt test discovery on
320 a different copy of the package then the import *could* happen from the
321 wrong place. If this happens test discovery will warn you and exit.
322
323 If you supply the start directory as a package name rather than a
324 path to a directory then discover assumes that whichever location it
325 imports from is the location you intended, so you will not get the
326 warning.
327
Benjamin Petersonb48af542010-04-11 20:43:16 +0000328Test modules and packages can customize test loading and discovery by through
329the `load_tests protocol`_.
330
331
Georg Brandl116aa622007-08-15 14:28:22 +0000332.. _organizing-tests:
333
334Organizing test code
335--------------------
336
337The basic building blocks of unit testing are :dfn:`test cases` --- single
338scenarios that must be set up and checked for correctness. In :mod:`unittest`,
339test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
340class. To make your own test cases you must write subclasses of
341:class:`TestCase`, or use :class:`FunctionTestCase`.
342
343An instance of a :class:`TestCase`\ -derived class is an object that can
344completely run a single test method, together with optional set-up and tidy-up
345code.
346
347The testing code of a :class:`TestCase` instance should be entirely self
348contained, such that it can be run either in isolation or in arbitrary
349combination with any number of other test cases.
350
Benjamin Peterson52baa292009-03-24 00:56:30 +0000351The simplest :class:`TestCase` subclass will simply override the
352:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354 import unittest
355
356 class DefaultWidgetSizeTestCase(unittest.TestCase):
357 def runTest(self):
358 widget = Widget('The widget')
359 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
360
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000361Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000362methods provided by the :class:`TestCase` base class. If the test fails, an
363exception will be raised, and :mod:`unittest` will identify the test case as a
364:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
365helps you identify where the problem is: :dfn:`failures` are caused by incorrect
366results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
367code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369The way to run a test case will be described later. For now, note that to
370construct an instance of such a test case, we call its constructor without
371arguments::
372
373 testCase = DefaultWidgetSizeTestCase()
374
375Now, such test cases can be numerous, and their set-up can be repetitive. In
376the above case, constructing a :class:`Widget` in each of 100 Widget test case
377subclasses would mean unsightly duplication.
378
379Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000380:meth:`~TestCase.setUp`, which the testing framework will automatically call for
381us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383 import unittest
384
385 class SimpleWidgetTestCase(unittest.TestCase):
386 def setUp(self):
387 self.widget = Widget('The widget')
388
389 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
390 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000391 self.assertEqual(self.widget.size(), (50,50),
392 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394 class WidgetResizeTestCase(SimpleWidgetTestCase):
395 def runTest(self):
396 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000397 self.assertEqual(self.widget.size(), (100,150),
398 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000399
Benjamin Peterson52baa292009-03-24 00:56:30 +0000400If the :meth:`~TestCase.setUp` method raises an exception while the test is
401running, the framework will consider the test to have suffered an error, and the
402:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000403
Benjamin Peterson52baa292009-03-24 00:56:30 +0000404Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
405after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407 import unittest
408
409 class SimpleWidgetTestCase(unittest.TestCase):
410 def setUp(self):
411 self.widget = Widget('The widget')
412
413 def tearDown(self):
414 self.widget.dispose()
415 self.widget = None
416
Benjamin Peterson52baa292009-03-24 00:56:30 +0000417If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
418be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420Such a working environment for the testing code is called a :dfn:`fixture`.
421
422Often, many small test cases will use the same fixture. In this case, we would
423end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
424classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000425discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
426mechanism::
427
428 import unittest
429
430 class WidgetTestCase(unittest.TestCase):
431 def setUp(self):
432 self.widget = Widget('The widget')
433
434 def tearDown(self):
435 self.widget.dispose()
436 self.widget = None
437
Ezio Melottid59e44a2010-02-28 03:46:13 +0000438 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000439 self.assertEqual(self.widget.size(), (50,50),
440 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000441
Ezio Melottid59e44a2010-02-28 03:46:13 +0000442 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000443 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000444 self.assertEqual(self.widget.size(), (100,150),
445 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000446
Benjamin Peterson52baa292009-03-24 00:56:30 +0000447Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
448provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000449the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000450separately for each instance. When creating an instance we must specify the
451test method it is to run. We do this by passing the method name in the
452constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000453
Ezio Melottid59e44a2010-02-28 03:46:13 +0000454 defaultSizeTestCase = WidgetTestCase('test_default_size')
455 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000456
457Test case instances are grouped together according to the features they test.
458:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
459represented by :mod:`unittest`'s :class:`TestSuite` class::
460
461 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000462 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
463 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000464
465For the ease of running tests, as we will see later, it is a good idea to
466provide in each test module a callable object that returns a pre-built test
467suite::
468
469 def suite():
470 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000471 suite.addTest(WidgetTestCase('test_default_size'))
472 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000473 return suite
474
475or even::
476
477 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000478 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000479
480 return unittest.TestSuite(map(WidgetTestCase, tests))
481
482Since it is a common pattern to create a :class:`TestCase` subclass with many
483similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
484class that can be used to automate the process of creating a test suite and
485populating it with individual tests. For example, ::
486
487 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
488
Ezio Melottid59e44a2010-02-28 03:46:13 +0000489will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
490``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000491name prefix to identify test methods automatically.
492
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000493Note that the order in which the various test cases will be run is
494determined by sorting the test function names with respect to the
495built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000496
497Often it is desirable to group suites of test cases together, so as to run tests
498for the whole system at once. This is easy, since :class:`TestSuite` instances
499can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
500added to a :class:`TestSuite`::
501
502 suite1 = module1.TheTestSuite()
503 suite2 = module2.TheTestSuite()
504 alltests = unittest.TestSuite([suite1, suite2])
505
506You can place the definitions of test cases and test suites in the same modules
507as the code they are to test (such as :file:`widget.py`), but there are several
508advantages to placing the test code in a separate module, such as
509:file:`test_widget.py`:
510
511* The test module can be run standalone from the command line.
512
513* The test code can more easily be separated from shipped code.
514
515* There is less temptation to change test code to fit the code it tests without
516 a good reason.
517
518* Test code should be modified much less frequently than the code it tests.
519
520* Tested code can be refactored more easily.
521
522* Tests for modules written in C must be in separate modules anyway, so why not
523 be consistent?
524
525* If the testing strategy changes, there is no need to change the source code.
526
527
528.. _legacy-unit-tests:
529
530Re-using old test code
531----------------------
532
533Some users will find that they have existing test code that they would like to
534run from :mod:`unittest`, without converting every old test function to a
535:class:`TestCase` subclass.
536
537For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
538This subclass of :class:`TestCase` can be used to wrap an existing test
539function. Set-up and tear-down functions can also be provided.
540
541Given the following test function::
542
543 def testSomething():
544 something = makeSomething()
545 assert something.name is not None
546 # ...
547
548one can create an equivalent test case instance as follows::
549
550 testcase = unittest.FunctionTestCase(testSomething)
551
552If there are additional set-up and tear-down methods that should be called as
553part of the test case's operation, they can also be provided like so::
554
555 testcase = unittest.FunctionTestCase(testSomething,
556 setUp=makeSomethingDB,
557 tearDown=deleteSomethingDB)
558
559To make migrating existing test suites easier, :mod:`unittest` supports tests
560raising :exc:`AssertionError` to indicate test failure. However, it is
561recommended that you use the explicit :meth:`TestCase.fail\*` and
562:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
563may treat :exc:`AssertionError` differently.
564
565.. note::
566
Benjamin Petersond2397752009-06-27 23:45:02 +0000567 Even though :class:`FunctionTestCase` can be used to quickly convert an
568 existing test base over to a :mod:`unittest`\ -based system, this approach is
569 not recommended. Taking the time to set up proper :class:`TestCase`
570 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000571
Benjamin Peterson52baa292009-03-24 00:56:30 +0000572In some cases, the existing tests may have been written using the :mod:`doctest`
573module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
574automatically build :class:`unittest.TestSuite` instances from the existing
575:mod:`doctest`\ -based tests.
576
Georg Brandl116aa622007-08-15 14:28:22 +0000577
Benjamin Peterson5254c042009-03-23 22:25:03 +0000578.. _unittest-skipping:
579
580Skipping tests and expected failures
581------------------------------------
582
Michael Foordf5c851a2010-02-05 21:48:03 +0000583.. versionadded:: 3.1
584
Benjamin Peterson5254c042009-03-23 22:25:03 +0000585Unittest supports skipping individual test methods and even whole classes of
586tests. In addition, it supports marking a test as a "expected failure," a test
587that is broken and will fail, but shouldn't be counted as a failure on a
588:class:`TestResult`.
589
590Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
591or one of its conditional variants.
592
593Basic skipping looks like this: ::
594
595 class MyTestCase(unittest.TestCase):
596
597 @unittest.skip("demonstrating skipping")
598 def test_nothing(self):
599 self.fail("shouldn't happen")
600
Benjamin Petersond2397752009-06-27 23:45:02 +0000601 @unittest.skipIf(mylib.__version__ < (1, 3),
602 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000603 def test_format(self):
604 # Tests that work for only a certain version of the library.
605 pass
606
607 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
608 def test_windows_support(self):
609 # windows specific testing code
610 pass
611
Benjamin Peterson5254c042009-03-23 22:25:03 +0000612This is the output of running the example above in verbose mode: ::
613
Benjamin Petersonded31c42009-03-30 15:04:16 +0000614 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000615 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000616 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000617
618 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000619 Ran 3 tests in 0.005s
620
621 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000622
623Classes can be skipped just like methods: ::
624
625 @skip("showing class skipping")
626 class MySkippedTestCase(unittest.TestCase):
627 def test_not_run(self):
628 pass
629
Benjamin Peterson52baa292009-03-24 00:56:30 +0000630:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
631that needs to be set up is not available.
632
Benjamin Peterson5254c042009-03-23 22:25:03 +0000633Expected failures use the :func:`expectedFailure` decorator. ::
634
635 class ExpectedFailureTestCase(unittest.TestCase):
636 @unittest.expectedFailure
637 def test_fail(self):
638 self.assertEqual(1, 0, "broken")
639
640It's easy to roll your own skipping decorators by making a decorator that calls
641:func:`skip` on the test when it wants it to be skipped. This decorator skips
642the test unless the passed object has a certain attribute: ::
643
644 def skipUnlessHasattr(obj, attr):
645 if hasattr(obj, attr):
646 return lambda func: func
647 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
648
649The following decorators implement test skipping and expected failures:
650
Georg Brandl8a1caa22010-07-29 16:01:11 +0000651.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000652
653 Unconditionally skip the decorated test. *reason* should describe why the
654 test is being skipped.
655
Georg Brandl8a1caa22010-07-29 16:01:11 +0000656.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000657
658 Skip the decorated test if *condition* is true.
659
Georg Brandl8a1caa22010-07-29 16:01:11 +0000660.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000661
Georg Brandl6faee4e2010-09-21 14:48:28 +0000662 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000663
Georg Brandl8a1caa22010-07-29 16:01:11 +0000664.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000665
666 Mark the test as an expected failure. If the test fails when run, the test
667 is not counted as a failure.
668
Benjamin Petersonb48af542010-04-11 20:43:16 +0000669Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
670Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
671
Benjamin Peterson5254c042009-03-23 22:25:03 +0000672
Georg Brandl116aa622007-08-15 14:28:22 +0000673.. _unittest-contents:
674
675Classes and functions
676---------------------
677
Benjamin Peterson52baa292009-03-24 00:56:30 +0000678This section describes in depth the API of :mod:`unittest`.
679
680
681.. _testcase-objects:
682
683Test cases
684~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Georg Brandl7f01a132009-09-16 15:58:14 +0000686.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000687
688 Instances of the :class:`TestCase` class represent the smallest testable units
689 in the :mod:`unittest` universe. This class is intended to be used as a base
690 class, with specific tests being implemented by concrete subclasses. This class
691 implements the interface needed by the test runner to allow it to drive the
692 test, and methods that the test code can use to check for and report various
693 kinds of failure.
694
695 Each instance of :class:`TestCase` will run a single test method: the method
696 named *methodName*. If you remember, we had an earlier example that went
697 something like this::
698
699 def suite():
700 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000701 suite.addTest(WidgetTestCase('test_default_size'))
702 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000703 return suite
704
705 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
706 single test.
707
Benjamin Peterson52baa292009-03-24 00:56:30 +0000708 *methodName* defaults to :meth:`runTest`.
709
710 :class:`TestCase` instances provide three groups of methods: one group used
711 to run the test, another used by the test implementation to check conditions
712 and report failures, and some inquiry methods allowing information about the
713 test itself to be gathered.
714
715 Methods in the first group (running the test) are:
716
717
718 .. method:: setUp()
719
720 Method called to prepare the test fixture. This is called immediately
721 before calling the test method; any exception raised by this method will
722 be considered an error rather than a test failure. The default
723 implementation does nothing.
724
725
726 .. method:: tearDown()
727
728 Method called immediately after the test method has been called and the
729 result recorded. This is called even if the test method raised an
730 exception, so the implementation in subclasses may need to be particularly
731 careful about checking internal state. Any exception raised by this
732 method will be considered an error rather than a test failure. This
733 method will only be called if the :meth:`setUp` succeeds, regardless of
734 the outcome of the test method. The default implementation does nothing.
735
736
Benjamin Petersonb48af542010-04-11 20:43:16 +0000737 .. method:: setUpClass()
738
739 A class method called before tests in an individual class run.
740 ``setUpClass`` is called with the class as the only argument
741 and must be decorated as a :func:`classmethod`::
742
743 @classmethod
744 def setUpClass(cls):
745 ...
746
747 See `Class and Module Fixtures`_ for more details.
748
749 .. versionadded:: 3.2
750
751
752 .. method:: tearDownClass()
753
754 A class method called after tests in an individual class have run.
755 ``tearDownClass`` is called with the class as the only argument
756 and must be decorated as a :meth:`classmethod`::
757
758 @classmethod
759 def tearDownClass(cls):
760 ...
761
762 See `Class and Module Fixtures`_ for more details.
763
764 .. versionadded:: 3.2
765
766
Georg Brandl7f01a132009-09-16 15:58:14 +0000767 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000768
769 Run the test, collecting the result into the test result object passed as
Ezio Melotti75b2a5e2010-11-20 10:13:45 +0000770 *result*. If *result* is omitted or ``None``, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000771 object is created (by calling the :meth:`defaultTestResult` method) and
772 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000773
774 The same effect may be had by simply calling the :class:`TestCase`
775 instance.
776
777
Benjamin Petersone549ead2009-03-28 21:42:05 +0000778 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000779
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000780 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000781 test. See :ref:`unittest-skipping` for more information.
782
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000783 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000784
Benjamin Peterson52baa292009-03-24 00:56:30 +0000785
786 .. method:: debug()
787
788 Run the test without collecting the result. This allows exceptions raised
789 by the test to be propagated to the caller, and can be used to support
790 running tests under a debugger.
791
Ezio Melotti22170ed2010-11-20 09:57:27 +0000792 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000793
Ezio Melotti4370b302010-11-03 20:39:14 +0000794 The :class:`TestCase` class provides a number of methods to check for and
795 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000796
Ezio Melotti4370b302010-11-03 20:39:14 +0000797 +-----------------------------------------+-----------------------------+---------------+
798 | Method | Checks that | New in |
799 +=========================================+=============================+===============+
800 | :meth:`assertEqual(a, b) | ``a == b`` | |
801 | <TestCase.assertEqual>` | | |
802 +-----------------------------------------+-----------------------------+---------------+
803 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
804 | <TestCase.assertNotEqual>` | | |
805 +-----------------------------------------+-----------------------------+---------------+
806 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
807 | <TestCase.assertTrue>` | | |
808 +-----------------------------------------+-----------------------------+---------------+
809 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
810 | <TestCase.assertFalse>` | | |
811 +-----------------------------------------+-----------------------------+---------------+
812 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
813 | <TestCase.assertIs>` | | |
814 +-----------------------------------------+-----------------------------+---------------+
815 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
816 | <TestCase.assertIsNot>` | | |
817 +-----------------------------------------+-----------------------------+---------------+
818 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
819 | <TestCase.assertIsNone>` | | |
820 +-----------------------------------------+-----------------------------+---------------+
821 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
822 | <TestCase.assertIsNotNone>` | | |
823 +-----------------------------------------+-----------------------------+---------------+
824 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
825 | <TestCase.assertIn>` | | |
826 +-----------------------------------------+-----------------------------+---------------+
827 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
828 | <TestCase.assertNotIn>` | | |
829 +-----------------------------------------+-----------------------------+---------------+
830 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
831 | <TestCase.assertIsInstance>` | | |
832 +-----------------------------------------+-----------------------------+---------------+
833 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
834 | <TestCase.assertNotIsInstance>` | | |
835 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000836
Ezio Melotti22170ed2010-11-20 09:57:27 +0000837 All the assert methods (except :meth:`assertRaises`,
Ezio Melottied3a7d22010-12-01 02:32:32 +0000838 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`)
Ezio Melotti22170ed2010-11-20 09:57:27 +0000839 accept a *msg* argument that, if specified, is used as the error message on
840 failure (see also :data:`longMessage`).
Benjamin Peterson52baa292009-03-24 00:56:30 +0000841
Georg Brandl7f01a132009-09-16 15:58:14 +0000842 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000843
844 Test that *first* and *second* are equal. If the values do not compare
Ezio Melotti4841fd62010-11-05 15:43:40 +0000845 equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000846
847 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000848 list, tuple, dict, set, frozenset or str or any type that a subclass
849 registers with :meth:`addTypeEqualityFunc` the type specific equality
850 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000851 error message (see also the :ref:`list of type-specific methods
852 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000853
Raymond Hettinger35a88362009-04-09 00:08:24 +0000854 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000855 Added the automatic calling of type specific equality function.
856
Michael Foord28a817e2010-02-09 00:03:57 +0000857 .. versionchanged:: 3.2
858 :meth:`assertMultiLineEqual` added as the default type equality
859 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000860
Benjamin Peterson52baa292009-03-24 00:56:30 +0000861
Georg Brandl7f01a132009-09-16 15:58:14 +0000862 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000863
864 Test that *first* and *second* are not equal. If the values do compare
Ezio Melotti4841fd62010-11-05 15:43:40 +0000865 equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000866
Ezio Melotti4370b302010-11-03 20:39:14 +0000867 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000868 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000869
Ezio Melotti4841fd62010-11-05 15:43:40 +0000870 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000871
Ezio Melotti4841fd62010-11-05 15:43:40 +0000872 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
873 is True`` (use ``assertIs(expr, True)`` for the latter). This method
874 should also be avoided when more specific methods are available (e.g.
875 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
876 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000877
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000878
Ezio Melotti9794a262010-11-04 14:52:13 +0000879 .. method:: assertIs(first, second, msg=None)
880 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000881
Ezio Melotti9794a262010-11-04 14:52:13 +0000882 Test that *first* and *second* evaluate (or don't evaluate) to the same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000883
Raymond Hettinger35a88362009-04-09 00:08:24 +0000884 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000885
886
Ezio Melotti4370b302010-11-03 20:39:14 +0000887 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000888 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000889
Ezio Melotti9794a262010-11-04 14:52:13 +0000890 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000891
Ezio Melotti4370b302010-11-03 20:39:14 +0000892 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000893
894
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000895 .. method:: assertIn(first, second, msg=None)
896 assertNotIn(first, second, msg=None)
897
Ezio Melotti4841fd62010-11-05 15:43:40 +0000898 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000899
Raymond Hettinger35a88362009-04-09 00:08:24 +0000900 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000901
902
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000903 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000904 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000905
Ezio Melotti9794a262010-11-04 14:52:13 +0000906 Test that *obj* is (or is not) an instance of *cls* (which can be a
907 class or a tuple of classes, as supported by :func:`isinstance`).
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000908
Ezio Melotti4370b302010-11-03 20:39:14 +0000909 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000910
911
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000912
Ezio Melotti4370b302010-11-03 20:39:14 +0000913 It is also possible to check that exceptions and warnings are raised using
914 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000915
Ezio Melotti4370b302010-11-03 20:39:14 +0000916 +---------------------------------------------------------+--------------------------------------+------------+
917 | Method | Checks that | New in |
918 +=========================================================+======================================+============+
919 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | |
920 | <TestCase.assertRaises>` | | |
921 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +0000922 | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
923 | <TestCase.assertRaisesRegex>` | and the message matches `re` | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000924 +---------------------------------------------------------+--------------------------------------+------------+
925 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
926 | <TestCase.assertWarns>` | | |
927 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +0000928 | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
929 | <TestCase.assertWarnsRegex>` | and the message matches `re` | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000930 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000931
Georg Brandl7f01a132009-09-16 15:58:14 +0000932 .. method:: assertRaises(exception, callable, *args, **kwds)
Georg Brandl7f01a132009-09-16 15:58:14 +0000933 assertRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000934
935 Test that an exception is raised when *callable* is called with any
936 positional or keyword arguments that are also passed to
937 :meth:`assertRaises`. The test passes if *exception* is raised, is an
938 error if another exception is raised, or fails if no exception is raised.
939 To catch any of a group of exceptions, a tuple containing the exception
940 classes may be passed as *exception*.
941
Georg Brandl7f01a132009-09-16 15:58:14 +0000942 If only the *exception* argument is given, returns a context manager so
943 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000944
Michael Foord41531f22010-02-05 21:13:40 +0000945 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000946 do_something()
947
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000948 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000949 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000950 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000951
Georg Brandl8a1caa22010-07-29 16:01:11 +0000952 with self.assertRaises(SomeException) as cm:
953 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000954
Georg Brandl8a1caa22010-07-29 16:01:11 +0000955 the_exception = cm.exception
956 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000957
Ezio Melotti49008232010-02-08 21:57:48 +0000958 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000959 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000960
Ezio Melotti49008232010-02-08 21:57:48 +0000961 .. versionchanged:: 3.2
962 Added the :attr:`exception` attribute.
963
Benjamin Peterson52baa292009-03-24 00:56:30 +0000964
Ezio Melottied3a7d22010-12-01 02:32:32 +0000965 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
966 assertRaisesRegex(exception, regex)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000967
Ezio Melottied3a7d22010-12-01 02:32:32 +0000968 Like :meth:`assertRaises` but also tests that *regex* matches
969 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000970 a regular expression object or a string containing a regular expression
971 suitable for use by :func:`re.search`. Examples::
972
Ezio Melottied3a7d22010-12-01 02:32:32 +0000973 self.assertRaisesRegex(ValueError, 'invalid literal for.*XYZ$',
974 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000975
976 or::
977
Ezio Melottied3a7d22010-12-01 02:32:32 +0000978 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000979 int('XYZ')
980
Georg Brandl419e3de2010-12-01 15:44:25 +0000981 .. versionadded:: 3.1
982 under the name ``assertRaisesRegexp``.
Ezio Melottied3a7d22010-12-01 02:32:32 +0000983 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +0000984 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000985
986
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000987 .. method:: assertWarns(warning, callable, *args, **kwds)
988 assertWarns(warning)
989
990 Test that a warning is triggered when *callable* is called with any
991 positional or keyword arguments that are also passed to
992 :meth:`assertWarns`. The test passes if *warning* is triggered and
993 fails if it isn't. Also, any unexpected exception is an error.
994 To catch any of a group of warnings, a tuple containing the warning
995 classes may be passed as *warnings*.
996
997 If only the *warning* argument is given, returns a context manager so
998 that the code under test can be written inline rather than as a function::
999
1000 with self.assertWarns(SomeWarning):
1001 do_something()
1002
1003 The context manager will store the caught warning object in its
1004 :attr:`warning` attribute, and the source line which triggered the
1005 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1006 This can be useful if the intention is to perform additional checks
1007 on the exception raised::
1008
1009 with self.assertWarns(SomeWarning) as cm:
1010 do_something()
1011
1012 self.assertIn('myfile.py', cm.filename)
1013 self.assertEqual(320, cm.lineno)
1014
1015 This method works regardless of the warning filters in place when it
1016 is called.
1017
1018 .. versionadded:: 3.2
1019
1020
Ezio Melottied3a7d22010-12-01 02:32:32 +00001021 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
1022 assertWarnsRegex(warning, regex)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001023
Ezio Melottied3a7d22010-12-01 02:32:32 +00001024 Like :meth:`assertWarns` but also tests that *regex* matches on the
1025 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001026 object or a string containing a regular expression suitable for use
1027 by :func:`re.search`. Example::
1028
Ezio Melottied3a7d22010-12-01 02:32:32 +00001029 self.assertWarnsRegex(DeprecationWarning,
1030 r'legacy_function\(\) is deprecated',
1031 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001032
1033 or::
1034
Ezio Melottied3a7d22010-12-01 02:32:32 +00001035 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001036 frobnicate('/etc/passwd')
1037
1038 .. versionadded:: 3.2
1039
1040
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001041
Ezio Melotti4370b302010-11-03 20:39:14 +00001042 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001043
Ezio Melotti4370b302010-11-03 20:39:14 +00001044 +---------------------------------------+--------------------------------+--------------+
1045 | Method | Checks that | New in |
1046 +=======================================+================================+==============+
1047 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1048 | <TestCase.assertAlmostEqual>` | | |
1049 +---------------------------------------+--------------------------------+--------------+
1050 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1051 | <TestCase.assertNotAlmostEqual>` | | |
1052 +---------------------------------------+--------------------------------+--------------+
1053 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1054 | <TestCase.assertGreater>` | | |
1055 +---------------------------------------+--------------------------------+--------------+
1056 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1057 | <TestCase.assertGreaterEqual>` | | |
1058 +---------------------------------------+--------------------------------+--------------+
1059 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1060 | <TestCase.assertLess>` | | |
1061 +---------------------------------------+--------------------------------+--------------+
1062 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1063 | <TestCase.assertLessEqual>` | | |
1064 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001065 | :meth:`assertRegex(s, re) | ``regex.search(s)`` | 3.1 |
1066 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001067 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001068 | :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 |
1069 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001070 +---------------------------------------+--------------------------------+--------------+
1071 | :meth:`assertDictContainsSubset(a, b) | all the key/value pairs | 3.1 |
1072 | <TestCase.assertDictContainsSubset>` | in `a` exist in `b` | |
1073 +---------------------------------------+--------------------------------+--------------+
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001074 | :meth:`assertCountEqual(a, b) | `a` and `b` have the same | 3.2 |
1075 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001076 | | regardless of their order | |
1077 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001078
1079
Ezio Melotti4370b302010-11-03 20:39:14 +00001080 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001081 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001082
Ezio Melotti4841fd62010-11-05 15:43:40 +00001083 Test that *first* and *second* are approximately (or not approximately)
1084 equal by computing the difference, rounding to the given number of
1085 decimal *places* (default 7), and comparing to zero. Note that these
1086 methods round the values to the given number of *decimal places* (i.e.
1087 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001088
Ezio Melotti4370b302010-11-03 20:39:14 +00001089 If *delta* is supplied instead of *places* then the difference
Ezio Melotti4841fd62010-11-05 15:43:40 +00001090 between *first* and *second* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001091
Ezio Melotti4370b302010-11-03 20:39:14 +00001092 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001093
Ezio Melotti4370b302010-11-03 20:39:14 +00001094 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001095 :meth:`assertAlmostEqual` automatically considers almost equal objects
1096 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1097 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001098
Ezio Melotti4370b302010-11-03 20:39:14 +00001099
Ezio Melotti4370b302010-11-03 20:39:14 +00001100 .. method:: assertGreater(first, second, msg=None)
1101 assertGreaterEqual(first, second, msg=None)
1102 assertLess(first, second, msg=None)
1103 assertLessEqual(first, second, msg=None)
1104
1105 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001106 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001107
1108 >>> self.assertGreaterEqual(3, 4)
1109 AssertionError: "3" unexpectedly not greater than or equal to "4"
1110
1111 .. versionadded:: 3.1
1112
1113
Ezio Melottied3a7d22010-12-01 02:32:32 +00001114 .. method:: assertRegex(text, regex, msg=None)
1115 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001116
Ezio Melottied3a7d22010-12-01 02:32:32 +00001117 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001118 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001119 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001120 may be a regular expression object or a string containing a regular
1121 expression suitable for use by :func:`re.search`.
1122
Georg Brandl419e3de2010-12-01 15:44:25 +00001123 .. versionadded:: 3.1
1124 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001125 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001126 The method ``assertRegexpMatches()`` has been renamed to
1127 :meth:`.assertRegex`.
1128 .. versionadded:: 3.2
1129 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001130
1131
1132 .. method:: assertDictContainsSubset(expected, actual, msg=None)
1133
1134 Tests whether the key/value pairs in dictionary *actual* are a
1135 superset of those in *expected*. If not, an error message listing
1136 the missing keys and mismatched values is generated.
1137
Ezio Melotti4370b302010-11-03 20:39:14 +00001138 .. versionadded:: 3.1
1139
1140
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001141 .. method:: assertCountEqual(expected, actual, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001142
1143 Test that sequence *expected* contains the same elements as *actual*,
1144 regardless of their order. When they don't, an error message listing the
1145 differences between the sequences will be generated.
1146
1147 Duplicate elements are *not* ignored when comparing *actual* and
1148 *expected*. It verifies if each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001149 sequences. Equivalent to:
1150 ``assertEqual(Counter(iter(expected)), Counter(iter(actual)))``
1151 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001152
Ezio Melotti4370b302010-11-03 20:39:14 +00001153 .. versionadded:: 3.2
1154
Ezio Melotti4370b302010-11-03 20:39:14 +00001155 .. method:: assertSameElements(actual, expected, msg=None)
1156
1157 Test that sequence *expected* contains the same elements as *actual*,
1158 regardless of their order. When they don't, an error message listing
1159 the differences between the sequences will be generated.
1160
1161 Duplicate elements are ignored when comparing *actual* and *expected*.
1162 It is the equivalent of ``assertEqual(set(expected), set(actual))``
1163 but it works with sequences of unhashable objects as well. Because
1164 duplicates are ignored, this method has been deprecated in favour of
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001165 :meth:`assertCountEqual`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001166
Ezio Melotti4370b302010-11-03 20:39:14 +00001167 .. versionadded:: 3.1
1168 .. deprecated:: 3.2
1169
1170
Ezio Melotti22170ed2010-11-20 09:57:27 +00001171 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001172
Ezio Melotti22170ed2010-11-20 09:57:27 +00001173 The :meth:`assertEqual` method dispatches the equality check for objects of
1174 the same type to different type-specific methods. These methods are already
1175 implemented for most of the built-in types, but it's also possible to
1176 register new methods using :meth:`addTypeEqualityFunc`:
1177
1178 .. method:: addTypeEqualityFunc(typeobj, function)
1179
1180 Registers a type-specific method called by :meth:`assertEqual` to check
1181 if two objects of exactly the same *typeobj* (not subclasses) compare
1182 equal. *function* must take two positional arguments and a third msg=None
1183 keyword argument just as :meth:`assertEqual` does. It must raise
1184 :data:`self.failureException(msg) <failureException>` when inequality
1185 between the first two parameters is detected -- possibly providing useful
1186 information and explaining the inequalities in details in the error
1187 message.
1188
1189 .. versionadded:: 3.1
1190
1191 The list of type-specific methods automatically used by
1192 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1193 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001194
1195 +-----------------------------------------+-----------------------------+--------------+
1196 | Method | Used to compare | New in |
1197 +=========================================+=============================+==============+
1198 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1199 | <TestCase.assertMultiLineEqual>` | | |
1200 +-----------------------------------------+-----------------------------+--------------+
1201 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1202 | <TestCase.assertSequenceEqual>` | | |
1203 +-----------------------------------------+-----------------------------+--------------+
1204 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1205 | <TestCase.assertListEqual>` | | |
1206 +-----------------------------------------+-----------------------------+--------------+
1207 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1208 | <TestCase.assertTupleEqual>` | | |
1209 +-----------------------------------------+-----------------------------+--------------+
1210 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1211 | <TestCase.assertSetEqual>` | | |
1212 +-----------------------------------------+-----------------------------+--------------+
1213 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1214 | <TestCase.assertDictEqual>` | | |
1215 +-----------------------------------------+-----------------------------+--------------+
1216
1217
1218
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001219 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001220
1221 Test that the multiline string *first* is equal to the string *second*.
1222 When not equal a diff of the two strings highlighting the differences
1223 will be included in the error message. This method is used by default
1224 when comparing strings with :meth:`assertEqual`.
1225
Ezio Melotti4370b302010-11-03 20:39:14 +00001226 .. versionadded:: 3.1
1227
1228
1229 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
1230
1231 Tests that two sequences are equal. If a *seq_type* is supplied, both
1232 *seq1* and *seq2* must be instances of *seq_type* or a failure will
1233 be raised. If the sequences are different an error message is
1234 constructed that shows the difference between the two.
1235
Ezio Melotti22170ed2010-11-20 09:57:27 +00001236 This method is not called directly by :meth:`assertEqual`, but
1237 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001238 :meth:`assertTupleEqual`.
1239
1240 .. versionadded:: 3.1
1241
1242
1243 .. method:: assertListEqual(list1, list2, msg=None)
1244 assertTupleEqual(tuple1, tuple2, msg=None)
1245
1246 Tests that two lists or tuples are equal. If not an error message is
1247 constructed that shows only the differences between the two. An error
1248 is also raised if either of the parameters are of the wrong type.
1249 These methods are used by default when comparing lists or tuples with
1250 :meth:`assertEqual`.
1251
Ezio Melotti4370b302010-11-03 20:39:14 +00001252 .. versionadded:: 3.1
1253
1254
1255 .. method:: assertSetEqual(set1, set2, msg=None)
1256
1257 Tests that two sets are equal. If not, an error message is constructed
1258 that lists the differences between the sets. This method is used by
1259 default when comparing sets or frozensets with :meth:`assertEqual`.
1260
1261 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
1262 method.
1263
Ezio Melotti4370b302010-11-03 20:39:14 +00001264 .. versionadded:: 3.1
1265
1266
1267 .. method:: assertDictEqual(expected, actual, msg=None)
1268
1269 Test that two dictionaries are equal. If not, an error message is
1270 constructed that shows the differences in the dictionaries. This
1271 method will be used by default to compare dictionaries in
1272 calls to :meth:`assertEqual`.
1273
Ezio Melotti4370b302010-11-03 20:39:14 +00001274 .. versionadded:: 3.1
1275
1276
1277
Ezio Melotti22170ed2010-11-20 09:57:27 +00001278 .. _other-methods-and-attrs:
1279
Ezio Melotti4370b302010-11-03 20:39:14 +00001280 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001281
Benjamin Peterson52baa292009-03-24 00:56:30 +00001282
Georg Brandl7f01a132009-09-16 15:58:14 +00001283 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001284
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001285 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001286 the error message.
1287
1288
1289 .. attribute:: failureException
1290
1291 This class attribute gives the exception raised by the test method. If a
1292 test framework needs to use a specialized exception, possibly to carry
1293 additional information, it must subclass this exception in order to "play
1294 fair" with the framework. The initial value of this attribute is
1295 :exc:`AssertionError`.
1296
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001297
1298 .. attribute:: longMessage
1299
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001300 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001301 :ref:`assert methods <assert-methods>` will be appended to the end of the
1302 normal failure message. The normal messages contain useful information
1303 about the objects involved, for example the message from assertEqual
1304 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001305 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001306 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001307
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001308 This attribute defaults to ``False``, meaning that a custom message passed
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001309 to an assert method will silence the normal message.
1310
1311 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001312 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001313
Raymond Hettinger35a88362009-04-09 00:08:24 +00001314 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001315
1316
Michael Foord98b3e762010-06-05 21:59:55 +00001317 .. attribute:: maxDiff
1318
1319 This attribute controls the maximum length of diffs output by assert
1320 methods that report diffs on failure. It defaults to 80*8 characters.
1321 Assert methods affected by this attribute are
1322 :meth:`assertSequenceEqual` (including all the sequence comparison
1323 methods that delegate to it), :meth:`assertDictEqual` and
1324 :meth:`assertMultiLineEqual`.
1325
1326 Setting ``maxDiff`` to None means that there is no maximum length of
1327 diffs.
1328
1329 .. versionadded:: 3.2
1330
1331
Benjamin Peterson52baa292009-03-24 00:56:30 +00001332 Testing frameworks can use the following methods to collect information on
1333 the test:
1334
1335
1336 .. method:: countTestCases()
1337
1338 Return the number of tests represented by this test object. For
1339 :class:`TestCase` instances, this will always be ``1``.
1340
1341
1342 .. method:: defaultTestResult()
1343
1344 Return an instance of the test result class that should be used for this
1345 test case class (if no other result instance is provided to the
1346 :meth:`run` method).
1347
1348 For :class:`TestCase` instances, this will always be an instance of
1349 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1350 as necessary.
1351
1352
1353 .. method:: id()
1354
1355 Return a string identifying the specific test case. This is usually the
1356 full name of the test method, including the module and class name.
1357
1358
1359 .. method:: shortDescription()
1360
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001361 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001362 has been provided. The default implementation of this method
1363 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001364 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001365
Georg Brandl419e3de2010-12-01 15:44:25 +00001366 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001367 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001368 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001369 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001370 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001371
Georg Brandl116aa622007-08-15 14:28:22 +00001372
Georg Brandl7f01a132009-09-16 15:58:14 +00001373 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001374
1375 Add a function to be called after :meth:`tearDown` to cleanup resources
1376 used during the test. Functions will be called in reverse order to the
1377 order they are added (LIFO). They are called with any arguments and
1378 keyword arguments passed into :meth:`addCleanup` when they are
1379 added.
1380
1381 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1382 then any cleanup functions added will still be called.
1383
Georg Brandl853947a2010-01-31 18:53:23 +00001384 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001385
1386
1387 .. method:: doCleanups()
1388
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001389 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001390 after :meth:`setUp` if :meth:`setUp` raises an exception.
1391
1392 It is responsible for calling all the cleanup functions added by
1393 :meth:`addCleanup`. If you need cleanup functions to be called
1394 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1395 yourself.
1396
1397 :meth:`doCleanups` pops methods off the stack of cleanup
1398 functions one at a time, so it can be called at any time.
1399
Georg Brandl853947a2010-01-31 18:53:23 +00001400 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001401
1402
Georg Brandl7f01a132009-09-16 15:58:14 +00001403.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001404
1405 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001406 allows the test runner to drive the test, but does not provide the methods
1407 which test code can use to check and report errors. This is used to create
1408 test cases using legacy test code, allowing it to be integrated into a
1409 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001410
1411
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001412.. _deprecated-aliases:
1413
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001414Deprecated aliases
1415##################
1416
1417For historical reasons, some of the :class:`TestCase` methods had one or more
1418aliases that are now deprecated. The following table lists the correct names
1419along with their deprecated aliases:
1420
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001421 ============================== ====================== ======================
1422 Method Name Deprecated alias Deprecated alias
1423 ============================== ====================== ======================
1424 :meth:`.assertEqual` failUnlessEqual assertEquals
1425 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1426 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001427 :meth:`.assertFalse` failIf
1428 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001429 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1430 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001431 :meth:`.assertRegex` assertRegexpMatches
1432 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001433 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001434
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001435 .. deprecated-removed:: 3.1 3.3
1436 the fail* aliases listed in the second column.
1437 .. deprecated:: 3.2
1438 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001439 .. deprecated:: 3.2
1440 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1441 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001442
1443
Benjamin Peterson52baa292009-03-24 00:56:30 +00001444.. _testsuite-objects:
1445
Benjamin Peterson52baa292009-03-24 00:56:30 +00001446Grouping tests
1447~~~~~~~~~~~~~~
1448
Georg Brandl7f01a132009-09-16 15:58:14 +00001449.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001450
1451 This class represents an aggregation of individual tests cases and test suites.
1452 The class presents the interface needed by the test runner to allow it to be run
1453 as any other test case. Running a :class:`TestSuite` instance is the same as
1454 iterating over the suite, running each test individually.
1455
1456 If *tests* is given, it must be an iterable of individual test cases or other
1457 test suites that will be used to build the suite initially. Additional methods
1458 are provided to add test cases and suites to the collection later on.
1459
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001460 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1461 they do not actually implement a test. Instead, they are used to aggregate
1462 tests into groups of tests that should be run together. Some additional
1463 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001464
1465
1466 .. method:: TestSuite.addTest(test)
1467
1468 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1469
1470
1471 .. method:: TestSuite.addTests(tests)
1472
1473 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1474 instances to this test suite.
1475
Benjamin Petersond2397752009-06-27 23:45:02 +00001476 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1477 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001478
1479 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1480
1481
1482 .. method:: run(result)
1483
1484 Run the tests associated with this suite, collecting the result into the
1485 test result object passed as *result*. Note that unlike
1486 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1487 be passed in.
1488
1489
1490 .. method:: debug()
1491
1492 Run the tests associated with this suite without collecting the
1493 result. This allows exceptions raised by the test to be propagated to the
1494 caller and can be used to support running tests under a debugger.
1495
1496
1497 .. method:: countTestCases()
1498
1499 Return the number of tests represented by this test object, including all
1500 individual tests and sub-suites.
1501
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001502
1503 .. method:: __iter__()
1504
1505 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1506 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1507 that this method maybe called several times on a single suite
1508 (for example when counting tests or comparing for equality)
1509 so the tests returned must be the same for repeated iterations.
1510
Georg Brandl853947a2010-01-31 18:53:23 +00001511 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001512 In earlier versions the :class:`TestSuite` accessed tests directly rather
1513 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1514 for providing tests.
1515
Benjamin Peterson52baa292009-03-24 00:56:30 +00001516 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1517 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1518
1519
Benjamin Peterson52baa292009-03-24 00:56:30 +00001520Loading and running tests
1521~~~~~~~~~~~~~~~~~~~~~~~~~
1522
Georg Brandl116aa622007-08-15 14:28:22 +00001523.. class:: TestLoader()
1524
Benjamin Peterson52baa292009-03-24 00:56:30 +00001525 The :class:`TestLoader` class is used to create test suites from classes and
1526 modules. Normally, there is no need to create an instance of this class; the
1527 :mod:`unittest` module provides an instance that can be shared as
1528 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1529 customization of some configurable properties.
1530
1531 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001532
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001533
Benjamin Peterson52baa292009-03-24 00:56:30 +00001534 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001535
Benjamin Peterson52baa292009-03-24 00:56:30 +00001536 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1537 :class:`testCaseClass`.
1538
1539
1540 .. method:: loadTestsFromModule(module)
1541
1542 Return a suite of all tests cases contained in the given module. This
1543 method searches *module* for classes derived from :class:`TestCase` and
1544 creates an instance of the class for each test method defined for the
1545 class.
1546
Georg Brandle720c0a2009-04-27 16:20:50 +00001547 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001548
1549 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1550 convenient in sharing fixtures and helper functions, defining test
1551 methods on base classes that are not intended to be instantiated
1552 directly does not play well with this method. Doing so, however, can
1553 be useful when the fixtures are different and defined in subclasses.
1554
Benjamin Petersond2397752009-06-27 23:45:02 +00001555 If a module provides a ``load_tests`` function it will be called to
1556 load the tests. This allows modules to customize test loading.
1557 This is the `load_tests protocol`_.
1558
Georg Brandl853947a2010-01-31 18:53:23 +00001559 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001560 Support for ``load_tests`` added.
1561
Benjamin Peterson52baa292009-03-24 00:56:30 +00001562
Georg Brandl7f01a132009-09-16 15:58:14 +00001563 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001564
1565 Return a suite of all tests cases given a string specifier.
1566
1567 The specifier *name* is a "dotted name" that may resolve either to a
1568 module, a test case class, a test method within a test case class, a
1569 :class:`TestSuite` instance, or a callable object which returns a
1570 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1571 applied in the order listed here; that is, a method on a possible test
1572 case class will be picked up as "a test method within a test case class",
1573 rather than "a callable object".
1574
1575 For example, if you have a module :mod:`SampleTests` containing a
1576 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1577 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001578 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1579 return a suite which will run all three test methods. Using the specifier
1580 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1581 suite which will run only the :meth:`test_two` test method. The specifier
1582 can refer to modules and packages which have not been imported; they will
1583 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001584
1585 The method optionally resolves *name* relative to the given *module*.
1586
1587
Georg Brandl7f01a132009-09-16 15:58:14 +00001588 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001589
1590 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1591 than a single name. The return value is a test suite which supports all
1592 the tests defined for each name.
1593
1594
1595 .. method:: getTestCaseNames(testCaseClass)
1596
1597 Return a sorted sequence of method names found within *testCaseClass*;
1598 this should be a subclass of :class:`TestCase`.
1599
Benjamin Petersond2397752009-06-27 23:45:02 +00001600
1601 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1602
1603 Find and return all test modules from the specified start directory,
1604 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001605 *pattern* will be loaded. (Using shell style pattern matching.) Only
1606 module names that are importable (i.e. are valid Python identifiers) will
1607 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001608
1609 All test modules must be importable from the top level of the project. If
1610 the start directory is not the top level directory then the top level
1611 directory must be specified separately.
1612
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001613 If importing a module fails, for example due to a syntax error, then this
1614 will be recorded as a single error and discovery will continue.
1615
Benjamin Petersond2397752009-06-27 23:45:02 +00001616 If a test package name (directory with :file:`__init__.py`) matches the
1617 pattern then the package will be checked for a ``load_tests``
1618 function. If this exists then it will be called with *loader*, *tests*,
1619 *pattern*.
1620
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001621 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001622 ``load_tests`` is responsible for loading all tests in the package.
1623
1624 The pattern is deliberately not stored as a loader attribute so that
1625 packages can continue discovery themselves. *top_level_dir* is stored so
1626 ``load_tests`` does not need to pass this argument in to
1627 ``loader.discover()``.
1628
Benjamin Petersonb48af542010-04-11 20:43:16 +00001629 *start_dir* can be a dotted module name as well as a directory.
1630
Georg Brandl853947a2010-01-31 18:53:23 +00001631 .. versionadded:: 3.2
1632
Benjamin Petersond2397752009-06-27 23:45:02 +00001633
Benjamin Peterson52baa292009-03-24 00:56:30 +00001634 The following attributes of a :class:`TestLoader` can be configured either by
1635 subclassing or assignment on an instance:
1636
1637
1638 .. attribute:: testMethodPrefix
1639
1640 String giving the prefix of method names which will be interpreted as test
1641 methods. The default value is ``'test'``.
1642
1643 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1644 methods.
1645
1646
1647 .. attribute:: sortTestMethodsUsing
1648
1649 Function to be used to compare method names when sorting them in
1650 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1651
1652
1653 .. attribute:: suiteClass
1654
1655 Callable object that constructs a test suite from a list of tests. No
1656 methods on the resulting object are needed. The default value is the
1657 :class:`TestSuite` class.
1658
1659 This affects all the :meth:`loadTestsFrom\*` methods.
1660
1661
Benjamin Peterson52baa292009-03-24 00:56:30 +00001662.. class:: TestResult
1663
1664 This class is used to compile information about which tests have succeeded
1665 and which have failed.
1666
1667 A :class:`TestResult` object stores the results of a set of tests. The
1668 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1669 properly recorded; test authors do not need to worry about recording the
1670 outcome of tests.
1671
1672 Testing frameworks built on top of :mod:`unittest` may want access to the
1673 :class:`TestResult` object generated by running a set of tests for reporting
1674 purposes; a :class:`TestResult` instance is returned by the
1675 :meth:`TestRunner.run` method for this purpose.
1676
1677 :class:`TestResult` instances have the following attributes that will be of
1678 interest when inspecting the results of running a set of tests:
1679
1680
1681 .. attribute:: errors
1682
1683 A list containing 2-tuples of :class:`TestCase` instances and strings
1684 holding formatted tracebacks. Each tuple represents a test which raised an
1685 unexpected exception.
1686
Benjamin Peterson52baa292009-03-24 00:56:30 +00001687 .. attribute:: failures
1688
1689 A list containing 2-tuples of :class:`TestCase` instances and strings
1690 holding formatted tracebacks. Each tuple represents a test where a failure
1691 was explicitly signalled using the :meth:`TestCase.fail\*` or
1692 :meth:`TestCase.assert\*` methods.
1693
Benjamin Peterson52baa292009-03-24 00:56:30 +00001694 .. attribute:: skipped
1695
1696 A list containing 2-tuples of :class:`TestCase` instances and strings
1697 holding the reason for skipping the test.
1698
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001699 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001700
1701 .. attribute:: expectedFailures
1702
Georg Brandl6faee4e2010-09-21 14:48:28 +00001703 A list containing 2-tuples of :class:`TestCase` instances and strings
1704 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001705 of the test case.
1706
1707 .. attribute:: unexpectedSuccesses
1708
1709 A list containing :class:`TestCase` instances that were marked as expected
1710 failures, but succeeded.
1711
1712 .. attribute:: shouldStop
1713
1714 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1715
1716
1717 .. attribute:: testsRun
1718
1719 The total number of tests run so far.
1720
1721
Benjamin Petersonb48af542010-04-11 20:43:16 +00001722
1723 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1724 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1725 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1726 fails or errors. Any output is also attached to the failure / error message.
1727
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001728 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001729
1730
1731 .. attribute:: failfast
1732
1733 If set to true :meth:`stop` will be called on the first failure or error,
1734 halting the test run.
1735
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001736 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001737
1738
Benjamin Peterson52baa292009-03-24 00:56:30 +00001739 .. method:: wasSuccessful()
1740
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001741 Return ``True`` if all tests run so far have passed, otherwise returns
1742 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001743
1744
1745 .. method:: stop()
1746
1747 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001748 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001749 :class:`TestRunner` objects should respect this flag and return without
1750 running any additional tests.
1751
1752 For example, this feature is used by the :class:`TextTestRunner` class to
1753 stop the test framework when the user signals an interrupt from the
1754 keyboard. Interactive tools which provide :class:`TestRunner`
1755 implementations can use this in a similar manner.
1756
1757 The following methods of the :class:`TestResult` class are used to maintain
1758 the internal data structures, and may be extended in subclasses to support
1759 additional reporting requirements. This is particularly useful in building
1760 tools which support interactive reporting while tests are being run.
1761
1762
1763 .. method:: startTest(test)
1764
1765 Called when the test case *test* is about to be run.
1766
Benjamin Peterson52baa292009-03-24 00:56:30 +00001767 .. method:: stopTest(test)
1768
1769 Called after the test case *test* has been executed, regardless of the
1770 outcome.
1771
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001772 .. method:: startTestRun(test)
1773
1774 Called once before any tests are executed.
1775
Georg Brandl853947a2010-01-31 18:53:23 +00001776 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001777
1778
1779 .. method:: stopTestRun(test)
1780
Ezio Melotti176d6c42010-01-27 20:58:07 +00001781 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001782
Georg Brandl853947a2010-01-31 18:53:23 +00001783 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001784
1785
Benjamin Peterson52baa292009-03-24 00:56:30 +00001786 .. method:: addError(test, err)
1787
1788 Called when the test case *test* raises an unexpected exception *err* is a
1789 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1790 traceback)``.
1791
1792 The default implementation appends a tuple ``(test, formatted_err)`` to
1793 the instance's :attr:`errors` attribute, where *formatted_err* is a
1794 formatted traceback derived from *err*.
1795
1796
1797 .. method:: addFailure(test, err)
1798
Benjamin Petersond2397752009-06-27 23:45:02 +00001799 Called when the test case *test* signals a failure. *err* is a tuple of
1800 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001801
1802 The default implementation appends a tuple ``(test, formatted_err)`` to
1803 the instance's :attr:`failures` attribute, where *formatted_err* is a
1804 formatted traceback derived from *err*.
1805
1806
1807 .. method:: addSuccess(test)
1808
1809 Called when the test case *test* succeeds.
1810
1811 The default implementation does nothing.
1812
1813
1814 .. method:: addSkip(test, reason)
1815
1816 Called when the test case *test* is skipped. *reason* is the reason the
1817 test gave for skipping.
1818
1819 The default implementation appends a tuple ``(test, reason)`` to the
1820 instance's :attr:`skipped` attribute.
1821
1822
1823 .. method:: addExpectedFailure(test, err)
1824
1825 Called when the test case *test* fails, but was marked with the
1826 :func:`expectedFailure` decorator.
1827
1828 The default implementation appends a tuple ``(test, formatted_err)`` to
1829 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1830 is a formatted traceback derived from *err*.
1831
1832
1833 .. method:: addUnexpectedSuccess(test)
1834
1835 Called when the test case *test* was marked with the
1836 :func:`expectedFailure` decorator, but succeeded.
1837
1838 The default implementation appends the test to the instance's
1839 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001840
Georg Brandl67b21b72010-08-17 15:07:14 +00001841
Michael Foord34c94622010-02-10 15:51:42 +00001842.. class:: TextTestResult(stream, descriptions, verbosity)
1843
Georg Brandl67b21b72010-08-17 15:07:14 +00001844 A concrete implementation of :class:`TestResult` used by the
1845 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001846
Georg Brandl67b21b72010-08-17 15:07:14 +00001847 .. versionadded:: 3.2
1848 This class was previously named ``_TextTestResult``. The old name still
1849 exists as an alias but is deprecated.
1850
Georg Brandl116aa622007-08-15 14:28:22 +00001851
1852.. data:: defaultTestLoader
1853
1854 Instance of the :class:`TestLoader` class intended to be shared. If no
1855 customization of the :class:`TestLoader` is needed, this instance can be used
1856 instead of repeatedly creating new instances.
1857
1858
Ezio Melotti60901872010-12-01 00:56:10 +00001859.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001860
1861 A basic test runner implementation which prints results on standard error. It
1862 has a few configurable parameters, but is essentially very simple. Graphical
1863 applications which run test suites should provide alternate implementations.
1864
Ezio Melotti60901872010-12-01 00:56:10 +00001865 By default this runner shows :exc:`DeprecationWarning`,
1866 :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` even if they are
1867 :ref:`ignored by default <warning-ignored>`. Deprecation warnings caused by
1868 :ref:`deprecated unittest methods <deprecated-aliases>` are also
1869 special-cased and, when the warning filters are ``'default'`` or ``'always'``,
1870 they will appear only once per-module, in order to avoid too many warning
1871 messages. This behavior can be overridden using the :option`-Wd` or
1872 :option:`-Wa` options and leaving *warnings* to ``None``.
1873
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001874 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001875
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001876 This method returns the instance of ``TestResult`` used by :meth:`run`.
1877 It is not intended to be called directly, but can be overridden in
1878 subclasses to provide a custom ``TestResult``.
1879
Michael Foord34c94622010-02-10 15:51:42 +00001880 ``_makeResult()`` instantiates the class or callable passed in the
1881 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001882 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001883 The result class is instantiated with the following arguments::
1884
1885 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001886
Georg Brandl419e3de2010-12-01 15:44:25 +00001887 .. versionchanged:: 3.2
1888 Added the ``warnings`` argument.
Ezio Melotti60901872010-12-01 00:56:10 +00001889
Georg Brandl419e3de2010-12-01 15:44:25 +00001890.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
1891 testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1, \
1892 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001893
1894 A command-line program that runs a set of tests; this is primarily for making
1895 test modules conveniently executable. The simplest use for this function is to
1896 include the following line at the end of a test script::
1897
1898 if __name__ == '__main__':
1899 unittest.main()
1900
Benjamin Petersond2397752009-06-27 23:45:02 +00001901 You can run tests with more detailed information by passing in the verbosity
1902 argument::
1903
1904 if __name__ == '__main__':
1905 unittest.main(verbosity=2)
1906
Georg Brandl116aa622007-08-15 14:28:22 +00001907 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001908 created instance of it. By default ``main`` calls :func:`sys.exit` with
1909 an exit code indicating success or failure of the tests run.
1910
1911 ``main`` supports being used from the interactive interpreter by passing in the
1912 argument ``exit=False``. This displays the result on standard output without
1913 calling :func:`sys.exit`::
1914
1915 >>> from unittest import main
1916 >>> main(module='test_module', exit=False)
1917
Benjamin Petersonb48af542010-04-11 20:43:16 +00001918 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00001919 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001920
Ezio Melotti60901872010-12-01 00:56:10 +00001921 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
1922 that should be used while running the tests. If it's not specified, it will
1923 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
1924 otherwise it will be set to ``'default'``.
1925
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001926 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1927 This stores the result of the tests run as the ``result`` attribute.
1928
Georg Brandl853947a2010-01-31 18:53:23 +00001929 .. versionchanged:: 3.2
Ezio Melotti60901872010-12-01 00:56:10 +00001930 The ``exit``, ``verbosity``, ``failfast``, ``catchbreak``, ``buffer``,
1931 and ``warnings`` parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001932
1933
1934load_tests Protocol
1935###################
1936
Georg Brandl853947a2010-01-31 18:53:23 +00001937.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001938
Benjamin Petersond2397752009-06-27 23:45:02 +00001939Modules or packages can customize how tests are loaded from them during normal
1940test runs or test discovery by implementing a function called ``load_tests``.
1941
1942If a test module defines ``load_tests`` it will be called by
1943:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1944
1945 load_tests(loader, standard_tests, None)
1946
1947It should return a :class:`TestSuite`.
1948
1949*loader* is the instance of :class:`TestLoader` doing the loading.
1950*standard_tests* are the tests that would be loaded by default from the
1951module. It is common for test modules to only want to add or remove tests
1952from the standard set of tests.
1953The third argument is used when loading packages as part of test discovery.
1954
1955A typical ``load_tests`` function that loads tests from a specific set of
1956:class:`TestCase` classes may look like::
1957
1958 test_cases = (TestCase1, TestCase2, TestCase3)
1959
1960 def load_tests(loader, tests, pattern):
1961 suite = TestSuite()
1962 for test_class in test_cases:
1963 tests = loader.loadTestsFromTestCase(test_class)
1964 suite.addTests(tests)
1965 return suite
1966
1967If discovery is started, either from the command line or by calling
1968:meth:`TestLoader.discover`, with a pattern that matches a package
1969name then the package :file:`__init__.py` will be checked for ``load_tests``.
1970
1971.. note::
1972
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001973 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00001974 that start with 'test' but *won't* match any test directories.
1975
1976 A pattern like 'test*' will match test packages as well as
1977 modules.
1978
1979If the package :file:`__init__.py` defines ``load_tests`` then it will be
1980called and discovery not continued into the package. ``load_tests``
1981is called with the following arguments::
1982
1983 load_tests(loader, standard_tests, pattern)
1984
1985This should return a :class:`TestSuite` representing all the tests
1986from the package. (``standard_tests`` will only contain tests
1987collected from :file:`__init__.py`.)
1988
1989Because the pattern is passed into ``load_tests`` the package is free to
1990continue (and potentially modify) test discovery. A 'do nothing'
1991``load_tests`` function for a test package would look like::
1992
1993 def load_tests(loader, standard_tests, pattern):
1994 # top level directory cached on loader instance
1995 this_dir = os.path.dirname(__file__)
1996 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1997 standard_tests.addTests(package_tests)
1998 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00001999
2000
2001Class and Module Fixtures
2002-------------------------
2003
2004Class and module level fixtures are implemented in :class:`TestSuite`. When
2005the test suite encounters a test from a new class then :meth:`tearDownClass`
2006from the previous class (if there is one) is called, followed by
2007:meth:`setUpClass` from the new class.
2008
2009Similarly if a test is from a different module from the previous test then
2010``tearDownModule`` from the previous module is run, followed by
2011``setUpModule`` from the new module.
2012
2013After all the tests have run the final ``tearDownClass`` and
2014``tearDownModule`` are run.
2015
2016Note that shared fixtures do not play well with [potential] features like test
2017parallelization and they break test isolation. They should be used with care.
2018
2019The default ordering of tests created by the unittest test loaders is to group
2020all tests from the same modules and classes together. This will lead to
2021``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2022module. If you randomize the order, so that tests from different modules and
2023classes are adjacent to each other, then these shared fixture functions may be
2024called multiple times in a single test run.
2025
2026Shared fixtures are not intended to work with suites with non-standard
2027ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2028support shared fixtures.
2029
2030If there are any exceptions raised during one of the shared fixture functions
2031the test is reported as an error. Because there is no corresponding test
2032instance an ``_ErrorHolder`` object (that has the same interface as a
2033:class:`TestCase`) is created to represent the error. If you are just using
2034the standard unittest test runner then this detail doesn't matter, but if you
2035are a framework author it may be relevant.
2036
2037
2038setUpClass and tearDownClass
2039~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2040
2041These must be implemented as class methods::
2042
2043 import unittest
2044
2045 class Test(unittest.TestCase):
2046 @classmethod
2047 def setUpClass(cls):
2048 cls._connection = createExpensiveConnectionObject()
2049
2050 @classmethod
2051 def tearDownClass(cls):
2052 cls._connection.destroy()
2053
2054If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2055then you must call up to them yourself. The implementations in
2056:class:`TestCase` are empty.
2057
2058If an exception is raised during a ``setUpClass`` then the tests in the class
2059are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002060have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
2061``SkipTest`` exception then the class will be reported as having been skipped
2062instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002063
2064
2065setUpModule and tearDownModule
2066~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2067
2068These should be implemented as functions::
2069
2070 def setUpModule():
2071 createConnection()
2072
2073 def tearDownModule():
2074 closeConnection()
2075
2076If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002077module will be run and the ``tearDownModule`` will not be run. If the exception is a
2078``SkipTest`` exception then the module will be reported as having been skipped
2079instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002080
2081
2082Signal Handling
2083---------------
2084
Georg Brandl419e3de2010-12-01 15:44:25 +00002085.. versionadded:: 3.2
2086
Éric Araujo8acb67c2010-11-26 23:31:07 +00002087The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002088along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2089more friendly handling of control-C during a test run. With catch break
2090behavior enabled control-C will allow the currently running test to complete,
2091and the test run will then end and report all the results so far. A second
2092control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002093
Michael Foordde4ceab2010-04-25 19:53:49 +00002094The control-c handling signal handler attempts to remain compatible with code or
2095tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2096handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2097i.e. it has been replaced by the system under test and delegated to, then it
2098calls the default handler. This will normally be the expected behavior by code
2099that replaces an installed handler and delegates to it. For individual tests
2100that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2101decorator can be used.
2102
2103There are a few utility functions for framework authors to enable control-c
2104handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002105
2106.. function:: installHandler()
2107
2108 Install the control-c handler. When a :const:`signal.SIGINT` is received
2109 (usually in response to the user pressing control-c) all registered results
2110 have :meth:`~TestResult.stop` called.
2111
Michael Foord469b1f02010-04-26 23:41:26 +00002112
Benjamin Petersonb48af542010-04-11 20:43:16 +00002113.. function:: registerResult(result)
2114
2115 Register a :class:`TestResult` object for control-c handling. Registering a
2116 result stores a weak reference to it, so it doesn't prevent the result from
2117 being garbage collected.
2118
Michael Foordde4ceab2010-04-25 19:53:49 +00002119 Registering a :class:`TestResult` object has no side-effects if control-c
2120 handling is not enabled, so test frameworks can unconditionally register
2121 all results they create independently of whether or not handling is enabled.
2122
Michael Foord469b1f02010-04-26 23:41:26 +00002123
Benjamin Petersonb48af542010-04-11 20:43:16 +00002124.. function:: removeResult(result)
2125
2126 Remove a registered result. Once a result has been removed then
2127 :meth:`~TestResult.stop` will no longer be called on that result object in
2128 response to a control-c.
2129
Michael Foord469b1f02010-04-26 23:41:26 +00002130
Michael Foordde4ceab2010-04-25 19:53:49 +00002131.. function:: removeHandler(function=None)
2132
2133 When called without arguments this function removes the control-c handler
2134 if it has been installed. This function can also be used as a test decorator
2135 to temporarily remove the handler whilst the test is being executed::
2136
2137 @unittest.removeHandler
2138 def test_signal_handling(self):
2139 ...