blob: 346b8a268271d4332608cd85d6025b0f8756aa19 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
11
12.. versionadded:: 2.1
Benjamin Peterson692428e2009-03-23 21:50:21 +000013
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Peterson99721e02009-03-23 23:10:14 +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 Brandl8ec7f652007-08-15 14:28:01 +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 Peterson176a56c2009-05-25 00:48:58 +000062all tests added directly to the suite and in "child" test suites are run.
Georg Brandl8ec7f652007-08-15 14:28:01 +000063
Benjamin Peterson99721e02009-03-23 23:10:14 +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 Brandl8ec7f652007-08-15 14:28:01 +000072
73
74.. seealso::
75
76 Module :mod:`doctest`
77 Another test-support module with a very different flavor.
78
Michael Foordba097ec2010-04-03 17:03:11 +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 Brandld198b762009-05-31 14:15:25 +000084 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
Georg Brandl2fcd1732009-05-30 10:45:40 +000085 Kent Beck's original paper on testing frameworks using the pattern shared
86 by :mod:`unittest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000087
Georg Brandld198b762009-05-31 14:15:25 +000088 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Georg Brandl2fcd1732009-05-30 10:45:40 +000089 Third-party unittest frameworks with a lighter-weight syntax for writing
90 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger21b617b2009-03-24 00:17:11 +000091
Michael Foordba097ec2010-04-03 17:03:11 +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.
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
Michael Foordba097ec2010-04-03 17:03:11 +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.
Michael Foordb4a81c82009-05-29 20:33:46 +000099
Michael Foord5d31e052009-05-11 17:59:43 +0000100
Georg Brandl8ec7f652007-08-15 14:28:01 +0000101.. _unittest-minimal-example:
102
103Basic example
104-------------
105
106The :mod:`unittest` module provides a rich set of tools for constructing and
107running tests. This section demonstrates that a small subset of the tools
108suffice to meet the needs of most users.
109
110Here is a short script to test three functions from the :mod:`random` module::
111
112 import random
113 import unittest
114
115 class TestSequenceFunctions(unittest.TestCase):
116
117 def setUp(self):
118 self.seq = range(10)
119
Benjamin Peterson99721e02009-03-23 23:10:14 +0000120 def test_shuffle(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000121 # make sure the shuffled sequence does not lose any elements
122 random.shuffle(self.seq)
123 self.seq.sort()
124 self.assertEqual(self.seq, range(10))
125
Raymond Hettinger08090bf2010-03-09 08:44:18 +0000126 # should raise an exception for an immutable sequence
127 self.assertRaises(TypeError, random.shuffle, (1,2,3))
128
Benjamin Peterson99721e02009-03-23 23:10:14 +0000129 def test_choice(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000130 element = random.choice(self.seq)
Raymond Hettinger08090bf2010-03-09 08:44:18 +0000131 self.assertTrue(element in self.seq)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000132
Benjamin Peterson99721e02009-03-23 23:10:14 +0000133 def test_sample(self):
Raymond Hettinger08090bf2010-03-09 08:44:18 +0000134 with self.assertRaises(ValueError):
135 random.sample(self.seq, 20)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000136 for element in random.sample(self.seq, 5):
Raymond Hettinger08090bf2010-03-09 08:44:18 +0000137 self.assertTrue(element in self.seq)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000138
139 if __name__ == '__main__':
140 unittest.main()
141
Benjamin Peterson99721e02009-03-23 23:10:14 +0000142A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143individual tests are defined with methods whose names start with the letters
144``test``. This naming convention informs the test runner about which methods
145represent tests.
146
Benjamin Peterson99721e02009-03-23 23:10:14 +0000147The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foorddb43b5a2010-02-10 14:25:12 +0000148expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson99721e02009-03-23 23:10:14 +0000149:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
150These methods are used instead of the :keyword:`assert` statement so the test
151runner can accumulate all test results and produce a report.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152
Benjamin Peterson99721e02009-03-23 23:10:14 +0000153When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
154method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
155defined, the test runner will invoke that method after each test. In the
156example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
157test.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000158
159The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujoa8132ec2010-12-16 03:53:53 +0000160provides a command-line interface to the test script. When run from the command
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161line, the above script produces an output that looks like this::
162
163 ...
164 ----------------------------------------------------------------------
165 Ran 3 tests in 0.000s
166
167 OK
168
169Instead of :func:`unittest.main`, there are other ways to run the tests with a
170finer level of control, less terse output, and no requirement to be run from the
171command line. For example, the last two lines may be replaced with::
172
173 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
174 unittest.TextTestRunner(verbosity=2).run(suite)
175
176Running the revised script from the interpreter or another script produces the
177following output::
178
Ezio Melotti68beef62010-02-28 03:11:07 +0000179 test_choice (__main__.TestSequenceFunctions) ... ok
180 test_sample (__main__.TestSequenceFunctions) ... ok
181 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
183 ----------------------------------------------------------------------
184 Ran 3 tests in 0.110s
185
186 OK
187
188The above examples show the most commonly used :mod:`unittest` features which
189are sufficient to meet many everyday testing needs. The remainder of the
190documentation explores the full feature set from first principles.
191
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000192
193.. _unittest-command-line-interface:
194
Éric Araujoa8132ec2010-12-16 03:53:53 +0000195Command-Line Interface
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000196----------------------
197
198The unittest module can be used from the command line to run tests from
199modules, classes or even individual test methods::
200
201 python -m unittest test_module1 test_module2
202 python -m unittest test_module.TestClass
203 python -m unittest test_module.TestClass.test_method
204
205You can pass in a list with any combination of module names, and fully
206qualified class or method names.
207
208You can run tests with more detail (higher verbosity) by passing in the -v flag::
209
Ezio Melotti062d2b52009-12-19 22:41:49 +0000210 python -m unittest -v test_module
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000211
Éric Araujoa8132ec2010-12-16 03:53:53 +0000212For a list of all the command-line options::
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000213
214 python -m unittest -h
215
216.. versionchanged:: 2.7
217 In earlier versions it was only possible to run individual test methods and
218 not modules or classes.
219
Michael Foordba097ec2010-04-03 17:03:11 +0000220
Éric Araujoa8132ec2010-12-16 03:53:53 +0000221Command-line options
222~~~~~~~~~~~~~~~~~~~~
Michael Foordba097ec2010-04-03 17:03:11 +0000223
Éric Araujoa8132ec2010-12-16 03:53:53 +0000224:program:`unittest` supports these command-line options:
Michael Foordba097ec2010-04-03 17:03:11 +0000225
Éric Araujoa8132ec2010-12-16 03:53:53 +0000226.. program:: unittest
Michael Foordba097ec2010-04-03 17:03:11 +0000227
Éric Araujoa8132ec2010-12-16 03:53:53 +0000228.. cmdoption:: -b, --buffer
Michael Foordba097ec2010-04-03 17:03:11 +0000229
Éric Araujoa8132ec2010-12-16 03:53:53 +0000230 The standard output and standard error streams are buffered during the test
231 run. Output during a passing test is discarded. Output is echoed normally
232 on test fail or error and is added to the failure messages.
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000233
Éric Araujoa8132ec2010-12-16 03:53:53 +0000234.. cmdoption:: -c, --catch
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000235
Éric Araujoa8132ec2010-12-16 03:53:53 +0000236 Control-C during the test run waits for the current test to end and then
237 reports all the results so far. A second control-C raises the normal
238 :exc:`KeyboardInterrupt` exception.
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000239
Éric Araujoa8132ec2010-12-16 03:53:53 +0000240 See `Signal Handling`_ for the functions that provide this functionality.
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000241
Éric Araujoa8132ec2010-12-16 03:53:53 +0000242.. cmdoption:: -f, --failfast
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000243
Éric Araujoa8132ec2010-12-16 03:53:53 +0000244 Stop the test run on the first error or failure.
245
246.. versionadded:: 2.7
247 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Michael Foordba097ec2010-04-03 17:03:11 +0000248
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000249The command line can also be used for test discovery, for running all of the
250tests in a project or just a subset.
251
252
253.. _unittest-test-discovery:
254
255Test Discovery
256--------------
257
258.. versionadded:: 2.7
259
Ezio Melotti9e1ed472011-03-08 17:08:25 +0200260Unittest supports simple test discovery. In order to be compatible with test
261discovery, all of the test files must be :ref:`modules <tut-modules>` or
262:ref:`packages <tut-packages>` importable from the top-level directory of
263the project (this means that their filenames must be valid
264:ref:`identifiers <identifiers>`).
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000265
266Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujoa8132ec2010-12-16 03:53:53 +0000267used from the command line. The basic command-line usage is::
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000268
269 cd project_directory
270 python -m unittest discover
271
272The ``discover`` sub-command has the following options:
273
Éric Araujoa8132ec2010-12-16 03:53:53 +0000274.. program:: unittest discover
275
276.. cmdoption:: -v, --verbose
277
278 Verbose output
279
280.. cmdoption:: -s directory
281
282 Directory to start discovery ('.' default)
283
284.. cmdoption:: -p pattern
285
286 Pattern to match test files ('test*.py' default)
287
288.. cmdoption:: -t directory
289
290 Top level directory of project (defaults to start directory)
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000291
Andrew M. Kuchling60383182010-04-30 01:32:47 +0000292The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
293as positional arguments in that order. The following two command lines
294are equivalent::
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000295
Ezio Melotti7b4e02c2010-01-27 20:25:11 +0000296 python -m unittest discover -s project_directory -p '*_test.py'
297 python -m unittest discover project_directory '*_test.py'
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000298
Michael Foord8851b712010-05-08 15:09:37 +0000299As well as being a path it is possible to pass a package name, for example
300``myproject.subpackage.test``, as the start directory. The package name you
301supply will then be imported and its location on the filesystem will be used
302as the start directory.
303
304.. caution::
305
306 Test discovery loads tests by importing them. Once test discovery has
307 found all the test files from the start directory you specify it turns the
308 paths into package names to import. For example `foo/bar/baz.py` will be
309 imported as ``foo.bar.baz``.
310
311 If you have a package installed globally and attempt test discovery on
312 a different copy of the package then the import *could* happen from the
313 wrong place. If this happens test discovery will warn you and exit.
314
315 If you supply the start directory as a package name rather than a
316 path to a directory then discover assumes that whichever location it
317 imports from is the location you intended, so you will not get the
318 warning.
319
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000320Test modules and packages can customize test loading and discovery by through
321the `load_tests protocol`_.
322
323
Georg Brandl8ec7f652007-08-15 14:28:01 +0000324.. _organizing-tests:
325
326Organizing test code
327--------------------
328
329The basic building blocks of unit testing are :dfn:`test cases` --- single
330scenarios that must be set up and checked for correctness. In :mod:`unittest`,
331test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
332class. To make your own test cases you must write subclasses of
333:class:`TestCase`, or use :class:`FunctionTestCase`.
334
335An instance of a :class:`TestCase`\ -derived class is an object that can
336completely run a single test method, together with optional set-up and tidy-up
337code.
338
339The testing code of a :class:`TestCase` instance should be entirely self
340contained, such that it can be run either in isolation or in arbitrary
341combination with any number of other test cases.
342
Benjamin Peterson99721e02009-03-23 23:10:14 +0000343The simplest :class:`TestCase` subclass will simply override the
344:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000345
346 import unittest
347
348 class DefaultWidgetSizeTestCase(unittest.TestCase):
349 def runTest(self):
350 widget = Widget('The widget')
351 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
352
Gregory P. Smith28399852009-03-31 16:54:10 +0000353Note that in order to test something, we use the one of the :meth:`assert\*`
Georg Brandl2fcd1732009-05-30 10:45:40 +0000354methods provided by the :class:`TestCase` base class. If the test fails, an
355exception will be raised, and :mod:`unittest` will identify the test case as a
356:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
357helps you identify where the problem is: :dfn:`failures` are caused by incorrect
358results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
359code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000360
361The way to run a test case will be described later. For now, note that to
362construct an instance of such a test case, we call its constructor without
363arguments::
364
365 testCase = DefaultWidgetSizeTestCase()
366
367Now, such test cases can be numerous, and their set-up can be repetitive. In
368the above case, constructing a :class:`Widget` in each of 100 Widget test case
369subclasses would mean unsightly duplication.
370
371Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson99721e02009-03-23 23:10:14 +0000372:meth:`~TestCase.setUp`, which the testing framework will automatically call for
373us when we run the test::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000374
375 import unittest
376
377 class SimpleWidgetTestCase(unittest.TestCase):
378 def setUp(self):
379 self.widget = Widget('The widget')
380
381 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
382 def runTest(self):
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000383 self.assertEqual(self.widget.size(), (50,50),
384 'incorrect default size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000385
386 class WidgetResizeTestCase(SimpleWidgetTestCase):
387 def runTest(self):
388 self.widget.resize(100,150)
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000389 self.assertEqual(self.widget.size(), (100,150),
390 'wrong size after resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000391
Benjamin Peterson99721e02009-03-23 23:10:14 +0000392If the :meth:`~TestCase.setUp` method raises an exception while the test is
393running, the framework will consider the test to have suffered an error, and the
394:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000395
Benjamin Peterson99721e02009-03-23 23:10:14 +0000396Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
397after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000398
399 import unittest
400
401 class SimpleWidgetTestCase(unittest.TestCase):
402 def setUp(self):
403 self.widget = Widget('The widget')
404
405 def tearDown(self):
406 self.widget.dispose()
407 self.widget = None
408
Benjamin Peterson99721e02009-03-23 23:10:14 +0000409If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
410be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000411
412Such a working environment for the testing code is called a :dfn:`fixture`.
413
414Often, many small test cases will use the same fixture. In this case, we would
415end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
416classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000417discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
418mechanism::
419
420 import unittest
421
422 class WidgetTestCase(unittest.TestCase):
423 def setUp(self):
424 self.widget = Widget('The widget')
425
426 def tearDown(self):
427 self.widget.dispose()
428 self.widget = None
429
Ezio Melotti68beef62010-02-28 03:11:07 +0000430 def test_default_size(self):
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000431 self.assertEqual(self.widget.size(), (50,50),
432 'incorrect default size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000433
Ezio Melotti68beef62010-02-28 03:11:07 +0000434 def test_resize(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435 self.widget.resize(100,150)
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000436 self.assertEqual(self.widget.size(), (100,150),
437 'wrong size after resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000438
Benjamin Peterson99721e02009-03-23 23:10:14 +0000439Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
440provided two different test methods. Class instances will now each run one of
Ezio Melotti68beef62010-02-28 03:11:07 +0000441the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson99721e02009-03-23 23:10:14 +0000442separately for each instance. When creating an instance we must specify the
443test method it is to run. We do this by passing the method name in the
444constructor::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000445
Ezio Melotti68beef62010-02-28 03:11:07 +0000446 defaultSizeTestCase = WidgetTestCase('test_default_size')
447 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000448
449Test case instances are grouped together according to the features they test.
450:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
451represented by :mod:`unittest`'s :class:`TestSuite` class::
452
453 widgetTestSuite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000454 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
455 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000456
457For the ease of running tests, as we will see later, it is a good idea to
458provide in each test module a callable object that returns a pre-built test
459suite::
460
461 def suite():
462 suite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000463 suite.addTest(WidgetTestCase('test_default_size'))
464 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000465 return suite
466
467or even::
468
469 def suite():
Ezio Melotti68beef62010-02-28 03:11:07 +0000470 tests = ['test_default_size', 'test_resize']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000471
472 return unittest.TestSuite(map(WidgetTestCase, tests))
473
474Since it is a common pattern to create a :class:`TestCase` subclass with many
475similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
476class that can be used to automate the process of creating a test suite and
477populating it with individual tests. For example, ::
478
479 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
480
Ezio Melotti68beef62010-02-28 03:11:07 +0000481will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
482``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl8ec7f652007-08-15 14:28:01 +0000483name prefix to identify test methods automatically.
484
485Note that the order in which the various test cases will be run is determined by
486sorting the test function names with the built-in :func:`cmp` function.
487
488Often it is desirable to group suites of test cases together, so as to run tests
489for the whole system at once. This is easy, since :class:`TestSuite` instances
490can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
491added to a :class:`TestSuite`::
492
493 suite1 = module1.TheTestSuite()
494 suite2 = module2.TheTestSuite()
495 alltests = unittest.TestSuite([suite1, suite2])
496
497You can place the definitions of test cases and test suites in the same modules
498as the code they are to test (such as :file:`widget.py`), but there are several
499advantages to placing the test code in a separate module, such as
500:file:`test_widget.py`:
501
502* The test module can be run standalone from the command line.
503
504* The test code can more easily be separated from shipped code.
505
506* There is less temptation to change test code to fit the code it tests without
507 a good reason.
508
509* Test code should be modified much less frequently than the code it tests.
510
511* Tested code can be refactored more easily.
512
513* Tests for modules written in C must be in separate modules anyway, so why not
514 be consistent?
515
516* If the testing strategy changes, there is no need to change the source code.
517
518
519.. _legacy-unit-tests:
520
521Re-using old test code
522----------------------
523
524Some users will find that they have existing test code that they would like to
525run from :mod:`unittest`, without converting every old test function to a
526:class:`TestCase` subclass.
527
528For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
529This subclass of :class:`TestCase` can be used to wrap an existing test
530function. Set-up and tear-down functions can also be provided.
531
532Given the following test function::
533
534 def testSomething():
535 something = makeSomething()
536 assert something.name is not None
537 # ...
538
539one can create an equivalent test case instance as follows::
540
541 testcase = unittest.FunctionTestCase(testSomething)
542
543If there are additional set-up and tear-down methods that should be called as
544part of the test case's operation, they can also be provided like so::
545
546 testcase = unittest.FunctionTestCase(testSomething,
547 setUp=makeSomethingDB,
548 tearDown=deleteSomethingDB)
549
550To make migrating existing test suites easier, :mod:`unittest` supports tests
551raising :exc:`AssertionError` to indicate test failure. However, it is
552recommended that you use the explicit :meth:`TestCase.fail\*` and
553:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
554may treat :exc:`AssertionError` differently.
555
556.. note::
557
Georg Brandl2fcd1732009-05-30 10:45:40 +0000558 Even though :class:`FunctionTestCase` can be used to quickly convert an
559 existing test base over to a :mod:`unittest`\ -based system, this approach is
560 not recommended. Taking the time to set up proper :class:`TestCase`
561 subclasses will make future test refactorings infinitely easier.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000562
Benjamin Peterson99721e02009-03-23 23:10:14 +0000563In some cases, the existing tests may have been written using the :mod:`doctest`
564module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
565automatically build :class:`unittest.TestSuite` instances from the existing
566:mod:`doctest`\ -based tests.
567
Georg Brandl8ec7f652007-08-15 14:28:01 +0000568
Benjamin Peterson692428e2009-03-23 21:50:21 +0000569.. _unittest-skipping:
570
571Skipping tests and expected failures
572------------------------------------
573
Michael Foordfb0844b2010-02-05 21:45:12 +0000574.. versionadded:: 2.7
575
Benjamin Peterson692428e2009-03-23 21:50:21 +0000576Unittest supports skipping individual test methods and even whole classes of
577tests. In addition, it supports marking a test as a "expected failure," a test
578that is broken and will fail, but shouldn't be counted as a failure on a
579:class:`TestResult`.
580
581Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
582or one of its conditional variants.
583
584Basic skipping looks like this: ::
585
586 class MyTestCase(unittest.TestCase):
587
588 @unittest.skip("demonstrating skipping")
589 def test_nothing(self):
590 self.fail("shouldn't happen")
591
Georg Brandl2fcd1732009-05-30 10:45:40 +0000592 @unittest.skipIf(mylib.__version__ < (1, 3),
593 "not supported in this library version")
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000594 def test_format(self):
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000595 # Tests that work for only a certain version of the library.
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000596 pass
597
598 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
599 def test_windows_support(self):
600 # windows specific testing code
601 pass
602
Benjamin Peterson692428e2009-03-23 21:50:21 +0000603This is the output of running the example above in verbose mode: ::
604
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000605 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000606 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000607 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000608
609 ----------------------------------------------------------------------
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000610 Ran 3 tests in 0.005s
611
612 OK (skipped=3)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000613
614Classes can be skipped just like methods: ::
615
616 @skip("showing class skipping")
617 class MySkippedTestCase(unittest.TestCase):
618 def test_not_run(self):
619 pass
620
Benjamin Peterson31b78062009-03-23 23:13:36 +0000621:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
622that needs to be set up is not available.
623
Benjamin Peterson692428e2009-03-23 21:50:21 +0000624Expected failures use the :func:`expectedFailure` decorator. ::
625
626 class ExpectedFailureTestCase(unittest.TestCase):
627 @unittest.expectedFailure
628 def test_fail(self):
629 self.assertEqual(1, 0, "broken")
630
631It's easy to roll your own skipping decorators by making a decorator that calls
632:func:`skip` on the test when it wants it to be skipped. This decorator skips
633the test unless the passed object has a certain attribute: ::
634
635 def skipUnlessHasattr(obj, attr):
636 if hasattr(obj, attr):
637 return lambda func: func
638 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
639
640The following decorators implement test skipping and expected failures:
641
642.. function:: skip(reason)
643
644 Unconditionally skip the decorated test. *reason* should describe why the
645 test is being skipped.
646
647.. function:: skipIf(condition, reason)
648
649 Skip the decorated test if *condition* is true.
650
651.. function:: skipUnless(condition, reason)
652
Georg Brandl09302282010-10-06 09:32:48 +0000653 Skip the decorated test unless *condition* is true.
Benjamin Peterson692428e2009-03-23 21:50:21 +0000654
655.. function:: expectedFailure
656
657 Mark the test as an expected failure. If the test fails when run, the test
658 is not counted as a failure.
659
Michael Foord09e29802010-04-04 22:41:54 +0000660Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
661Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
Michael Foordba097ec2010-04-03 17:03:11 +0000662
Benjamin Peterson692428e2009-03-23 21:50:21 +0000663
Georg Brandl8ec7f652007-08-15 14:28:01 +0000664.. _unittest-contents:
665
666Classes and functions
667---------------------
668
Benjamin Peterson99721e02009-03-23 23:10:14 +0000669This section describes in depth the API of :mod:`unittest`.
670
671
672.. _testcase-objects:
673
674Test cases
675~~~~~~~~~~
Georg Brandl8ec7f652007-08-15 14:28:01 +0000676
677.. class:: TestCase([methodName])
678
679 Instances of the :class:`TestCase` class represent the smallest testable units
680 in the :mod:`unittest` universe. This class is intended to be used as a base
681 class, with specific tests being implemented by concrete subclasses. This class
682 implements the interface needed by the test runner to allow it to drive the
683 test, and methods that the test code can use to check for and report various
684 kinds of failure.
685
686 Each instance of :class:`TestCase` will run a single test method: the method
687 named *methodName*. If you remember, we had an earlier example that went
688 something like this::
689
690 def suite():
691 suite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000692 suite.addTest(WidgetTestCase('test_default_size'))
693 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694 return suite
695
696 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
697 single test.
698
Benjamin Peterson99721e02009-03-23 23:10:14 +0000699 *methodName* defaults to :meth:`runTest`.
700
701 :class:`TestCase` instances provide three groups of methods: one group used
702 to run the test, another used by the test implementation to check conditions
703 and report failures, and some inquiry methods allowing information about the
704 test itself to be gathered.
705
706 Methods in the first group (running the test) are:
707
708
709 .. method:: setUp()
710
711 Method called to prepare the test fixture. This is called immediately
712 before calling the test method; any exception raised by this method will
713 be considered an error rather than a test failure. The default
714 implementation does nothing.
715
716
717 .. method:: tearDown()
718
719 Method called immediately after the test method has been called and the
720 result recorded. This is called even if the test method raised an
721 exception, so the implementation in subclasses may need to be particularly
722 careful about checking internal state. Any exception raised by this
723 method will be considered an error rather than a test failure. This
724 method will only be called if the :meth:`setUp` succeeds, regardless of
725 the outcome of the test method. The default implementation does nothing.
726
727
Michael Foordba097ec2010-04-03 17:03:11 +0000728 .. method:: setUpClass()
729
730 A class method called before tests in an individual class run.
731 ``setUpClass`` is called with the class as the only argument
Michael Foord09e29802010-04-04 22:41:54 +0000732 and must be decorated as a :func:`classmethod`::
Michael Foordba097ec2010-04-03 17:03:11 +0000733
734 @classmethod
735 def setUpClass(cls):
736 ...
737
738 See `Class and Module Fixtures`_ for more details.
739
740 .. versionadded:: 2.7
741
742
743 .. method:: tearDownClass()
744
745 A class method called after tests in an individual class have run.
746 ``tearDownClass`` is called with the class as the only argument
747 and must be decorated as a :meth:`classmethod`::
748
749 @classmethod
750 def tearDownClass(cls):
751 ...
752
753 See `Class and Module Fixtures`_ for more details.
754
755 .. versionadded:: 2.7
756
757
Benjamin Peterson99721e02009-03-23 23:10:14 +0000758 .. method:: run([result])
759
760 Run the test, collecting the result into the test result object passed as
761 *result*. If *result* is omitted or :const:`None`, a temporary result
Ezio Melottic2f5a592009-06-30 22:51:06 +0000762 object is created (by calling the :meth:`defaultTestResult` method) and
763 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000764
765 The same effect may be had by simply calling the :class:`TestCase`
766 instance.
767
768
Benjamin Peterson47d97382009-03-26 20:05:50 +0000769 .. method:: skipTest(reason)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000770
Stefan Krah4a769052010-05-19 15:59:40 +0000771 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson31b78062009-03-23 23:13:36 +0000772 test. See :ref:`unittest-skipping` for more information.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000773
Georg Brandl90aae552010-04-10 11:15:24 +0000774 .. versionadded:: 2.7
775
Benjamin Peterson99721e02009-03-23 23:10:14 +0000776
777 .. method:: debug()
778
779 Run the test without collecting the result. This allows exceptions raised
780 by the test to be propagated to the caller, and can be used to support
781 running tests under a debugger.
782
783 The test code can use any of the following methods to check for and report
784 failures.
785
786
Gregory P. Smith28399852009-03-31 16:54:10 +0000787 .. method:: assertTrue(expr[, msg])
788 assert_(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000789 failUnless(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000790
Georg Brandl64034bb2009-04-25 14:51:31 +0000791 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson99721e02009-03-23 23:10:14 +0000792 will be *msg* if given, otherwise it will be :const:`None`.
793
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000794 .. deprecated:: 2.7
Georg Brandl6f635f42010-05-10 21:50:57 +0000795 :meth:`failUnless` and :meth:`assert_`; use :meth:`assertTrue`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000796
Benjamin Peterson99721e02009-03-23 23:10:14 +0000797
798 .. method:: assertEqual(first, second[, msg])
799 failUnlessEqual(first, second[, msg])
800
801 Test that *first* and *second* are equal. If the values do not compare
802 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000803 :const:`None`. Note that using :meth:`assertEqual` improves upon
804 doing the comparison as the first parameter to :meth:`assertTrue`: the
805 default value for *msg* include representations of both *first* and
806 *second*.
807
808 In addition, if *first* and *second* are the exact same type and one of
Michael Foordfe6349c2010-02-08 22:41:16 +0000809 list, tuple, dict, set, frozenset or unicode or any type that a subclass
Michael Foord7b5aa462010-02-08 23:15:22 +0000810 registers with :meth:`addTypeEqualityFunc` the type specific equality
811 function will be called in order to generate a more useful default error
812 message.
Gregory P. Smith28399852009-03-31 16:54:10 +0000813
814 .. versionchanged:: 2.7
815 Added the automatic calling of type specific equality function.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000816
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000817 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000818 :meth:`failUnlessEqual`; use :meth:`assertEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000819
Benjamin Peterson99721e02009-03-23 23:10:14 +0000820
821 .. method:: assertNotEqual(first, second[, msg])
822 failIfEqual(first, second[, msg])
823
824 Test that *first* and *second* are not equal. If the values do compare
825 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000826 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
827 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson99721e02009-03-23 23:10:14 +0000828 default value for *msg* can be computed to include representations of both
829 *first* and *second*.
830
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000831 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000832 :meth:`failIfEqual`; use :meth:`assertNotEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000833
Benjamin Peterson99721e02009-03-23 23:10:14 +0000834
Michael Foordba097ec2010-04-03 17:03:11 +0000835 .. method:: assertAlmostEqual(first, second[, places[, msg[, delta]]])
Michael Foordefc2f492010-04-08 04:33:20 +0000836 failUnlessAlmostEqual(first, second[, places[, msg[, delta]]])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000837
838 Test that *first* and *second* are approximately equal by computing the
839 difference, rounding to the given number of decimal *places* (default 7),
840 and comparing to zero.
841
842 Note that comparing a given number of decimal places is not the same as
843 comparing a given number of significant digits. If the values do not
844 compare equal, the test will fail with the explanation given by *msg*, or
845 :const:`None`.
846
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000847 If *delta* is supplied instead of *places* then the difference
Michael Foordba097ec2010-04-03 17:03:11 +0000848 between *first* and *second* must be less than *delta*.
849
850 Supplying both *delta* and *places* raises a ``TypeError``.
851
Michael Foordc3f79372009-09-13 16:40:02 +0000852 .. versionchanged:: 2.7
853 Objects that compare equal are automatically almost equal.
Michael Foordba097ec2010-04-03 17:03:11 +0000854 Added the ``delta`` keyword argument.
Michael Foordc3f79372009-09-13 16:40:02 +0000855
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000856 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000857 :meth:`failUnlessAlmostEqual`; use :meth:`assertAlmostEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000858
Benjamin Peterson99721e02009-03-23 23:10:14 +0000859
Michael Foordba097ec2010-04-03 17:03:11 +0000860 .. method:: assertNotAlmostEqual(first, second[, places[, msg[, delta]]])
Michael Foordefc2f492010-04-08 04:33:20 +0000861 failIfAlmostEqual(first, second[, places[, msg[, delta]]])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000862
863 Test that *first* and *second* are not approximately equal by computing
864 the difference, rounding to the given number of decimal *places* (default
865 7), and comparing to zero.
866
867 Note that comparing a given number of decimal places is not the same as
868 comparing a given number of significant digits. If the values do not
869 compare equal, the test will fail with the explanation given by *msg*, or
870 :const:`None`.
871
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000872 If *delta* is supplied instead of *places* then the difference
Michael Foordba097ec2010-04-03 17:03:11 +0000873 between *first* and *second* must be more than *delta*.
874
875 Supplying both *delta* and *places* raises a ``TypeError``.
876
Michael Foordc3f79372009-09-13 16:40:02 +0000877 .. versionchanged:: 2.7
878 Objects that compare equal automatically fail.
Michael Foordba097ec2010-04-03 17:03:11 +0000879 Added the ``delta`` keyword argument.
Michael Foordc3f79372009-09-13 16:40:02 +0000880
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000881 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +0000882 :meth:`failIfAlmostEqual`; use :meth:`assertNotAlmostEqual`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000883
Benjamin Peterson99721e02009-03-23 23:10:14 +0000884
Gregory P. Smith28399852009-03-31 16:54:10 +0000885 .. method:: assertGreater(first, second, msg=None)
886 assertGreaterEqual(first, second, msg=None)
887 assertLess(first, second, msg=None)
888 assertLessEqual(first, second, msg=None)
889
890 Test that *first* is respectively >, >=, < or <= than *second* depending
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000891 on the method name. If not, the test will fail with an explanation
Gregory P. Smith28399852009-03-31 16:54:10 +0000892 or with the explanation given by *msg*::
893
894 >>> self.assertGreaterEqual(3, 4)
895 AssertionError: "3" unexpectedly not greater than or equal to "4"
896
897 .. versionadded:: 2.7
898
899
900 .. method:: assertMultiLineEqual(self, first, second, msg=None)
901
902 Test that the multiline string *first* is equal to the string *second*.
903 When not equal a diff of the two strings highlighting the differences
Michael Foordfe6349c2010-02-08 22:41:16 +0000904 will be included in the error message. This method is used by default
905 when comparing Unicode strings with :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000906
Michael Foord98e7b762010-03-20 03:00:34 +0000907 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000908
909 .. versionadded:: 2.7
910
911
Ezio Melotti5afe42b2010-01-16 19:36:42 +0000912 .. method:: assertRegexpMatches(text, regexp, msg=None)
Gregory P. Smith28399852009-03-31 16:54:10 +0000913
914 Verifies that a *regexp* search matches *text*. Fails with an error
915 message including the pattern and the *text*. *regexp* may be
916 a regular expression object or a string containing a regular expression
917 suitable for use by :func:`re.search`.
918
919 .. versionadded:: 2.7
920
921
Michael Foordba097ec2010-04-03 17:03:11 +0000922 .. method:: assertNotRegexpMatches(text, regexp, msg=None)
923
924 Verifies that a *regexp* search does not match *text*. Fails with an error
Michael Foord959c16d2010-05-08 16:40:52 +0000925 message including the pattern and the part of *text* that matches. *regexp*
926 may be a regular expression object or a string containing a regular
927 expression suitable for use by :func:`re.search`.
Michael Foordba097ec2010-04-03 17:03:11 +0000928
929 .. versionadded:: 2.7
930
931
Gregory P. Smith28399852009-03-31 16:54:10 +0000932 .. method:: assertIn(first, second, msg=None)
933 assertNotIn(first, second, msg=None)
934
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000935 Tests that *first* is or is not in *second* with an explanatory error
Gregory P. Smith28399852009-03-31 16:54:10 +0000936 message as appropriate.
937
Michael Foord98e7b762010-03-20 03:00:34 +0000938 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000939
940 .. versionadded:: 2.7
941
942
Michael Foord98e7b762010-03-20 03:00:34 +0000943 .. method:: assertItemsEqual(actual, expected, msg=None)
Gregory P. Smith28399852009-03-31 16:54:10 +0000944
Michael Foorde70c72c2010-01-31 19:59:26 +0000945 Test that sequence *expected* contains the same elements as *actual*,
Michael Foord98e7b762010-03-20 03:00:34 +0000946 regardless of their order. When they don't, an error message listing the
947 differences between the sequences will be generated.
Gregory P. Smith28399852009-03-31 16:54:10 +0000948
Michael Foord98e7b762010-03-20 03:00:34 +0000949 Duplicate elements are *not* ignored when comparing *actual* and
950 *expected*. It verifies if each element has the same count in both
951 sequences. It is the equivalent of ``assertEqual(sorted(expected),
952 sorted(actual))`` but it works with sequences of unhashable objects as
953 well.
Michael Foord1c430012010-02-05 20:52:14 +0000954
Michael Foord98e7b762010-03-20 03:00:34 +0000955 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000956
957 .. versionadded:: 2.7
958
959
960 .. method:: assertSetEqual(set1, set2, msg=None)
961
962 Tests that two sets are equal. If not, an error message is constructed
Michael Foordfe6349c2010-02-08 22:41:16 +0000963 that lists the differences between the sets. This method is used by
964 default when comparing sets or frozensets with :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000965
966 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
967 method.
968
Michael Foord98e7b762010-03-20 03:00:34 +0000969 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000970
971 .. versionadded:: 2.7
972
973
974 .. method:: assertDictEqual(expected, actual, msg=None)
975
976 Test that two dictionaries are equal. If not, an error message is
Michael Foordfe6349c2010-02-08 22:41:16 +0000977 constructed that shows the differences in the dictionaries. This
978 method will be used by default to compare dictionaries in
979 calls to :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000980
Michael Foord98e7b762010-03-20 03:00:34 +0000981 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000982
983 .. versionadded:: 2.7
984
985
986 .. method:: assertDictContainsSubset(expected, actual, msg=None)
987
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000988 Tests whether the key/value pairs in dictionary *actual* are a
Gregory P. Smith28399852009-03-31 16:54:10 +0000989 superset of those in *expected*. If not, an error message listing
990 the missing keys and mismatched values is generated.
991
Michael Foord98e7b762010-03-20 03:00:34 +0000992 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +0000993
994 .. versionadded:: 2.7
995
996
997 .. method:: assertListEqual(list1, list2, msg=None)
998 assertTupleEqual(tuple1, tuple2, msg=None)
999
1000 Tests that two lists or tuples are equal. If not an error message is
1001 constructed that shows only the differences between the two. An error
1002 is also raised if either of the parameters are of the wrong type.
Michael Foordfe6349c2010-02-08 22:41:16 +00001003 These methods are used by default when comparing lists or tuples with
1004 :meth:`assertEqual`.
Gregory P. Smith28399852009-03-31 16:54:10 +00001005
Michael Foord98e7b762010-03-20 03:00:34 +00001006 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +00001007
1008 .. versionadded:: 2.7
1009
1010
1011 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
1012
1013 Tests that two sequences are equal. If a *seq_type* is supplied, both
1014 *seq1* and *seq2* must be instances of *seq_type* or a failure will
1015 be raised. If the sequences are different an error message is
1016 constructed that shows the difference between the two.
1017
Michael Foord98e7b762010-03-20 03:00:34 +00001018 If specified, *msg* will be used as the error message on failure.
Gregory P. Smith28399852009-03-31 16:54:10 +00001019
1020 This method is used to implement :meth:`assertListEqual` and
1021 :meth:`assertTupleEqual`.
1022
1023 .. versionadded:: 2.7
1024
1025
Benjamin Peterson99721e02009-03-23 23:10:14 +00001026 .. method:: assertRaises(exception[, callable, ...])
1027 failUnlessRaises(exception[, callable, ...])
1028
1029 Test that an exception is raised when *callable* is called with any
1030 positional or keyword arguments that are also passed to
1031 :meth:`assertRaises`. The test passes if *exception* is raised, is an
1032 error if another exception is raised, or fails if no exception is raised.
1033 To catch any of a group of exceptions, a tuple containing the exception
1034 classes may be passed as *exception*.
1035
Benjamin Peterson7233acc2009-03-29 03:31:40 +00001036 If *callable* is omitted or None, returns a context manager so that the
1037 code under test can be written inline rather than as a function::
1038
Michael Foord1f3fa8a2010-02-05 21:07:38 +00001039 with self.assertRaises(SomeException):
Benjamin Peterson7233acc2009-03-29 03:31:40 +00001040 do_something()
1041
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00001042 The context manager will store the caught exception object in its
Georg Brandldc3694b2010-02-07 17:02:22 +00001043 :attr:`exception` attribute. This can be useful if the intention
Michael Foord1f3fa8a2010-02-05 21:07:38 +00001044 is to perform additional checks on the exception raised::
1045
1046 with self.assertRaises(SomeException) as cm:
1047 do_something()
1048
Georg Brandldc3694b2010-02-07 17:02:22 +00001049 the_exception = cm.exception
Michael Foordba7732e2010-02-05 23:28:12 +00001050 self.assertEqual(the_exception.error_code, 3)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00001051
Benjamin Peterson99721e02009-03-23 23:10:14 +00001052 .. versionchanged:: 2.7
Benjamin Peterson7233acc2009-03-29 03:31:40 +00001053 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001054
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001055 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +00001056 :meth:`failUnlessRaises`; use :meth:`assertRaises`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001057
Benjamin Peterson99721e02009-03-23 23:10:14 +00001058
Gregory P. Smith28399852009-03-31 16:54:10 +00001059 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
Benjamin Peterson99721e02009-03-23 23:10:14 +00001060
Gregory P. Smith28399852009-03-31 16:54:10 +00001061 Like :meth:`assertRaises` but also tests that *regexp* matches
1062 on the string representation of the raised exception. *regexp* may be
1063 a regular expression object or a string containing a regular expression
1064 suitable for use by :func:`re.search`. Examples::
1065
1066 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
1067 int, 'XYZ')
1068
1069 or::
1070
1071 with self.assertRaisesRegexp(ValueError, 'literal'):
1072 int('XYZ')
1073
1074 .. versionadded:: 2.7
1075
1076
1077 .. method:: assertIsNone(expr[, msg])
1078
1079 This signals a test failure if *expr* is not None.
1080
1081 .. versionadded:: 2.7
1082
1083
1084 .. method:: assertIsNotNone(expr[, msg])
1085
1086 The inverse of the :meth:`assertIsNone` method.
1087 This signals a test failure if *expr* is None.
1088
1089 .. versionadded:: 2.7
1090
1091
Michael Foordf2dfef12009-04-05 19:19:28 +00001092 .. method:: assertIs(expr1, expr2[, msg])
1093
1094 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
1095 object.
1096
1097 .. versionadded:: 2.7
1098
1099
1100 .. method:: assertIsNot(expr1, expr2[, msg])
1101
1102 The inverse of the :meth:`assertIs` method.
1103 This signals a test failure if *expr1* and *expr2* evaluate to the same
1104 object.
1105
1106 .. versionadded:: 2.7
1107
1108
Georg Brandlf895cf52009-10-01 20:59:31 +00001109 .. method:: assertIsInstance(obj, cls[, msg])
1110
1111 This signals a test failure if *obj* is not an instance of *cls* (which
1112 can be a class or a tuple of classes, as supported by :func:`isinstance`).
1113
1114 .. versionadded:: 2.7
1115
1116
1117 .. method:: assertNotIsInstance(obj, cls[, msg])
1118
1119 The inverse of the :meth:`assertIsInstance` method. This signals a test
1120 failure if *obj* is an instance of *cls*.
1121
1122 .. versionadded:: 2.7
1123
1124
Gregory P. Smith28399852009-03-31 16:54:10 +00001125 .. method:: assertFalse(expr[, msg])
1126 failIf(expr[, msg])
1127
1128 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001129 This signals a test failure if *expr* is true, with *msg* or :const:`None`
1130 for the error message.
1131
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001132 .. deprecated:: 2.7
Georg Brandl1c7c7302010-02-06 10:08:21 +00001133 :meth:`failIf`; use :meth:`assertFalse`.
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001134
Benjamin Peterson99721e02009-03-23 23:10:14 +00001135
1136 .. method:: fail([msg])
1137
1138 Signals a test failure unconditionally, with *msg* or :const:`None` for
1139 the error message.
1140
1141
1142 .. attribute:: failureException
1143
1144 This class attribute gives the exception raised by the test method. If a
1145 test framework needs to use a specialized exception, possibly to carry
1146 additional information, it must subclass this exception in order to "play
1147 fair" with the framework. The initial value of this attribute is
1148 :exc:`AssertionError`.
1149
Michael Foord345b2fe2009-04-02 03:20:38 +00001150
1151 .. attribute:: longMessage
1152
1153 If set to True then any explicit failure message you pass in to the
1154 assert methods will be appended to the end of the normal failure message.
1155 The normal messages contain useful information about the objects involved,
1156 for example the message from assertEqual shows you the repr of the two
1157 unequal objects. Setting this attribute to True allows you to have a
1158 custom error message in addition to the normal one.
1159
1160 This attribute defaults to False, meaning that a custom message passed
1161 to an assert method will silence the normal message.
1162
1163 The class setting can be overridden in individual tests by assigning an
1164 instance attribute to True or False before calling the assert methods.
1165
1166 .. versionadded:: 2.7
1167
1168
Michael Foord8dde2012010-06-05 21:57:03 +00001169 .. attribute:: maxDiff
1170
1171 This attribute controls the maximum length of diffs output by assert
1172 methods that report diffs on failure. It defaults to 80*8 characters.
1173 Assert methods affected by this attribute are
1174 :meth:`assertSequenceEqual` (including all the sequence comparison
1175 methods that delegate to it), :meth:`assertDictEqual` and
1176 :meth:`assertMultiLineEqual`.
1177
1178 Setting ``maxDiff`` to None means that there is no maximum length of
1179 diffs.
1180
1181 .. versionadded:: 2.7
1182
1183
Benjamin Peterson99721e02009-03-23 23:10:14 +00001184 Testing frameworks can use the following methods to collect information on
1185 the test:
1186
1187
1188 .. method:: countTestCases()
1189
1190 Return the number of tests represented by this test object. For
1191 :class:`TestCase` instances, this will always be ``1``.
1192
1193
1194 .. method:: defaultTestResult()
1195
1196 Return an instance of the test result class that should be used for this
1197 test case class (if no other result instance is provided to the
1198 :meth:`run` method).
1199
1200 For :class:`TestCase` instances, this will always be an instance of
1201 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1202 as necessary.
1203
1204
1205 .. method:: id()
1206
1207 Return a string identifying the specific test case. This is usually the
1208 full name of the test method, including the module and class name.
1209
1210
1211 .. method:: shortDescription()
1212
Gregory P. Smith28399852009-03-31 16:54:10 +00001213 Returns a description of the test, or :const:`None` if no description
1214 has been provided. The default implementation of this method
1215 returns the first line of the test method's docstring, if available,
Michael Foorddb43b5a2010-02-10 14:25:12 +00001216 or :const:`None`.
Gregory P. Smith28399852009-03-31 16:54:10 +00001217
1218
1219 .. method:: addTypeEqualityFunc(typeobj, function)
1220
1221 Registers a type specific :meth:`assertEqual` equality checking
1222 function to be called by :meth:`assertEqual` when both objects it has
1223 been asked to compare are exactly *typeobj* (not subclasses).
1224 *function* must take two positional arguments and a third msg=None
1225 keyword argument just as :meth:`assertEqual` does. It must raise
Andrew M. Kuchling59631852009-04-09 11:23:36 +00001226 ``self.failureException`` when inequality between the first two
Gregory P. Smith28399852009-03-31 16:54:10 +00001227 parameters is detected.
1228
1229 One good use of custom equality checking functions for a type
Andrew M. Kuchling59631852009-04-09 11:23:36 +00001230 is to raise ``self.failureException`` with an error message useful
1231 for debugging the problem by explaining the inequalities in detail.
Gregory P. Smith28399852009-03-31 16:54:10 +00001232
1233 .. versionadded:: 2.7
Georg Brandl8ec7f652007-08-15 14:28:01 +00001234
1235
Michael Foorde2fb98f2009-05-02 20:15:05 +00001236 .. method:: addCleanup(function[, *args[, **kwargs]])
1237
1238 Add a function to be called after :meth:`tearDown` to cleanup resources
1239 used during the test. Functions will be called in reverse order to the
1240 order they are added (LIFO). They are called with any arguments and
1241 keyword arguments passed into :meth:`addCleanup` when they are
1242 added.
1243
1244 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1245 then any cleanup functions added will still be called.
1246
1247 .. versionadded:: 2.7
1248
1249
1250 .. method:: doCleanups()
1251
Barry Warsawfa900d42010-04-12 14:40:49 +00001252 This method is called unconditionally after :meth:`tearDown`, or
Michael Foorde2fb98f2009-05-02 20:15:05 +00001253 after :meth:`setUp` if :meth:`setUp` raises an exception.
1254
1255 It is responsible for calling all the cleanup functions added by
1256 :meth:`addCleanup`. If you need cleanup functions to be called
1257 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1258 yourself.
1259
1260 :meth:`doCleanups` pops methods off the stack of cleanup
1261 functions one at a time, so it can be called at any time.
1262
1263 .. versionadded:: 2.7
1264
1265
Georg Brandl8ec7f652007-08-15 14:28:01 +00001266.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
1267
1268 This class implements the portion of the :class:`TestCase` interface which
Georg Brandl2fcd1732009-05-30 10:45:40 +00001269 allows the test runner to drive the test, but does not provide the methods
1270 which test code can use to check and report errors. This is used to create
1271 test cases using legacy test code, allowing it to be integrated into a
1272 :mod:`unittest`-based test framework.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001273
1274
Benjamin Peterson99721e02009-03-23 23:10:14 +00001275.. _testsuite-objects:
1276
1277Grouping tests
1278~~~~~~~~~~~~~~
1279
Georg Brandl8ec7f652007-08-15 14:28:01 +00001280.. class:: TestSuite([tests])
1281
1282 This class represents an aggregation of individual tests cases and test suites.
1283 The class presents the interface needed by the test runner to allow it to be run
1284 as any other test case. Running a :class:`TestSuite` instance is the same as
1285 iterating over the suite, running each test individually.
1286
1287 If *tests* is given, it must be an iterable of individual test cases or other
1288 test suites that will be used to build the suite initially. Additional methods
1289 are provided to add test cases and suites to the collection later on.
1290
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001291 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1292 they do not actually implement a test. Instead, they are used to aggregate
1293 tests into groups of tests that should be run together. Some additional
1294 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson99721e02009-03-23 23:10:14 +00001295
1296
1297 .. method:: TestSuite.addTest(test)
1298
1299 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1300
1301
1302 .. method:: TestSuite.addTests(tests)
1303
1304 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1305 instances to this test suite.
1306
Georg Brandl2fcd1732009-05-30 10:45:40 +00001307 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1308 each element.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001309
1310 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1311
1312
1313 .. method:: run(result)
1314
1315 Run the tests associated with this suite, collecting the result into the
1316 test result object passed as *result*. Note that unlike
1317 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1318 be passed in.
1319
1320
1321 .. method:: debug()
1322
1323 Run the tests associated with this suite without collecting the
1324 result. This allows exceptions raised by the test to be propagated to the
1325 caller and can be used to support running tests under a debugger.
1326
1327
1328 .. method:: countTestCases()
1329
1330 Return the number of tests represented by this test object, including all
1331 individual tests and sub-suites.
1332
Georg Brandl9bc66822009-04-27 17:04:23 +00001333
1334 .. method:: __iter__()
1335
1336 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1337 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1338 that this method maybe called several times on a single suite
1339 (for example when counting tests or comparing for equality)
1340 so the tests returned must be the same for repeated iterations.
1341
1342 .. versionchanged:: 2.7
1343 In earlier versions the :class:`TestSuite` accessed tests directly rather
1344 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1345 for providing tests.
1346
Benjamin Peterson99721e02009-03-23 23:10:14 +00001347 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1348 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1349
1350
Benjamin Peterson99721e02009-03-23 23:10:14 +00001351Loading and running tests
1352~~~~~~~~~~~~~~~~~~~~~~~~~
1353
Georg Brandl8ec7f652007-08-15 14:28:01 +00001354.. class:: TestLoader()
1355
Benjamin Peterson99721e02009-03-23 23:10:14 +00001356 The :class:`TestLoader` class is used to create test suites from classes and
1357 modules. Normally, there is no need to create an instance of this class; the
1358 :mod:`unittest` module provides an instance that can be shared as
1359 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1360 customization of some configurable properties.
1361
1362 :class:`TestLoader` objects have the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001363
1364
Benjamin Peterson99721e02009-03-23 23:10:14 +00001365 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001366
Benjamin Peterson99721e02009-03-23 23:10:14 +00001367 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1368 :class:`testCaseClass`.
1369
1370
1371 .. method:: loadTestsFromModule(module)
1372
1373 Return a suite of all tests cases contained in the given module. This
1374 method searches *module* for classes derived from :class:`TestCase` and
1375 creates an instance of the class for each test method defined for the
1376 class.
1377
Georg Brandl16a57f62009-04-27 15:29:09 +00001378 .. note::
Benjamin Peterson99721e02009-03-23 23:10:14 +00001379
1380 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1381 convenient in sharing fixtures and helper functions, defining test
1382 methods on base classes that are not intended to be instantiated
1383 directly does not play well with this method. Doing so, however, can
1384 be useful when the fixtures are different and defined in subclasses.
1385
Michael Foordb4a81c82009-05-29 20:33:46 +00001386 If a module provides a ``load_tests`` function it will be called to
1387 load the tests. This allows modules to customize test loading.
1388 This is the `load_tests protocol`_.
1389
1390 .. versionchanged:: 2.7
1391 Support for ``load_tests`` added.
1392
Benjamin Peterson99721e02009-03-23 23:10:14 +00001393
1394 .. method:: loadTestsFromName(name[, module])
1395
1396 Return a suite of all tests cases given a string specifier.
1397
1398 The specifier *name* is a "dotted name" that may resolve either to a
1399 module, a test case class, a test method within a test case class, a
1400 :class:`TestSuite` instance, or a callable object which returns a
1401 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1402 applied in the order listed here; that is, a method on a possible test
1403 case class will be picked up as "a test method within a test case class",
1404 rather than "a callable object".
1405
1406 For example, if you have a module :mod:`SampleTests` containing a
Georg Brandl2fcd1732009-05-30 10:45:40 +00001407 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1408 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1409 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1410 return a suite which will run all three test methods. Using the specifier
1411 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1412 suite which will run only the :meth:`test_two` test method. The specifier
1413 can refer to modules and packages which have not been imported; they will
1414 be imported as a side-effect.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001415
1416 The method optionally resolves *name* relative to the given *module*.
1417
1418
1419 .. method:: loadTestsFromNames(names[, module])
1420
1421 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1422 than a single name. The return value is a test suite which supports all
1423 the tests defined for each name.
1424
1425
1426 .. method:: getTestCaseNames(testCaseClass)
1427
1428 Return a sorted sequence of method names found within *testCaseClass*;
1429 this should be a subclass of :class:`TestCase`.
1430
Michael Foordb4a81c82009-05-29 20:33:46 +00001431
1432 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1433
1434 Find and return all test modules from the specified start directory,
1435 recursing into subdirectories to find them. Only test files that match
Michael Foorde91ea562009-09-13 19:07:03 +00001436 *pattern* will be loaded. (Using shell style pattern matching.) Only
1437 module names that are importable (i.e. are valid Python identifiers) will
1438 be loaded.
Michael Foordb4a81c82009-05-29 20:33:46 +00001439
1440 All test modules must be importable from the top level of the project. If
1441 the start directory is not the top level directory then the top level
1442 directory must be specified separately.
1443
Michael Foorde91ea562009-09-13 19:07:03 +00001444 If importing a module fails, for example due to a syntax error, then this
1445 will be recorded as a single error and discovery will continue.
1446
Michael Foordb4a81c82009-05-29 20:33:46 +00001447 If a test package name (directory with :file:`__init__.py`) matches the
1448 pattern then the package will be checked for a ``load_tests``
1449 function. If this exists then it will be called with *loader*, *tests*,
1450 *pattern*.
1451
Michael Foorddc0460a2009-09-13 19:08:18 +00001452 If load_tests exists then discovery does *not* recurse into the package,
Michael Foordb4a81c82009-05-29 20:33:46 +00001453 ``load_tests`` is responsible for loading all tests in the package.
1454
1455 The pattern is deliberately not stored as a loader attribute so that
1456 packages can continue discovery themselves. *top_level_dir* is stored so
1457 ``load_tests`` does not need to pass this argument in to
1458 ``loader.discover()``.
1459
Michael Foordba097ec2010-04-03 17:03:11 +00001460 *start_dir* can be a dotted module name as well as a directory.
1461
Michael Foord17565e52009-09-27 20:08:23 +00001462 .. versionadded:: 2.7
Michael Foordb4a81c82009-05-29 20:33:46 +00001463
Benjamin Peterson99721e02009-03-23 23:10:14 +00001464 The following attributes of a :class:`TestLoader` can be configured either by
1465 subclassing or assignment on an instance:
1466
1467
1468 .. attribute:: testMethodPrefix
1469
1470 String giving the prefix of method names which will be interpreted as test
1471 methods. The default value is ``'test'``.
1472
1473 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1474 methods.
1475
1476
1477 .. attribute:: sortTestMethodsUsing
1478
1479 Function to be used to compare method names when sorting them in
1480 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
1481 default value is the built-in :func:`cmp` function; the attribute can also
1482 be set to :const:`None` to disable the sort.
1483
1484
1485 .. attribute:: suiteClass
1486
1487 Callable object that constructs a test suite from a list of tests. No
1488 methods on the resulting object are needed. The default value is the
1489 :class:`TestSuite` class.
1490
1491 This affects all the :meth:`loadTestsFrom\*` methods.
1492
1493
Benjamin Peterson99721e02009-03-23 23:10:14 +00001494.. class:: TestResult
1495
1496 This class is used to compile information about which tests have succeeded
1497 and which have failed.
1498
1499 A :class:`TestResult` object stores the results of a set of tests. The
1500 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1501 properly recorded; test authors do not need to worry about recording the
1502 outcome of tests.
1503
1504 Testing frameworks built on top of :mod:`unittest` may want access to the
1505 :class:`TestResult` object generated by running a set of tests for reporting
1506 purposes; a :class:`TestResult` instance is returned by the
1507 :meth:`TestRunner.run` method for this purpose.
1508
1509 :class:`TestResult` instances have the following attributes that will be of
1510 interest when inspecting the results of running a set of tests:
1511
1512
1513 .. attribute:: errors
1514
1515 A list containing 2-tuples of :class:`TestCase` instances and strings
1516 holding formatted tracebacks. Each tuple represents a test which raised an
1517 unexpected exception.
1518
1519 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001520 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1521
1522
1523 .. attribute:: failures
1524
1525 A list containing 2-tuples of :class:`TestCase` instances and strings
1526 holding formatted tracebacks. Each tuple represents a test where a failure
1527 was explicitly signalled using the :meth:`TestCase.fail\*` or
1528 :meth:`TestCase.assert\*` methods.
1529
1530 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001531 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1532
1533 .. attribute:: skipped
1534
1535 A list containing 2-tuples of :class:`TestCase` instances and strings
1536 holding the reason for skipping the test.
1537
1538 .. versionadded:: 2.7
1539
1540 .. attribute:: expectedFailures
1541
Georg Brandl09302282010-10-06 09:32:48 +00001542 A list containing 2-tuples of :class:`TestCase` instances and strings
1543 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson99721e02009-03-23 23:10:14 +00001544 of the test case.
1545
1546 .. attribute:: unexpectedSuccesses
1547
1548 A list containing :class:`TestCase` instances that were marked as expected
1549 failures, but succeeded.
1550
1551 .. attribute:: shouldStop
1552
1553 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1554
1555
1556 .. attribute:: testsRun
1557
1558 The total number of tests run so far.
1559
1560
Michael Foordba097ec2010-04-03 17:03:11 +00001561 .. attribute:: buffer
1562
1563 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1564 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1565 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1566 fails or errors. Any output is also attached to the failure / error message.
1567
1568 .. versionadded:: 2.7
1569
1570
1571 .. attribute:: failfast
1572
1573 If set to true :meth:`stop` will be called on the first failure or error,
1574 halting the test run.
1575
1576 .. versionadded:: 2.7
1577
1578
Benjamin Peterson99721e02009-03-23 23:10:14 +00001579 .. method:: wasSuccessful()
1580
1581 Return :const:`True` if all tests run so far have passed, otherwise returns
1582 :const:`False`.
1583
1584
1585 .. method:: stop()
1586
1587 This method can be called to signal that the set of tests being run should
1588 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1589 :class:`TestRunner` objects should respect this flag and return without
1590 running any additional tests.
1591
1592 For example, this feature is used by the :class:`TextTestRunner` class to
1593 stop the test framework when the user signals an interrupt from the
1594 keyboard. Interactive tools which provide :class:`TestRunner`
1595 implementations can use this in a similar manner.
1596
1597 The following methods of the :class:`TestResult` class are used to maintain
1598 the internal data structures, and may be extended in subclasses to support
1599 additional reporting requirements. This is particularly useful in building
1600 tools which support interactive reporting while tests are being run.
1601
1602
1603 .. method:: startTest(test)
1604
1605 Called when the test case *test* is about to be run.
1606
Benjamin Peterson99721e02009-03-23 23:10:14 +00001607 .. method:: stopTest(test)
1608
1609 Called after the test case *test* has been executed, regardless of the
1610 outcome.
1611
Michael Foord07ef4872009-05-02 22:43:34 +00001612 .. method:: startTestRun(test)
1613
1614 Called once before any tests are executed.
1615
1616 .. versionadded:: 2.7
1617
1618
1619 .. method:: stopTestRun(test)
1620
Ezio Melotti7b4e02c2010-01-27 20:25:11 +00001621 Called once after all tests are executed.
Michael Foord07ef4872009-05-02 22:43:34 +00001622
1623 .. versionadded:: 2.7
1624
1625
Benjamin Peterson99721e02009-03-23 23:10:14 +00001626 .. method:: addError(test, err)
1627
1628 Called when the test case *test* raises an unexpected exception *err* is a
1629 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1630 traceback)``.
1631
1632 The default implementation appends a tuple ``(test, formatted_err)`` to
1633 the instance's :attr:`errors` attribute, where *formatted_err* is a
1634 formatted traceback derived from *err*.
1635
1636
1637 .. method:: addFailure(test, err)
1638
Michael Foordb4a81c82009-05-29 20:33:46 +00001639 Called when the test case *test* signals a failure. *err* is a tuple of
1640 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001641
1642 The default implementation appends a tuple ``(test, formatted_err)`` to
1643 the instance's :attr:`failures` attribute, where *formatted_err* is a
1644 formatted traceback derived from *err*.
1645
1646
1647 .. method:: addSuccess(test)
1648
1649 Called when the test case *test* succeeds.
1650
1651 The default implementation does nothing.
1652
1653
1654 .. method:: addSkip(test, reason)
1655
1656 Called when the test case *test* is skipped. *reason* is the reason the
1657 test gave for skipping.
1658
1659 The default implementation appends a tuple ``(test, reason)`` to the
1660 instance's :attr:`skipped` attribute.
1661
1662
1663 .. method:: addExpectedFailure(test, err)
1664
1665 Called when the test case *test* fails, but was marked with the
1666 :func:`expectedFailure` decorator.
1667
1668 The default implementation appends a tuple ``(test, formatted_err)`` to
1669 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1670 is a formatted traceback derived from *err*.
1671
1672
1673 .. method:: addUnexpectedSuccess(test)
1674
1675 Called when the test case *test* was marked with the
1676 :func:`expectedFailure` decorator, but succeeded.
1677
1678 The default implementation appends the test to the instance's
1679 :attr:`unexpectedSuccesses` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001680
Michael Foorddb43b5a2010-02-10 14:25:12 +00001681.. class:: TextTestResult(stream, descriptions, verbosity)
1682
1683 A concrete implementation of :class:`TestResult` used by the
1684 :class:`TextTestRunner`.
1685
1686 .. versionadded:: 2.7
1687 This class was previously named ``_TextTestResult``. The old name still
1688 exists as an alias but is deprecated.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001689
1690.. data:: defaultTestLoader
1691
1692 Instance of the :class:`TestLoader` class intended to be shared. If no
1693 customization of the :class:`TestLoader` is needed, this instance can be used
1694 instead of repeatedly creating new instances.
1695
1696
Michael Foorddb43b5a2010-02-10 14:25:12 +00001697.. class:: TextTestRunner([stream[, descriptions[, verbosity], [resultclass]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001698
1699 A basic test runner implementation which prints results on standard error. It
1700 has a few configurable parameters, but is essentially very simple. Graphical
1701 applications which run test suites should provide alternate implementations.
1702
Georg Brandl9bc66822009-04-27 17:04:23 +00001703 .. method:: _makeResult()
1704
1705 This method returns the instance of ``TestResult`` used by :meth:`run`.
1706 It is not intended to be called directly, but can be overridden in
1707 subclasses to provide a custom ``TestResult``.
1708
Michael Foorddb43b5a2010-02-10 14:25:12 +00001709 ``_makeResult()`` instantiates the class or callable passed in the
1710 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Michael Foordefc2f492010-04-08 04:33:20 +00001711 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foorddb43b5a2010-02-10 14:25:12 +00001712 The result class is instantiated with the following arguments::
1713
1714 stream, descriptions, verbosity
1715
Georg Brandl8ec7f652007-08-15 14:28:01 +00001716
Michael Foordddb20df2010-04-04 23:28:44 +00001717.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit[, verbosity[, failfast[, catchbreak[,buffer]]]]]]]]]])
Michael Foord55430352010-04-05 00:39:50 +00001718
Georg Brandl8ec7f652007-08-15 14:28:01 +00001719 A command-line program that runs a set of tests; this is primarily for making
1720 test modules conveniently executable. The simplest use for this function is to
1721 include the following line at the end of a test script::
1722
1723 if __name__ == '__main__':
1724 unittest.main()
1725
Michael Foord5d31e052009-05-11 17:59:43 +00001726 You can run tests with more detailed information by passing in the verbosity
1727 argument::
1728
1729 if __name__ == '__main__':
1730 unittest.main(verbosity=2)
1731
Georg Brandl8ec7f652007-08-15 14:28:01 +00001732 The *testRunner* argument can either be a test runner class or an already
Michael Foord829f6b82009-05-02 11:43:06 +00001733 created instance of it. By default ``main`` calls :func:`sys.exit` with
1734 an exit code indicating success or failure of the tests run.
1735
1736 ``main`` supports being used from the interactive interpreter by passing in the
1737 argument ``exit=False``. This displays the result on standard output without
1738 calling :func:`sys.exit`::
1739
1740 >>> from unittest import main
1741 >>> main(module='test_module', exit=False)
1742
Michael Foordddb20df2010-04-04 23:28:44 +00001743 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
Éric Araujoa8132ec2010-12-16 03:53:53 +00001744 effect as the same-name `command-line options`_.
Michael Foordddb20df2010-04-04 23:28:44 +00001745
Michael Foord829f6b82009-05-02 11:43:06 +00001746 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1747 This stores the result of the tests run as the ``result`` attribute.
1748
1749 .. versionchanged:: 2.7
Michael Foordddb20df2010-04-04 23:28:44 +00001750 The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
1751 parameters were added.
Michael Foordb4a81c82009-05-29 20:33:46 +00001752
1753
1754load_tests Protocol
1755###################
1756
Michael Foord17565e52009-09-27 20:08:23 +00001757.. versionadded:: 2.7
1758
Michael Foordb4a81c82009-05-29 20:33:46 +00001759Modules or packages can customize how tests are loaded from them during normal
1760test runs or test discovery by implementing a function called ``load_tests``.
1761
1762If a test module defines ``load_tests`` it will be called by
1763:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1764
1765 load_tests(loader, standard_tests, None)
1766
1767It should return a :class:`TestSuite`.
1768
1769*loader* is the instance of :class:`TestLoader` doing the loading.
1770*standard_tests* are the tests that would be loaded by default from the
1771module. It is common for test modules to only want to add or remove tests
1772from the standard set of tests.
1773The third argument is used when loading packages as part of test discovery.
1774
1775A typical ``load_tests`` function that loads tests from a specific set of
1776:class:`TestCase` classes may look like::
1777
1778 test_cases = (TestCase1, TestCase2, TestCase3)
1779
1780 def load_tests(loader, tests, pattern):
1781 suite = TestSuite()
1782 for test_class in test_cases:
1783 tests = loader.loadTestsFromTestCase(test_class)
1784 suite.addTests(tests)
1785 return suite
1786
1787If discovery is started, either from the command line or by calling
1788:meth:`TestLoader.discover`, with a pattern that matches a package
1789name then the package :file:`__init__.py` will be checked for ``load_tests``.
1790
1791.. note::
1792
Ezio Melotti062d2b52009-12-19 22:41:49 +00001793 The default pattern is 'test*.py'. This matches all Python files
Michael Foordb4a81c82009-05-29 20:33:46 +00001794 that start with 'test' but *won't* match any test directories.
1795
1796 A pattern like 'test*' will match test packages as well as
1797 modules.
1798
1799If the package :file:`__init__.py` defines ``load_tests`` then it will be
1800called and discovery not continued into the package. ``load_tests``
1801is called with the following arguments::
1802
1803 load_tests(loader, standard_tests, pattern)
1804
1805This should return a :class:`TestSuite` representing all the tests
1806from the package. (``standard_tests`` will only contain tests
1807collected from :file:`__init__.py`.)
1808
1809Because the pattern is passed into ``load_tests`` the package is free to
1810continue (and potentially modify) test discovery. A 'do nothing'
1811``load_tests`` function for a test package would look like::
1812
1813 def load_tests(loader, standard_tests, pattern):
1814 # top level directory cached on loader instance
1815 this_dir = os.path.dirname(__file__)
1816 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1817 standard_tests.addTests(package_tests)
1818 return standard_tests
Michael Foordba097ec2010-04-03 17:03:11 +00001819
1820
1821Class and Module Fixtures
1822-------------------------
1823
Michael Foord09e29802010-04-04 22:41:54 +00001824Class and module level fixtures are implemented in :class:`TestSuite`. When
1825the test suite encounters a test from a new class then :meth:`tearDownClass`
1826from the previous class (if there is one) is called, followed by
1827:meth:`setUpClass` from the new class.
Michael Foordba097ec2010-04-03 17:03:11 +00001828
Michael Foord09e29802010-04-04 22:41:54 +00001829Similarly if a test is from a different module from the previous test then
1830``tearDownModule`` from the previous module is run, followed by
1831``setUpModule`` from the new module.
Michael Foordba097ec2010-04-03 17:03:11 +00001832
Michael Foord09e29802010-04-04 22:41:54 +00001833After all the tests have run the final ``tearDownClass`` and
1834``tearDownModule`` are run.
Michael Foordba097ec2010-04-03 17:03:11 +00001835
Michael Foord09e29802010-04-04 22:41:54 +00001836Note that shared fixtures do not play well with [potential] features like test
1837parallelization and they break test isolation. They should be used with care.
Michael Foordba097ec2010-04-03 17:03:11 +00001838
Michael Foord09e29802010-04-04 22:41:54 +00001839The default ordering of tests created by the unittest test loaders is to group
1840all tests from the same modules and classes together. This will lead to
1841``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
1842module. If you randomize the order, so that tests from different modules and
1843classes are adjacent to each other, then these shared fixture functions may be
1844called multiple times in a single test run.
Michael Foordba097ec2010-04-03 17:03:11 +00001845
Michael Foord09e29802010-04-04 22:41:54 +00001846Shared fixtures are not intended to work with suites with non-standard
1847ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
1848support shared fixtures.
Michael Foordba097ec2010-04-03 17:03:11 +00001849
Michael Foord09e29802010-04-04 22:41:54 +00001850If there are any exceptions raised during one of the shared fixture functions
1851the test is reported as an error. Because there is no corresponding test
1852instance an ``_ErrorHolder`` object (that has the same interface as a
1853:class:`TestCase`) is created to represent the error. If you are just using
1854the standard unittest test runner then this detail doesn't matter, but if you
1855are a framework author it may be relevant.
Michael Foordba097ec2010-04-03 17:03:11 +00001856
1857
1858setUpClass and tearDownClass
1859~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1860
1861These must be implemented as class methods::
1862
1863 import unittest
1864
1865 class Test(unittest.TestCase):
1866 @classmethod
1867 def setUpClass(cls):
1868 cls._connection = createExpensiveConnectionObject()
1869
1870 @classmethod
1871 def tearDownClass(cls):
1872 cls._connection.destroy()
1873
Michael Foord09e29802010-04-04 22:41:54 +00001874If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
1875then you must call up to them yourself. The implementations in
1876:class:`TestCase` are empty.
Michael Foordba097ec2010-04-03 17:03:11 +00001877
Michael Foord09e29802010-04-04 22:41:54 +00001878If an exception is raised during a ``setUpClass`` then the tests in the class
1879are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord8dde2012010-06-05 21:57:03 +00001880have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
1881``SkipTest`` exception then the class will be reported as having been skipped
1882instead of as an error.
Michael Foordba097ec2010-04-03 17:03:11 +00001883
1884
1885setUpModule and tearDownModule
1886~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1887
1888These should be implemented as functions::
1889
1890 def setUpModule():
1891 createConnection()
1892
1893 def tearDownModule():
1894 closeConnection()
1895
Michael Foord09e29802010-04-04 22:41:54 +00001896If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord8dde2012010-06-05 21:57:03 +00001897module will be run and the ``tearDownModule`` will not be run. If the exception is a
1898``SkipTest`` exception then the module will be reported as having been skipped
1899instead of as an error.
Michael Foordba097ec2010-04-03 17:03:11 +00001900
1901
Michael Foord55430352010-04-05 00:39:50 +00001902Signal Handling
1903---------------
1904
Éric Araujoa8132ec2010-12-16 03:53:53 +00001905The :option:`-c/--catch <unittest -c>` command-line option to unittest,
1906along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
1907more friendly handling of control-C during a test run. With catch break
1908behavior enabled control-C will allow the currently running test to complete,
1909and the test run will then end and report all the results so far. A second
1910control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Michael Foord55430352010-04-05 00:39:50 +00001911
Michael Foord5c322ec2010-04-25 19:02:46 +00001912The control-c handling signal handler attempts to remain compatible with code or
1913tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
1914handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
1915i.e. it has been replaced by the system under test and delegated to, then it
1916calls the default handler. This will normally be the expected behavior by code
1917that replaces an installed handler and delegates to it. For individual tests
1918that need ``unittest`` control-c handling disabled the :func:`removeHandler`
1919decorator can be used.
1920
1921There are a few utility functions for framework authors to enable control-c
1922handling functionality within test frameworks.
Michael Foord55430352010-04-05 00:39:50 +00001923
1924.. function:: installHandler()
1925
Michael Foord31655032010-04-05 10:26:26 +00001926 Install the control-c handler. When a :const:`signal.SIGINT` is received
1927 (usually in response to the user pressing control-c) all registered results
Michael Foord55430352010-04-05 00:39:50 +00001928 have :meth:`~TestResult.stop` called.
1929
Michael Foord47b54402010-04-26 23:36:47 +00001930 .. versionadded:: 2.7
1931
Michael Foord55430352010-04-05 00:39:50 +00001932.. function:: registerResult(result)
1933
Michael Foord31655032010-04-05 10:26:26 +00001934 Register a :class:`TestResult` object for control-c handling. Registering a
Michael Foord55430352010-04-05 00:39:50 +00001935 result stores a weak reference to it, so it doesn't prevent the result from
1936 being garbage collected.
1937
Michael Foord5c322ec2010-04-25 19:02:46 +00001938 Registering a :class:`TestResult` object has no side-effects if control-c
1939 handling is not enabled, so test frameworks can unconditionally register
1940 all results they create independently of whether or not handling is enabled.
1941
Michael Foord47b54402010-04-26 23:36:47 +00001942 .. versionadded:: 2.7
1943
Michael Foord55430352010-04-05 00:39:50 +00001944.. function:: removeResult(result)
1945
Michael Foord31655032010-04-05 10:26:26 +00001946 Remove a registered result. Once a result has been removed then
Michael Foordd341ec82010-04-05 10:30:14 +00001947 :meth:`~TestResult.stop` will no longer be called on that result object in
Michael Foord31655032010-04-05 10:26:26 +00001948 response to a control-c.
Michael Foord55430352010-04-05 00:39:50 +00001949
Michael Foord47b54402010-04-26 23:36:47 +00001950 .. versionadded:: 2.7
1951
Michael Foord5c322ec2010-04-25 19:02:46 +00001952.. function:: removeHandler(function=None)
1953
1954 When called without arguments this function removes the control-c handler
1955 if it has been installed. This function can also be used as a test decorator
1956 to temporarily remove the handler whilst the test is being executed::
1957
1958 @unittest.removeHandler
1959 def test_signal_handling(self):
1960 ...
1961
Michael Foord47b54402010-04-26 23:36:47 +00001962 .. versionadded:: 2.7
1963