blob: 15765f5ed58892074b5d2289423fc3f122efa648 [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
Georg Brandl8ec7f652007-08-15 14:28:01 +000011.. versionadded:: 2.1
Benjamin Peterson692428e2009-03-23 21:50:21 +000012
Ezio Melottidd7c5932011-03-10 23:00:48 +020013(If you are already familiar with the basic concepts of testing, you might want
14to skip to :ref:`the list of assert methods <assert-methods>`.)
15
Georg Brandl8ec7f652007-08-15 14:28:01 +000016The Python unit testing framework, sometimes referred to as "PyUnit," is a
17Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
18turn, a Java version of Kent's Smalltalk testing framework. Each is the de
19facto standard unit testing framework for its respective language.
20
21:mod:`unittest` supports test automation, sharing of setup and shutdown code for
22tests, aggregation of tests into collections, and independence of the tests from
23the reporting framework. The :mod:`unittest` module provides classes that make
24it easy to support these qualities for a set of tests.
25
26To achieve this, :mod:`unittest` supports some important concepts:
27
28test fixture
29 A :dfn:`test fixture` represents the preparation needed to perform one or more
30 tests, and any associate cleanup actions. This may involve, for example,
31 creating temporary or proxy databases, directories, or starting a server
32 process.
33
34test case
35 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
36 response to a particular set of inputs. :mod:`unittest` provides a base class,
37 :class:`TestCase`, which may be used to create new test cases.
38
39test suite
40 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
41 used to aggregate tests that should be executed together.
42
43test runner
44 A :dfn:`test runner` is a component which orchestrates the execution of tests
45 and provides the outcome to the user. The runner may use a graphical interface,
46 a textual interface, or return a special value to indicate the results of
47 executing the tests.
48
49The test case and test fixture concepts are supported through the
50:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
51used when creating new tests, and the latter can be used when integrating
52existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson99721e02009-03-23 23:10:14 +000053fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
54:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
55and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
56can be passed to the constructor for these purposes. When the test is run, the
57fixture initialization is run first; if it succeeds, the cleanup method is run
58after the test has been executed, regardless of the outcome of the test. Each
59instance of the :class:`TestCase` will only be used to run a single test method,
60so a new fixture is created for each test.
Georg Brandl8ec7f652007-08-15 14:28:01 +000061
62Test suites are implemented by the :class:`TestSuite` class. This class allows
63individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson176a56c2009-05-25 00:48:58 +000064all tests added directly to the suite and in "child" test suites are run.
Georg Brandl8ec7f652007-08-15 14:28:01 +000065
Benjamin Peterson99721e02009-03-23 23:10:14 +000066A test runner is an object that provides a single method,
67:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
68object as a parameter, and returns a result object. The class
69:class:`TestResult` is provided for use as the result object. :mod:`unittest`
70provides the :class:`TextTestRunner` as an example test runner which reports
71test results on the standard error stream by default. Alternate runners can be
72implemented for other environments (such as graphical environments) without any
73need to derive from a specific class.
Georg Brandl8ec7f652007-08-15 14:28:01 +000074
75
76.. seealso::
77
78 Module :mod:`doctest`
79 Another test-support module with a very different flavor.
80
Georg Brandl06f3b3b2014-10-29 08:36:35 +010081 `unittest2: A backport of new unittest features for Python 2.4-2.6 <https://pypi.python.org/pypi/unittest2>`_
Michael Foordba097ec2010-04-03 17:03:11 +000082 Many new features were added to unittest in Python 2.7, including test
83 discovery. unittest2 allows you to use these features with earlier
84 versions of Python.
85
R David Murray39954212015-07-04 15:50:30 -040086 `Simple Smalltalk Testing: With Patterns <https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm>`_
Georg Brandl2fcd1732009-05-30 10:45:40 +000087 Kent Beck's original paper on testing frameworks using the pattern shared
88 by :mod:`unittest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000089
Berker Peksag87d415f2014-12-28 18:51:25 +020090 `Nose <https://nose.readthedocs.org/en/latest/>`_ and `py.test <http://pytest.org>`_
Georg Brandl2fcd1732009-05-30 10:45:40 +000091 Third-party unittest frameworks with a lighter-weight syntax for writing
92 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger21b617b2009-03-24 00:17:11 +000093
Georg Brandl06f3b3b2014-10-29 08:36:35 +010094 `The Python Testing Tools Taxonomy <https://wiki.python.org/moin/PythonTestingToolsTaxonomy>`_
Michael Foordba097ec2010-04-03 17:03:11 +000095 An extensive list of Python testing tools including functional testing
96 frameworks and mock object libraries.
Georg Brandl8ec7f652007-08-15 14:28:01 +000097
Michael Foordba097ec2010-04-03 17:03:11 +000098 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
99 A special-interest-group for discussion of testing, and testing tools,
100 in Python.
Michael Foordb4a81c82009-05-29 20:33:46 +0000101
Michael Foord5d31e052009-05-11 17:59:43 +0000102
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103.. _unittest-minimal-example:
104
105Basic example
106-------------
107
108The :mod:`unittest` module provides a rich set of tools for constructing and
109running tests. This section demonstrates that a small subset of the tools
110suffice to meet the needs of most users.
111
Ezio Melottibc1fda32015-03-24 12:42:41 +0200112Here is a short script to test three string methods::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000113
Ezio Melottibc1fda32015-03-24 12:42:41 +0200114 import unittest
Georg Brandl8ec7f652007-08-15 14:28:01 +0000115
Ezio Melottibc1fda32015-03-24 12:42:41 +0200116 class TestStringMethods(unittest.TestCase):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000117
Serhiy Storchaka12d547a2016-05-10 13:45:32 +0300118 def test_upper(self):
119 self.assertEqual('foo'.upper(), 'FOO')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000120
Serhiy Storchaka12d547a2016-05-10 13:45:32 +0300121 def test_isupper(self):
122 self.assertTrue('FOO'.isupper())
123 self.assertFalse('Foo'.isupper())
Georg Brandl8ec7f652007-08-15 14:28:01 +0000124
Serhiy Storchaka12d547a2016-05-10 13:45:32 +0300125 def test_split(self):
126 s = 'hello world'
127 self.assertEqual(s.split(), ['hello', 'world'])
128 # check that s.split fails when the separator is not a string
129 with self.assertRaises(TypeError):
130 s.split(2)
Raymond Hettinger08090bf2010-03-09 08:44:18 +0000131
Ezio Melottibc1fda32015-03-24 12:42:41 +0200132 if __name__ == '__main__':
133 unittest.main()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000134
Georg Brandl8ec7f652007-08-15 14:28:01 +0000135
Benjamin Peterson99721e02009-03-23 23:10:14 +0000136A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl8ec7f652007-08-15 14:28:01 +0000137individual tests are defined with methods whose names start with the letters
138``test``. This naming convention informs the test runner about which methods
139represent tests.
140
Benjamin Peterson99721e02009-03-23 23:10:14 +0000141The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Ezio Melottibc1fda32015-03-24 12:42:41 +0200142expected result; :meth:`~TestCase.assertTrue` or :meth:`~TestCase.assertFalse`
143to verify a condition; or :meth:`~TestCase.assertRaises` to verify that a
144specific exception gets raised. These methods are used instead of the
145:keyword:`assert` statement so the test runner can accumulate all test results
146and produce a report.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000147
Ezio Melottibc1fda32015-03-24 12:42:41 +0200148The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you
149to define instructions that will be executed before and after each test method.
Benjamin Petersonc6fa90c2016-01-07 22:01:26 -0800150They are covered in more detail in the section :ref:`organizing-tests`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151
152The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujoa8132ec2010-12-16 03:53:53 +0000153provides a command-line interface to the test script. When run from the command
Georg Brandl8ec7f652007-08-15 14:28:01 +0000154line, the above script produces an output that looks like this::
155
156 ...
157 ----------------------------------------------------------------------
158 Ran 3 tests in 0.000s
159
160 OK
161
162Instead of :func:`unittest.main`, there are other ways to run the tests with a
163finer level of control, less terse output, and no requirement to be run from the
164command line. For example, the last two lines may be replaced with::
165
Ezio Melottibc1fda32015-03-24 12:42:41 +0200166 suite = unittest.TestLoader().loadTestsFromTestCase(TestStringMethods)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000167 unittest.TextTestRunner(verbosity=2).run(suite)
168
169Running the revised script from the interpreter or another script produces the
170following output::
171
Ezio Melottibc1fda32015-03-24 12:42:41 +0200172 test_isupper (__main__.TestStringMethods) ... ok
173 test_split (__main__.TestStringMethods) ... ok
174 test_upper (__main__.TestStringMethods) ... ok
Georg Brandl8ec7f652007-08-15 14:28:01 +0000175
176 ----------------------------------------------------------------------
Ezio Melottibc1fda32015-03-24 12:42:41 +0200177 Ran 3 tests in 0.001s
Georg Brandl8ec7f652007-08-15 14:28:01 +0000178
179 OK
180
181The above examples show the most commonly used :mod:`unittest` features which
182are sufficient to meet many everyday testing needs. The remainder of the
183documentation explores the full feature set from first principles.
184
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000185
186.. _unittest-command-line-interface:
187
Ezio Melottic3ab30b2011-03-12 22:21:37 +0200188Command-Line Interface
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000189----------------------
190
191The unittest module can be used from the command line to run tests from
192modules, classes or even individual test methods::
193
194 python -m unittest test_module1 test_module2
195 python -m unittest test_module.TestClass
196 python -m unittest test_module.TestClass.test_method
197
198You can pass in a list with any combination of module names, and fully
199qualified class or method names.
200
201You can run tests with more detail (higher verbosity) by passing in the -v flag::
202
Ezio Melotti062d2b52009-12-19 22:41:49 +0000203 python -m unittest -v test_module
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000204
Éric Araujoa8132ec2010-12-16 03:53:53 +0000205For a list of all the command-line options::
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000206
207 python -m unittest -h
208
209.. versionchanged:: 2.7
210 In earlier versions it was only possible to run individual test methods and
211 not modules or classes.
212
Michael Foordba097ec2010-04-03 17:03:11 +0000213
Éric Araujoa8132ec2010-12-16 03:53:53 +0000214Command-line options
215~~~~~~~~~~~~~~~~~~~~
Michael Foordba097ec2010-04-03 17:03:11 +0000216
Éric Araujoa8132ec2010-12-16 03:53:53 +0000217:program:`unittest` supports these command-line options:
Michael Foordba097ec2010-04-03 17:03:11 +0000218
Éric Araujoa8132ec2010-12-16 03:53:53 +0000219.. program:: unittest
Michael Foordba097ec2010-04-03 17:03:11 +0000220
Éric Araujoa8132ec2010-12-16 03:53:53 +0000221.. cmdoption:: -b, --buffer
Michael Foordba097ec2010-04-03 17:03:11 +0000222
Éric Araujoa8132ec2010-12-16 03:53:53 +0000223 The standard output and standard error streams are buffered during the test
224 run. Output during a passing test is discarded. Output is echoed normally
225 on test fail or error and is added to the failure messages.
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000226
Éric Araujoa8132ec2010-12-16 03:53:53 +0000227.. cmdoption:: -c, --catch
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000228
Serhiy Storchaka9b2e37f2015-09-12 17:47:12 +0300229 :kbd:`Control-C` during the test run waits for the current test to end and then
230 reports all the results so far. A second :kbd:`Control-C` raises the normal
Éric Araujoa8132ec2010-12-16 03:53:53 +0000231 :exc:`KeyboardInterrupt` exception.
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000232
Éric Araujoa8132ec2010-12-16 03:53:53 +0000233 See `Signal Handling`_ for the functions that provide this functionality.
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000234
Éric Araujoa8132ec2010-12-16 03:53:53 +0000235.. cmdoption:: -f, --failfast
Andrew M. Kuchlingfb759a22010-04-29 01:44:30 +0000236
Éric Araujoa8132ec2010-12-16 03:53:53 +0000237 Stop the test run on the first error or failure.
238
239.. versionadded:: 2.7
240 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Michael Foordba097ec2010-04-03 17:03:11 +0000241
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000242The command line can also be used for test discovery, for running all of the
243tests in a project or just a subset.
244
245
246.. _unittest-test-discovery:
247
248Test Discovery
249--------------
250
251.. versionadded:: 2.7
252
Ezio Melotti9e1ed472011-03-08 17:08:25 +0200253Unittest supports simple test discovery. In order to be compatible with test
254discovery, all of the test files must be :ref:`modules <tut-modules>` or
255:ref:`packages <tut-packages>` importable from the top-level directory of
256the project (this means that their filenames must be valid
257:ref:`identifiers <identifiers>`).
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000258
259Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujoa8132ec2010-12-16 03:53:53 +0000260used from the command line. The basic command-line usage is::
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000261
262 cd project_directory
263 python -m unittest discover
264
265The ``discover`` sub-command has the following options:
266
Éric Araujoa8132ec2010-12-16 03:53:53 +0000267.. program:: unittest discover
268
269.. cmdoption:: -v, --verbose
270
271 Verbose output
272
Chris Jerdonek13cee162013-02-21 18:52:12 -0800273.. cmdoption:: -s, --start-directory directory
Éric Araujoa8132ec2010-12-16 03:53:53 +0000274
Chris Jerdonek13cee162013-02-21 18:52:12 -0800275 Directory to start discovery (``.`` default)
Éric Araujoa8132ec2010-12-16 03:53:53 +0000276
Chris Jerdonek13cee162013-02-21 18:52:12 -0800277.. cmdoption:: -p, --pattern pattern
Éric Araujoa8132ec2010-12-16 03:53:53 +0000278
Chris Jerdonek13cee162013-02-21 18:52:12 -0800279 Pattern to match test files (``test*.py`` default)
Éric Araujoa8132ec2010-12-16 03:53:53 +0000280
Chris Jerdonek13cee162013-02-21 18:52:12 -0800281.. cmdoption:: -t, --top-level-directory directory
Éric Araujoa8132ec2010-12-16 03:53:53 +0000282
283 Top level directory of project (defaults to start directory)
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000284
Andrew M. Kuchling60383182010-04-30 01:32:47 +0000285The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
286as positional arguments in that order. The following two command lines
287are equivalent::
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000288
Robert Collins11ac1a82015-08-24 12:06:18 +1200289 python -m unittest discover -s project_directory -p "*_test.py"
290 python -m unittest discover project_directory "*_test.py"
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000291
Michael Foord8851b712010-05-08 15:09:37 +0000292As well as being a path it is possible to pass a package name, for example
293``myproject.subpackage.test``, as the start directory. The package name you
294supply will then be imported and its location on the filesystem will be used
295as the start directory.
296
297.. caution::
298
299 Test discovery loads tests by importing them. Once test discovery has
300 found all the test files from the start directory you specify it turns the
Éric Araujoa7cbe282011-09-01 19:49:31 +0200301 paths into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord8851b712010-05-08 15:09:37 +0000302 imported as ``foo.bar.baz``.
303
304 If you have a package installed globally and attempt test discovery on
305 a different copy of the package then the import *could* happen from the
306 wrong place. If this happens test discovery will warn you and exit.
307
308 If you supply the start directory as a package name rather than a
309 path to a directory then discover assumes that whichever location it
310 imports from is the location you intended, so you will not get the
311 warning.
312
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000313Test modules and packages can customize test loading and discovery by through
314the `load_tests protocol`_.
315
316
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317.. _organizing-tests:
318
319Organizing test code
320--------------------
321
322The basic building blocks of unit testing are :dfn:`test cases` --- single
323scenarios that must be set up and checked for correctness. In :mod:`unittest`,
324test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
325class. To make your own test cases you must write subclasses of
326:class:`TestCase`, or use :class:`FunctionTestCase`.
327
328An instance of a :class:`TestCase`\ -derived class is an object that can
329completely run a single test method, together with optional set-up and tidy-up
330code.
331
332The testing code of a :class:`TestCase` instance should be entirely self
333contained, such that it can be run either in isolation or in arbitrary
334combination with any number of other test cases.
335
Benjamin Peterson99721e02009-03-23 23:10:14 +0000336The simplest :class:`TestCase` subclass will simply override the
337:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000338
339 import unittest
340
341 class DefaultWidgetSizeTestCase(unittest.TestCase):
342 def runTest(self):
343 widget = Widget('The widget')
344 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
345
Sandro Tosi2d71e5c2012-01-21 10:59:12 +0100346Note that in order to test something, we use one of the :meth:`assert\*`
Georg Brandl2fcd1732009-05-30 10:45:40 +0000347methods provided by the :class:`TestCase` base class. If the test fails, an
348exception will be raised, and :mod:`unittest` will identify the test case as a
349:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
350helps you identify where the problem is: :dfn:`failures` are caused by incorrect
351results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
352code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000353
354The way to run a test case will be described later. For now, note that to
355construct an instance of such a test case, we call its constructor without
356arguments::
357
358 testCase = DefaultWidgetSizeTestCase()
359
360Now, such test cases can be numerous, and their set-up can be repetitive. In
361the above case, constructing a :class:`Widget` in each of 100 Widget test case
362subclasses would mean unsightly duplication.
363
364Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson99721e02009-03-23 23:10:14 +0000365:meth:`~TestCase.setUp`, which the testing framework will automatically call for
366us when we run the test::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000367
368 import unittest
369
370 class SimpleWidgetTestCase(unittest.TestCase):
371 def setUp(self):
372 self.widget = Widget('The widget')
373
374 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
375 def runTest(self):
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000376 self.assertEqual(self.widget.size(), (50,50),
377 'incorrect default size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000378
379 class WidgetResizeTestCase(SimpleWidgetTestCase):
380 def runTest(self):
381 self.widget.resize(100,150)
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000382 self.assertEqual(self.widget.size(), (100,150),
383 'wrong size after resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000384
Benjamin Peterson99721e02009-03-23 23:10:14 +0000385If the :meth:`~TestCase.setUp` method raises an exception while the test is
386running, the framework will consider the test to have suffered an error, and the
387:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000388
Benjamin Peterson99721e02009-03-23 23:10:14 +0000389Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
390after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000391
392 import unittest
393
394 class SimpleWidgetTestCase(unittest.TestCase):
395 def setUp(self):
396 self.widget = Widget('The widget')
397
398 def tearDown(self):
399 self.widget.dispose()
400 self.widget = None
401
Benjamin Peterson99721e02009-03-23 23:10:14 +0000402If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
403be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000404
405Such a working environment for the testing code is called a :dfn:`fixture`.
406
407Often, many small test cases will use the same fixture. In this case, we would
408end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
409classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000410discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
411mechanism::
412
413 import unittest
414
415 class WidgetTestCase(unittest.TestCase):
416 def setUp(self):
417 self.widget = Widget('The widget')
418
419 def tearDown(self):
420 self.widget.dispose()
421 self.widget = None
422
Ezio Melotti68beef62010-02-28 03:11:07 +0000423 def test_default_size(self):
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000424 self.assertEqual(self.widget.size(), (50,50),
425 'incorrect default size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000426
Ezio Melotti68beef62010-02-28 03:11:07 +0000427 def test_resize(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000428 self.widget.resize(100,150)
Ezio Melotti85ee3e12010-02-04 20:06:38 +0000429 self.assertEqual(self.widget.size(), (100,150),
430 'wrong size after resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000431
Benjamin Peterson99721e02009-03-23 23:10:14 +0000432Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
433provided two different test methods. Class instances will now each run one of
Ezio Melotti68beef62010-02-28 03:11:07 +0000434the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson99721e02009-03-23 23:10:14 +0000435separately for each instance. When creating an instance we must specify the
436test method it is to run. We do this by passing the method name in the
437constructor::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000438
Ezio Melotti68beef62010-02-28 03:11:07 +0000439 defaultSizeTestCase = WidgetTestCase('test_default_size')
440 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000441
442Test case instances are grouped together according to the features they test.
443:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
444represented by :mod:`unittest`'s :class:`TestSuite` class::
445
446 widgetTestSuite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000447 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
448 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000449
450For the ease of running tests, as we will see later, it is a good idea to
451provide in each test module a callable object that returns a pre-built test
452suite::
453
454 def suite():
455 suite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000456 suite.addTest(WidgetTestCase('test_default_size'))
457 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000458 return suite
459
460or even::
461
462 def suite():
Ezio Melotti68beef62010-02-28 03:11:07 +0000463 tests = ['test_default_size', 'test_resize']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000464
465 return unittest.TestSuite(map(WidgetTestCase, tests))
466
467Since it is a common pattern to create a :class:`TestCase` subclass with many
468similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
469class that can be used to automate the process of creating a test suite and
470populating it with individual tests. For example, ::
471
472 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
473
Ezio Melotti68beef62010-02-28 03:11:07 +0000474will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
475``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl8ec7f652007-08-15 14:28:01 +0000476name prefix to identify test methods automatically.
477
Ezio Melottidd7c5932011-03-10 23:00:48 +0200478Note that the order in which the various test cases will be run is
479determined by sorting the test function names with respect to the
480built-in ordering for strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000481
482Often it is desirable to group suites of test cases together, so as to run tests
483for the whole system at once. This is easy, since :class:`TestSuite` instances
484can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
485added to a :class:`TestSuite`::
486
487 suite1 = module1.TheTestSuite()
488 suite2 = module2.TheTestSuite()
489 alltests = unittest.TestSuite([suite1, suite2])
490
491You can place the definitions of test cases and test suites in the same modules
492as the code they are to test (such as :file:`widget.py`), but there are several
493advantages to placing the test code in a separate module, such as
494:file:`test_widget.py`:
495
496* The test module can be run standalone from the command line.
497
498* The test code can more easily be separated from shipped code.
499
500* There is less temptation to change test code to fit the code it tests without
501 a good reason.
502
503* Test code should be modified much less frequently than the code it tests.
504
505* Tested code can be refactored more easily.
506
507* Tests for modules written in C must be in separate modules anyway, so why not
508 be consistent?
509
510* If the testing strategy changes, there is no need to change the source code.
511
512
513.. _legacy-unit-tests:
514
515Re-using old test code
516----------------------
517
518Some users will find that they have existing test code that they would like to
519run from :mod:`unittest`, without converting every old test function to a
520:class:`TestCase` subclass.
521
522For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
523This subclass of :class:`TestCase` can be used to wrap an existing test
524function. Set-up and tear-down functions can also be provided.
525
526Given the following test function::
527
528 def testSomething():
529 something = makeSomething()
530 assert something.name is not None
531 # ...
532
533one can create an equivalent test case instance as follows::
534
535 testcase = unittest.FunctionTestCase(testSomething)
536
537If there are additional set-up and tear-down methods that should be called as
538part of the test case's operation, they can also be provided like so::
539
540 testcase = unittest.FunctionTestCase(testSomething,
541 setUp=makeSomethingDB,
542 tearDown=deleteSomethingDB)
543
544To make migrating existing test suites easier, :mod:`unittest` supports tests
545raising :exc:`AssertionError` to indicate test failure. However, it is
546recommended that you use the explicit :meth:`TestCase.fail\*` and
547:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
548may treat :exc:`AssertionError` differently.
549
550.. note::
551
Georg Brandl2fcd1732009-05-30 10:45:40 +0000552 Even though :class:`FunctionTestCase` can be used to quickly convert an
553 existing test base over to a :mod:`unittest`\ -based system, this approach is
554 not recommended. Taking the time to set up proper :class:`TestCase`
555 subclasses will make future test refactorings infinitely easier.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000556
Benjamin Peterson99721e02009-03-23 23:10:14 +0000557In some cases, the existing tests may have been written using the :mod:`doctest`
558module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
559automatically build :class:`unittest.TestSuite` instances from the existing
560:mod:`doctest`\ -based tests.
561
Georg Brandl8ec7f652007-08-15 14:28:01 +0000562
Benjamin Peterson692428e2009-03-23 21:50:21 +0000563.. _unittest-skipping:
564
565Skipping tests and expected failures
566------------------------------------
567
Michael Foordfb0844b2010-02-05 21:45:12 +0000568.. versionadded:: 2.7
569
Benjamin Peterson692428e2009-03-23 21:50:21 +0000570Unittest supports skipping individual test methods and even whole classes of
Serhiy Storchakac72e66a2015-11-02 15:06:09 +0200571tests. In addition, it supports marking a test as an "expected failure," a test
Benjamin Peterson692428e2009-03-23 21:50:21 +0000572that is broken and will fail, but shouldn't be counted as a failure on a
573:class:`TestResult`.
574
575Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
576or one of its conditional variants.
577
Ezio Melottiff0deb02013-03-01 21:26:04 +0200578Basic skipping looks like this::
Benjamin Peterson692428e2009-03-23 21:50:21 +0000579
580 class MyTestCase(unittest.TestCase):
581
582 @unittest.skip("demonstrating skipping")
583 def test_nothing(self):
584 self.fail("shouldn't happen")
585
Georg Brandl2fcd1732009-05-30 10:45:40 +0000586 @unittest.skipIf(mylib.__version__ < (1, 3),
587 "not supported in this library version")
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000588 def test_format(self):
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000589 # Tests that work for only a certain version of the library.
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000590 pass
591
592 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
593 def test_windows_support(self):
594 # windows specific testing code
595 pass
596
Ezio Melottiff0deb02013-03-01 21:26:04 +0200597This is the output of running the example above in verbose mode::
Benjamin Peterson692428e2009-03-23 21:50:21 +0000598
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000599 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000600 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000601 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000602
603 ----------------------------------------------------------------------
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000604 Ran 3 tests in 0.005s
605
606 OK (skipped=3)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000607
Ezio Melottiff0deb02013-03-01 21:26:04 +0200608Classes can be skipped just like methods::
Benjamin Peterson692428e2009-03-23 21:50:21 +0000609
Sandro Tosi6ca845c2012-03-31 18:34:42 +0200610 @unittest.skip("showing class skipping")
Benjamin Peterson692428e2009-03-23 21:50:21 +0000611 class MySkippedTestCase(unittest.TestCase):
612 def test_not_run(self):
613 pass
614
Benjamin Peterson31b78062009-03-23 23:13:36 +0000615:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
616that needs to be set up is not available.
617
Benjamin Peterson692428e2009-03-23 21:50:21 +0000618Expected failures use the :func:`expectedFailure` decorator. ::
619
620 class ExpectedFailureTestCase(unittest.TestCase):
621 @unittest.expectedFailure
622 def test_fail(self):
623 self.assertEqual(1, 0, "broken")
624
625It's easy to roll your own skipping decorators by making a decorator that calls
626:func:`skip` on the test when it wants it to be skipped. This decorator skips
Ezio Melottiff0deb02013-03-01 21:26:04 +0200627the test unless the passed object has a certain attribute::
Benjamin Peterson692428e2009-03-23 21:50:21 +0000628
629 def skipUnlessHasattr(obj, attr):
630 if hasattr(obj, attr):
631 return lambda func: func
Ezio Melotti352def02013-03-27 20:11:55 +0200632 return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
Benjamin Peterson692428e2009-03-23 21:50:21 +0000633
634The following decorators implement test skipping and expected failures:
635
636.. function:: skip(reason)
637
638 Unconditionally skip the decorated test. *reason* should describe why the
639 test is being skipped.
640
641.. function:: skipIf(condition, reason)
642
643 Skip the decorated test if *condition* is true.
644
645.. function:: skipUnless(condition, reason)
646
Georg Brandl09302282010-10-06 09:32:48 +0000647 Skip the decorated test unless *condition* is true.
Benjamin Peterson692428e2009-03-23 21:50:21 +0000648
649.. function:: expectedFailure
650
651 Mark the test as an expected failure. If the test fails when run, the test
652 is not counted as a failure.
653
Ezio Melotti352def02013-03-27 20:11:55 +0200654.. exception:: SkipTest(reason)
655
656 This exception is raised to skip a test.
657
658 Usually you can use :meth:`TestCase.skipTest` or one of the skipping
659 decorators instead of raising this directly.
660
Michael Foord09e29802010-04-04 22:41:54 +0000661Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
662Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
Michael Foordba097ec2010-04-03 17:03:11 +0000663
Benjamin Peterson692428e2009-03-23 21:50:21 +0000664
Georg Brandl8ec7f652007-08-15 14:28:01 +0000665.. _unittest-contents:
666
667Classes and functions
668---------------------
669
Benjamin Peterson99721e02009-03-23 23:10:14 +0000670This section describes in depth the API of :mod:`unittest`.
671
672
673.. _testcase-objects:
674
675Test cases
676~~~~~~~~~~
Georg Brandl8ec7f652007-08-15 14:28:01 +0000677
Ezio Melottidd7c5932011-03-10 23:00:48 +0200678.. class:: TestCase(methodName='runTest')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000679
680 Instances of the :class:`TestCase` class represent the smallest testable units
681 in the :mod:`unittest` universe. This class is intended to be used as a base
682 class, with specific tests being implemented by concrete subclasses. This class
683 implements the interface needed by the test runner to allow it to drive the
684 test, and methods that the test code can use to check for and report various
685 kinds of failure.
686
687 Each instance of :class:`TestCase` will run a single test method: the method
688 named *methodName*. If you remember, we had an earlier example that went
689 something like this::
690
691 def suite():
692 suite = unittest.TestSuite()
Ezio Melotti68beef62010-02-28 03:11:07 +0000693 suite.addTest(WidgetTestCase('test_default_size'))
694 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000695 return suite
696
697 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
698 single test.
699
Benjamin Peterson99721e02009-03-23 23:10:14 +0000700 *methodName* defaults to :meth:`runTest`.
701
702 :class:`TestCase` instances provide three groups of methods: one group used
703 to run the test, another used by the test implementation to check conditions
704 and report failures, and some inquiry methods allowing information about the
705 test itself to be gathered.
706
707 Methods in the first group (running the test) are:
708
709
710 .. method:: setUp()
711
712 Method called to prepare the test fixture. This is called immediately
Terry Jan Reedy0d1e44b2014-04-15 23:44:10 -0400713 before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`,
714 any exception raised by this method will be considered an error rather than
Terry Jan Reedye804efa2014-04-15 23:38:11 -0400715 a test failure. The default implementation does nothing.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000716
717
718 .. method:: tearDown()
719
720 Method called immediately after the test method has been called and the
721 result recorded. This is called even if the test method raised an
722 exception, so the implementation in subclasses may need to be particularly
Ezio Melotti60662572016-03-13 09:40:09 +0200723 careful about checking internal state. Any exception, other than
724 :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
725 considered an additional error rather than a test failure (thus increasing
726 the total number of reported errors). This method will only be called if
727 the :meth:`setUp` succeeds, regardless of the outcome of the test method.
728 The default implementation does nothing.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000729
730
Michael Foordba097ec2010-04-03 17:03:11 +0000731 .. method:: setUpClass()
732
733 A class method called before tests in an individual class run.
734 ``setUpClass`` is called with the class as the only argument
Michael Foord09e29802010-04-04 22:41:54 +0000735 and must be decorated as a :func:`classmethod`::
Michael Foordba097ec2010-04-03 17:03:11 +0000736
737 @classmethod
738 def setUpClass(cls):
739 ...
740
741 See `Class and Module Fixtures`_ for more details.
742
743 .. versionadded:: 2.7
744
745
746 .. method:: tearDownClass()
747
748 A class method called after tests in an individual class have run.
749 ``tearDownClass`` is called with the class as the only argument
750 and must be decorated as a :meth:`classmethod`::
751
752 @classmethod
753 def tearDownClass(cls):
754 ...
755
756 See `Class and Module Fixtures`_ for more details.
757
758 .. versionadded:: 2.7
759
760
Ezio Melottidd7c5932011-03-10 23:00:48 +0200761 .. method:: run(result=None)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000762
763 Run the test, collecting the result into the test result object passed as
Ezio Melottidd7c5932011-03-10 23:00:48 +0200764 *result*. If *result* is omitted or ``None``, a temporary result
Ezio Melottic2f5a592009-06-30 22:51:06 +0000765 object is created (by calling the :meth:`defaultTestResult` method) and
766 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000767
768 The same effect may be had by simply calling the :class:`TestCase`
769 instance.
770
771
Benjamin Peterson47d97382009-03-26 20:05:50 +0000772 .. method:: skipTest(reason)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000773
Stefan Krah4a769052010-05-19 15:59:40 +0000774 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson31b78062009-03-23 23:13:36 +0000775 test. See :ref:`unittest-skipping` for more information.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000776
Georg Brandl90aae552010-04-10 11:15:24 +0000777 .. versionadded:: 2.7
778
Benjamin Peterson99721e02009-03-23 23:10:14 +0000779
780 .. method:: debug()
781
782 Run the test without collecting the result. This allows exceptions raised
783 by the test to be propagated to the caller, and can be used to support
784 running tests under a debugger.
785
Ezio Melottidd7c5932011-03-10 23:00:48 +0200786 .. _assert-methods:
Benjamin Peterson99721e02009-03-23 23:10:14 +0000787
Ezio Melotti7f620622016-01-12 11:03:10 +0200788 The :class:`TestCase` class provides several assert methods to check for and
789 report failures. The following table lists the most commonly used methods
790 (see the tables below for more assert methods):
Benjamin Peterson99721e02009-03-23 23:10:14 +0000791
Ezio Melottidd7c5932011-03-10 23:00:48 +0200792 +-----------------------------------------+-----------------------------+---------------+
793 | Method | Checks that | New in |
794 +=========================================+=============================+===============+
795 | :meth:`assertEqual(a, b) | ``a == b`` | |
796 | <TestCase.assertEqual>` | | |
797 +-----------------------------------------+-----------------------------+---------------+
798 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
799 | <TestCase.assertNotEqual>` | | |
800 +-----------------------------------------+-----------------------------+---------------+
801 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
802 | <TestCase.assertTrue>` | | |
803 +-----------------------------------------+-----------------------------+---------------+
804 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
805 | <TestCase.assertFalse>` | | |
806 +-----------------------------------------+-----------------------------+---------------+
807 | :meth:`assertIs(a, b) | ``a is b`` | 2.7 |
808 | <TestCase.assertIs>` | | |
809 +-----------------------------------------+-----------------------------+---------------+
810 | :meth:`assertIsNot(a, b) | ``a is not b`` | 2.7 |
811 | <TestCase.assertIsNot>` | | |
812 +-----------------------------------------+-----------------------------+---------------+
813 | :meth:`assertIsNone(x) | ``x is None`` | 2.7 |
814 | <TestCase.assertIsNone>` | | |
815 +-----------------------------------------+-----------------------------+---------------+
816 | :meth:`assertIsNotNone(x) | ``x is not None`` | 2.7 |
817 | <TestCase.assertIsNotNone>` | | |
818 +-----------------------------------------+-----------------------------+---------------+
819 | :meth:`assertIn(a, b) | ``a in b`` | 2.7 |
820 | <TestCase.assertIn>` | | |
821 +-----------------------------------------+-----------------------------+---------------+
822 | :meth:`assertNotIn(a, b) | ``a not in b`` | 2.7 |
823 | <TestCase.assertNotIn>` | | |
824 +-----------------------------------------+-----------------------------+---------------+
825 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 2.7 |
826 | <TestCase.assertIsInstance>` | | |
827 +-----------------------------------------+-----------------------------+---------------+
828 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 2.7 |
829 | <TestCase.assertNotIsInstance>` | | |
830 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson99721e02009-03-23 23:10:14 +0000831
Ezio Melottidd7c5932011-03-10 23:00:48 +0200832 All the assert methods (except :meth:`assertRaises`,
833 :meth:`assertRaisesRegexp`)
834 accept a *msg* argument that, if specified, is used as the error message on
835 failure (see also :data:`longMessage`).
Benjamin Peterson99721e02009-03-23 23:10:14 +0000836
Ezio Melottidd7c5932011-03-10 23:00:48 +0200837 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000838
839 Test that *first* and *second* are equal. If the values do not compare
Ezio Melottidd7c5932011-03-10 23:00:48 +0200840 equal, the test will fail.
Gregory P. Smith28399852009-03-31 16:54:10 +0000841
842 In addition, if *first* and *second* are the exact same type and one of
Michael Foordfe6349c2010-02-08 22:41:16 +0000843 list, tuple, dict, set, frozenset or unicode or any type that a subclass
Ezio Melotti055d70d2012-01-16 08:21:24 +0200844 registers with :meth:`addTypeEqualityFunc` the type-specific equality
Ezio Melottidd7c5932011-03-10 23:00:48 +0200845 function will be called in order to generate a more useful default
846 error message (see also the :ref:`list of type-specific methods
847 <type-specific-methods>`).
Gregory P. Smith28399852009-03-31 16:54:10 +0000848
849 .. versionchanged:: 2.7
Ezio Melotti055d70d2012-01-16 08:21:24 +0200850 Added the automatic calling of type-specific equality function.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000851
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000852
Ezio Melottidd7c5932011-03-10 23:00:48 +0200853 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000854
855 Test that *first* and *second* are not equal. If the values do compare
Ezio Melottidd7c5932011-03-10 23:00:48 +0200856 equal, the test will fail.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000857
Ezio Melottidd7c5932011-03-10 23:00:48 +0200858 .. method:: assertTrue(expr, msg=None)
859 assertFalse(expr, msg=None)
860
861 Test that *expr* is true (or false).
862
863 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
864 is True`` (use ``assertIs(expr, True)`` for the latter). This method
865 should also be avoided when more specific methods are available (e.g.
866 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
867 provide a better error message in case of failure.
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000868
Benjamin Peterson99721e02009-03-23 23:10:14 +0000869
Ezio Melottidd7c5932011-03-10 23:00:48 +0200870 .. method:: assertIs(first, second, msg=None)
871 assertIsNot(first, second, msg=None)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000872
Ezio Melottidd7c5932011-03-10 23:00:48 +0200873 Test that *first* and *second* evaluate (or don't evaluate) to the same object.
Gregory P. Smith28399852009-03-31 16:54:10 +0000874
875 .. versionadded:: 2.7
876
877
Ezio Melottidd7c5932011-03-10 23:00:48 +0200878 .. method:: assertIsNone(expr, msg=None)
879 assertIsNotNone(expr, msg=None)
Gregory P. Smith28399852009-03-31 16:54:10 +0000880
Serhiy Storchakaad13f332016-10-19 16:29:10 +0300881 Test that *expr* is (or is not) ``None``.
Michael Foordba097ec2010-04-03 17:03:11 +0000882
883 .. versionadded:: 2.7
884
885
Gregory P. Smith28399852009-03-31 16:54:10 +0000886 .. method:: assertIn(first, second, msg=None)
887 assertNotIn(first, second, msg=None)
888
Ezio Melottidd7c5932011-03-10 23:00:48 +0200889 Test that *first* is (or is not) in *second*.
Gregory P. Smith28399852009-03-31 16:54:10 +0000890
891 .. versionadded:: 2.7
892
893
Ezio Melottidd7c5932011-03-10 23:00:48 +0200894 .. method:: assertIsInstance(obj, cls, msg=None)
895 assertNotIsInstance(obj, cls, msg=None)
Gregory P. Smith28399852009-03-31 16:54:10 +0000896
Ezio Melottidd7c5932011-03-10 23:00:48 +0200897 Test that *obj* is (or is not) an instance of *cls* (which can be a
898 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melotti080b6f02011-12-19 07:04:48 +0200899 To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.
Gregory P. Smith28399852009-03-31 16:54:10 +0000900
901 .. versionadded:: 2.7
902
903
Ezio Melottidd7c5932011-03-10 23:00:48 +0200904 It is also possible to check that exceptions and warnings are raised using
905 the following methods:
Gregory P. Smith28399852009-03-31 16:54:10 +0000906
Ezio Melottidd7c5932011-03-10 23:00:48 +0200907 +---------------------------------------------------------+--------------------------------------+------------+
908 | Method | Checks that | New in |
909 +=========================================================+======================================+============+
Éric Araujoa7cbe282011-09-01 19:49:31 +0200910 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melottidd7c5932011-03-10 23:00:48 +0200911 | <TestCase.assertRaises>` | | |
912 +---------------------------------------------------------+--------------------------------------+------------+
Ezio Melotti36c33682013-09-13 22:17:40 +0300913 | :meth:`assertRaisesRegexp(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 2.7 |
914 | <TestCase.assertRaisesRegexp>` | and the message matches regex *r* | |
Ezio Melottidd7c5932011-03-10 23:00:48 +0200915 +---------------------------------------------------------+--------------------------------------+------------+
Gregory P. Smith28399852009-03-31 16:54:10 +0000916
Ezio Melottidd7c5932011-03-10 23:00:48 +0200917 .. method:: assertRaises(exception, callable, *args, **kwds)
918 assertRaises(exception)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000919
920 Test that an exception is raised when *callable* is called with any
921 positional or keyword arguments that are also passed to
922 :meth:`assertRaises`. The test passes if *exception* is raised, is an
923 error if another exception is raised, or fails if no exception is raised.
924 To catch any of a group of exceptions, a tuple containing the exception
925 classes may be passed as *exception*.
926
Ezio Melottidd7c5932011-03-10 23:00:48 +0200927 If only the *exception* argument is given, returns a context manager so
928 that the code under test can be written inline rather than as a function::
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000929
Michael Foord1f3fa8a2010-02-05 21:07:38 +0000930 with self.assertRaises(SomeException):
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000931 do_something()
932
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +0000933 The context manager will store the caught exception object in its
Georg Brandldc3694b2010-02-07 17:02:22 +0000934 :attr:`exception` attribute. This can be useful if the intention
Michael Foord1f3fa8a2010-02-05 21:07:38 +0000935 is to perform additional checks on the exception raised::
936
937 with self.assertRaises(SomeException) as cm:
938 do_something()
939
Georg Brandldc3694b2010-02-07 17:02:22 +0000940 the_exception = cm.exception
Michael Foordba7732e2010-02-05 23:28:12 +0000941 self.assertEqual(the_exception.error_code, 3)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +0000942
Benjamin Peterson99721e02009-03-23 23:10:14 +0000943 .. versionchanged:: 2.7
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000944 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000945
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000946
Ezio Melottidd7c5932011-03-10 23:00:48 +0200947 .. method:: assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
948 assertRaisesRegexp(exception, regexp)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000949
Gregory P. Smith28399852009-03-31 16:54:10 +0000950 Like :meth:`assertRaises` but also tests that *regexp* matches
951 on the string representation of the raised exception. *regexp* may be
952 a regular expression object or a string containing a regular expression
953 suitable for use by :func:`re.search`. Examples::
954
Terry Jan Reedy8d750032013-06-29 13:15:36 -0400955 self.assertRaisesRegexp(ValueError, "invalid literal for.*XYZ'$",
Gregory P. Smith28399852009-03-31 16:54:10 +0000956 int, 'XYZ')
957
958 or::
959
960 with self.assertRaisesRegexp(ValueError, 'literal'):
961 int('XYZ')
962
963 .. versionadded:: 2.7
964
965
Gregory P. Smith28399852009-03-31 16:54:10 +0000966
Ezio Melottidd7c5932011-03-10 23:00:48 +0200967 There are also other methods used to perform more specific checks, such as:
968
969 +---------------------------------------+--------------------------------+--------------+
970 | Method | Checks that | New in |
971 +=======================================+================================+==============+
972 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
973 | <TestCase.assertAlmostEqual>` | | |
974 +---------------------------------------+--------------------------------+--------------+
975 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
976 | <TestCase.assertNotAlmostEqual>` | | |
977 +---------------------------------------+--------------------------------+--------------+
978 | :meth:`assertGreater(a, b) | ``a > b`` | 2.7 |
979 | <TestCase.assertGreater>` | | |
980 +---------------------------------------+--------------------------------+--------------+
981 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 2.7 |
982 | <TestCase.assertGreaterEqual>` | | |
983 +---------------------------------------+--------------------------------+--------------+
984 | :meth:`assertLess(a, b) | ``a < b`` | 2.7 |
985 | <TestCase.assertLess>` | | |
986 +---------------------------------------+--------------------------------+--------------+
987 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 2.7 |
988 | <TestCase.assertLessEqual>` | | |
989 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti36c33682013-09-13 22:17:40 +0300990 | :meth:`assertRegexpMatches(s, r) | ``r.search(s)`` | 2.7 |
Ezio Melottidd7c5932011-03-10 23:00:48 +0200991 | <TestCase.assertRegexpMatches>` | | |
992 +---------------------------------------+--------------------------------+--------------+
Ezio Melotti36c33682013-09-13 22:17:40 +0300993 | :meth:`assertNotRegexpMatches(s, r) | ``not r.search(s)`` | 2.7 |
Ezio Melottidd7c5932011-03-10 23:00:48 +0200994 | <TestCase.assertNotRegexpMatches>` | | |
995 +---------------------------------------+--------------------------------+--------------+
996 | :meth:`assertItemsEqual(a, b) | sorted(a) == sorted(b) and | 2.7 |
997 | <TestCase.assertItemsEqual>` | works with unhashable objs | |
998 +---------------------------------------+--------------------------------+--------------+
999 | :meth:`assertDictContainsSubset(a, b) | all the key/value pairs | 2.7 |
Éric Araujoa7cbe282011-09-01 19:49:31 +02001000 | <TestCase.assertDictContainsSubset>` | in *a* exist in *b* | |
Ezio Melottidd7c5932011-03-10 23:00:48 +02001001 +---------------------------------------+--------------------------------+--------------+
1002
1003
1004 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1005 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
1006
1007 Test that *first* and *second* are approximately (or not approximately)
1008 equal by computing the difference, rounding to the given number of
1009 decimal *places* (default 7), and comparing to zero. Note that these
1010 methods round the values to the given number of *decimal places* (i.e.
1011 like the :func:`round` function) and not *significant digits*.
1012
1013 If *delta* is supplied instead of *places* then the difference
Ezio Melottid5991422013-08-11 13:04:50 +03001014 between *first* and *second* must be less or equal to (or greater than) *delta*.
Ezio Melottidd7c5932011-03-10 23:00:48 +02001015
1016 Supplying both *delta* and *places* raises a ``TypeError``.
1017
1018 .. versionchanged:: 2.7
1019 :meth:`assertAlmostEqual` automatically considers almost equal objects
1020 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1021 if the objects compare equal. Added the *delta* keyword argument.
1022
1023
1024
1025 .. method:: assertGreater(first, second, msg=None)
1026 assertGreaterEqual(first, second, msg=None)
1027 assertLess(first, second, msg=None)
1028 assertLessEqual(first, second, msg=None)
1029
1030 Test that *first* is respectively >, >=, < or <= than *second* depending
1031 on the method name. If not, the test will fail::
1032
1033 >>> self.assertGreaterEqual(3, 4)
1034 AssertionError: "3" unexpectedly not greater than or equal to "4"
Gregory P. Smith28399852009-03-31 16:54:10 +00001035
1036 .. versionadded:: 2.7
1037
1038
Ezio Melottidd7c5932011-03-10 23:00:48 +02001039 .. method:: assertRegexpMatches(text, regexp, msg=None)
Gregory P. Smith28399852009-03-31 16:54:10 +00001040
Ezio Melottidd7c5932011-03-10 23:00:48 +02001041 Test that a *regexp* search matches *text*. In case
1042 of failure, the error message will include the pattern and the *text* (or
1043 the pattern and the part of *text* that unexpectedly matched). *regexp*
1044 may be a regular expression object or a string containing a regular
1045 expression suitable for use by :func:`re.search`.
Gregory P. Smith28399852009-03-31 16:54:10 +00001046
1047 .. versionadded:: 2.7
1048
1049
Ezio Melottidd7c5932011-03-10 23:00:48 +02001050 .. method:: assertNotRegexpMatches(text, regexp, msg=None)
Michael Foordf2dfef12009-04-05 19:19:28 +00001051
Ezio Melottidd7c5932011-03-10 23:00:48 +02001052 Verifies that a *regexp* search does not match *text*. Fails with an error
1053 message including the pattern and the part of *text* that matches. *regexp*
1054 may be a regular expression object or a string containing a regular
1055 expression suitable for use by :func:`re.search`.
Michael Foordf2dfef12009-04-05 19:19:28 +00001056
1057 .. versionadded:: 2.7
1058
1059
Ezio Melottidd7c5932011-03-10 23:00:48 +02001060 .. method:: assertItemsEqual(actual, expected, msg=None)
Michael Foordf2dfef12009-04-05 19:19:28 +00001061
Ezio Melottidd7c5932011-03-10 23:00:48 +02001062 Test that sequence *expected* contains the same elements as *actual*,
1063 regardless of their order. When they don't, an error message listing the
1064 differences between the sequences will be generated.
1065
1066 Duplicate elements are *not* ignored when comparing *actual* and
1067 *expected*. It verifies if each element has the same count in both
1068 sequences. It is the equivalent of ``assertEqual(sorted(expected),
1069 sorted(actual))`` but it works with sequences of unhashable objects as
1070 well.
Michael Foordf2dfef12009-04-05 19:19:28 +00001071
Ezio Melotti183dc462013-04-29 12:26:01 +03001072 In Python 3, this method is named ``assertCountEqual``.
1073
Michael Foordf2dfef12009-04-05 19:19:28 +00001074 .. versionadded:: 2.7
1075
1076
Ezio Melottidd7c5932011-03-10 23:00:48 +02001077 .. method:: assertDictContainsSubset(expected, actual, msg=None)
Georg Brandlf895cf52009-10-01 20:59:31 +00001078
Ezio Melottidd7c5932011-03-10 23:00:48 +02001079 Tests whether the key/value pairs in dictionary *actual* are a
1080 superset of those in *expected*. If not, an error message listing
1081 the missing keys and mismatched values is generated.
1082
1083 .. versionadded:: 2.7
1084 .. deprecated:: 3.2
1085
1086
1087
1088 .. _type-specific-methods:
1089
1090 The :meth:`assertEqual` method dispatches the equality check for objects of
1091 the same type to different type-specific methods. These methods are already
1092 implemented for most of the built-in types, but it's also possible to
1093 register new methods using :meth:`addTypeEqualityFunc`:
1094
1095 .. method:: addTypeEqualityFunc(typeobj, function)
1096
1097 Registers a type-specific method called by :meth:`assertEqual` to check
1098 if two objects of exactly the same *typeobj* (not subclasses) compare
1099 equal. *function* must take two positional arguments and a third msg=None
1100 keyword argument just as :meth:`assertEqual` does. It must raise
1101 :data:`self.failureException(msg) <failureException>` when inequality
1102 between the first two parameters is detected -- possibly providing useful
1103 information and explaining the inequalities in details in the error
1104 message.
1105
1106 .. versionadded:: 2.7
1107
1108 The list of type-specific methods automatically used by
1109 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1110 that it's usually not necessary to invoke these methods directly.
1111
1112 +-----------------------------------------+-----------------------------+--------------+
1113 | Method | Used to compare | New in |
1114 +=========================================+=============================+==============+
1115 | :meth:`assertMultiLineEqual(a, b) | strings | 2.7 |
1116 | <TestCase.assertMultiLineEqual>` | | |
1117 +-----------------------------------------+-----------------------------+--------------+
1118 | :meth:`assertSequenceEqual(a, b) | sequences | 2.7 |
1119 | <TestCase.assertSequenceEqual>` | | |
1120 +-----------------------------------------+-----------------------------+--------------+
1121 | :meth:`assertListEqual(a, b) | lists | 2.7 |
1122 | <TestCase.assertListEqual>` | | |
1123 +-----------------------------------------+-----------------------------+--------------+
1124 | :meth:`assertTupleEqual(a, b) | tuples | 2.7 |
1125 | <TestCase.assertTupleEqual>` | | |
1126 +-----------------------------------------+-----------------------------+--------------+
1127 | :meth:`assertSetEqual(a, b) | sets or frozensets | 2.7 |
1128 | <TestCase.assertSetEqual>` | | |
1129 +-----------------------------------------+-----------------------------+--------------+
1130 | :meth:`assertDictEqual(a, b) | dicts | 2.7 |
1131 | <TestCase.assertDictEqual>` | | |
1132 +-----------------------------------------+-----------------------------+--------------+
1133
1134
1135
1136 .. method:: assertMultiLineEqual(first, second, msg=None)
1137
1138 Test that the multiline string *first* is equal to the string *second*.
1139 When not equal a diff of the two strings highlighting the differences
1140 will be included in the error message. This method is used by default
Aditya Hase0666d0e2017-07-26 02:29:52 +05301141 when comparing Unicode strings with :meth:`assertEqual`.
Georg Brandlf895cf52009-10-01 20:59:31 +00001142
1143 .. versionadded:: 2.7
1144
1145
Ezio Melottidd7c5932011-03-10 23:00:48 +02001146 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
Georg Brandlf895cf52009-10-01 20:59:31 +00001147
Ezio Melottidd7c5932011-03-10 23:00:48 +02001148 Tests that two sequences are equal. If a *seq_type* is supplied, both
1149 *seq1* and *seq2* must be instances of *seq_type* or a failure will
1150 be raised. If the sequences are different an error message is
1151 constructed that shows the difference between the two.
1152
1153 This method is not called directly by :meth:`assertEqual`, but
1154 it's used to implement :meth:`assertListEqual` and
1155 :meth:`assertTupleEqual`.
Georg Brandlf895cf52009-10-01 20:59:31 +00001156
1157 .. versionadded:: 2.7
1158
1159
Ezio Melottidd7c5932011-03-10 23:00:48 +02001160 .. method:: assertListEqual(list1, list2, msg=None)
1161 assertTupleEqual(tuple1, tuple2, msg=None)
Gregory P. Smith28399852009-03-31 16:54:10 +00001162
Ezio Melotti6bb9c732012-08-29 17:50:42 +03001163 Tests that two lists or tuples are equal. If not, an error message is
Ezio Melottidd7c5932011-03-10 23:00:48 +02001164 constructed that shows only the differences between the two. An error
1165 is also raised if either of the parameters are of the wrong type.
1166 These methods are used by default when comparing lists or tuples with
1167 :meth:`assertEqual`.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001168
Ezio Melottidd7c5932011-03-10 23:00:48 +02001169 .. versionadded:: 2.7
Gregory P. Smith65ff0052009-03-31 19:59:14 +00001170
Benjamin Peterson99721e02009-03-23 23:10:14 +00001171
Ezio Melottidd7c5932011-03-10 23:00:48 +02001172 .. method:: assertSetEqual(set1, set2, msg=None)
Benjamin Peterson99721e02009-03-23 23:10:14 +00001173
Ezio Melottidd7c5932011-03-10 23:00:48 +02001174 Tests that two sets are equal. If not, an error message is constructed
1175 that lists the differences between the sets. This method is used by
1176 default when comparing sets or frozensets with :meth:`assertEqual`.
1177
1178 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
1179 method.
1180
1181 .. versionadded:: 2.7
1182
1183
1184 .. method:: assertDictEqual(expected, actual, msg=None)
1185
1186 Test that two dictionaries are equal. If not, an error message is
1187 constructed that shows the differences in the dictionaries. This
1188 method will be used by default to compare dictionaries in
1189 calls to :meth:`assertEqual`.
1190
1191 .. versionadded:: 2.7
1192
1193
1194
1195 .. _other-methods-and-attrs:
1196
1197 Finally the :class:`TestCase` provides the following methods and attributes:
1198
1199
1200 .. method:: fail(msg=None)
1201
1202 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson99721e02009-03-23 23:10:14 +00001203 the error message.
1204
1205
1206 .. attribute:: failureException
1207
1208 This class attribute gives the exception raised by the test method. If a
1209 test framework needs to use a specialized exception, possibly to carry
1210 additional information, it must subclass this exception in order to "play
1211 fair" with the framework. The initial value of this attribute is
1212 :exc:`AssertionError`.
1213
Michael Foord345b2fe2009-04-02 03:20:38 +00001214
1215 .. attribute:: longMessage
1216
Ezio Melottidd7c5932011-03-10 23:00:48 +02001217 If set to ``True`` then any explicit failure message you pass in to the
1218 :ref:`assert methods <assert-methods>` will be appended to the end of the
1219 normal failure message. The normal messages contain useful information
1220 about the objects involved, for example the message from assertEqual
1221 shows you the repr of the two unequal objects. Setting this attribute
1222 to ``True`` allows you to have a custom error message in addition to the
1223 normal one.
Michael Foord345b2fe2009-04-02 03:20:38 +00001224
Ezio Melottidd7c5932011-03-10 23:00:48 +02001225 This attribute defaults to ``False``, meaning that a custom message passed
Michael Foord345b2fe2009-04-02 03:20:38 +00001226 to an assert method will silence the normal message.
1227
1228 The class setting can be overridden in individual tests by assigning an
Ezio Melottidd7c5932011-03-10 23:00:48 +02001229 instance attribute to ``True`` or ``False`` before calling the assert methods.
Michael Foord345b2fe2009-04-02 03:20:38 +00001230
1231 .. versionadded:: 2.7
1232
1233
Michael Foord8dde2012010-06-05 21:57:03 +00001234 .. attribute:: maxDiff
1235
1236 This attribute controls the maximum length of diffs output by assert
1237 methods that report diffs on failure. It defaults to 80*8 characters.
1238 Assert methods affected by this attribute are
1239 :meth:`assertSequenceEqual` (including all the sequence comparison
1240 methods that delegate to it), :meth:`assertDictEqual` and
1241 :meth:`assertMultiLineEqual`.
1242
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001243 Setting ``maxDiff`` to ``None`` means that there is no maximum length of
Michael Foord8dde2012010-06-05 21:57:03 +00001244 diffs.
1245
1246 .. versionadded:: 2.7
1247
1248
Benjamin Peterson99721e02009-03-23 23:10:14 +00001249 Testing frameworks can use the following methods to collect information on
1250 the test:
1251
1252
1253 .. method:: countTestCases()
1254
1255 Return the number of tests represented by this test object. For
1256 :class:`TestCase` instances, this will always be ``1``.
1257
1258
1259 .. method:: defaultTestResult()
1260
1261 Return an instance of the test result class that should be used for this
1262 test case class (if no other result instance is provided to the
1263 :meth:`run` method).
1264
1265 For :class:`TestCase` instances, this will always be an instance of
1266 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1267 as necessary.
1268
1269
1270 .. method:: id()
1271
1272 Return a string identifying the specific test case. This is usually the
1273 full name of the test method, including the module and class name.
1274
1275
1276 .. method:: shortDescription()
1277
Ezio Melottidd7c5932011-03-10 23:00:48 +02001278 Returns a description of the test, or ``None`` if no description
Gregory P. Smith28399852009-03-31 16:54:10 +00001279 has been provided. The default implementation of this method
1280 returns the first line of the test method's docstring, if available,
Michael Foorddb43b5a2010-02-10 14:25:12 +00001281 or :const:`None`.
Gregory P. Smith28399852009-03-31 16:54:10 +00001282
1283
Gregory P. Smith28399852009-03-31 16:54:10 +00001284
Ezio Melottidd7c5932011-03-10 23:00:48 +02001285 .. method:: addCleanup(function, *args, **kwargs)
Michael Foorde2fb98f2009-05-02 20:15:05 +00001286
1287 Add a function to be called after :meth:`tearDown` to cleanup resources
1288 used during the test. Functions will be called in reverse order to the
1289 order they are added (LIFO). They are called with any arguments and
1290 keyword arguments passed into :meth:`addCleanup` when they are
1291 added.
1292
1293 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1294 then any cleanup functions added will still be called.
1295
1296 .. versionadded:: 2.7
1297
1298
1299 .. method:: doCleanups()
1300
Barry Warsawfa900d42010-04-12 14:40:49 +00001301 This method is called unconditionally after :meth:`tearDown`, or
Michael Foorde2fb98f2009-05-02 20:15:05 +00001302 after :meth:`setUp` if :meth:`setUp` raises an exception.
1303
1304 It is responsible for calling all the cleanup functions added by
1305 :meth:`addCleanup`. If you need cleanup functions to be called
1306 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1307 yourself.
1308
1309 :meth:`doCleanups` pops methods off the stack of cleanup
1310 functions one at a time, so it can be called at any time.
1311
1312 .. versionadded:: 2.7
1313
1314
Ezio Melottidd7c5932011-03-10 23:00:48 +02001315.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001316
1317 This class implements the portion of the :class:`TestCase` interface which
Georg Brandl2fcd1732009-05-30 10:45:40 +00001318 allows the test runner to drive the test, but does not provide the methods
1319 which test code can use to check and report errors. This is used to create
1320 test cases using legacy test code, allowing it to be integrated into a
1321 :mod:`unittest`-based test framework.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001322
1323
Ezio Melottidd7c5932011-03-10 23:00:48 +02001324Deprecated aliases
1325##################
1326
1327For historical reasons, some of the :class:`TestCase` methods had one or more
1328aliases that are now deprecated. The following table lists the correct names
1329along with their deprecated aliases:
1330
1331 ============================== ===============================
1332 Method Name Deprecated alias(es)
1333 ============================== ===============================
1334 :meth:`.assertEqual` failUnlessEqual, assertEquals
1335 :meth:`.assertNotEqual` failIfEqual
1336 :meth:`.assertTrue` failUnless, assert\_
1337 :meth:`.assertFalse` failIf
1338 :meth:`.assertRaises` failUnlessRaises
1339 :meth:`.assertAlmostEqual` failUnlessAlmostEqual
1340 :meth:`.assertNotAlmostEqual` failIfAlmostEqual
1341 ============================== ===============================
1342
1343 .. deprecated:: 2.7
1344 the aliases listed in the second column
1345
1346
1347
Benjamin Peterson99721e02009-03-23 23:10:14 +00001348.. _testsuite-objects:
1349
1350Grouping tests
1351~~~~~~~~~~~~~~
1352
Ezio Melottidd7c5932011-03-10 23:00:48 +02001353.. class:: TestSuite(tests=())
Georg Brandl8ec7f652007-08-15 14:28:01 +00001354
Martin Panter1b31d282017-01-18 12:14:29 +00001355 This class represents an aggregation of individual test cases and test suites.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001356 The class presents the interface needed by the test runner to allow it to be run
1357 as any other test case. Running a :class:`TestSuite` instance is the same as
1358 iterating over the suite, running each test individually.
1359
1360 If *tests* is given, it must be an iterable of individual test cases or other
1361 test suites that will be used to build the suite initially. Additional methods
1362 are provided to add test cases and suites to the collection later on.
1363
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001364 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1365 they do not actually implement a test. Instead, they are used to aggregate
1366 tests into groups of tests that should be run together. Some additional
1367 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson99721e02009-03-23 23:10:14 +00001368
1369
1370 .. method:: TestSuite.addTest(test)
1371
1372 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1373
1374
1375 .. method:: TestSuite.addTests(tests)
1376
1377 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1378 instances to this test suite.
1379
Georg Brandl2fcd1732009-05-30 10:45:40 +00001380 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1381 each element.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001382
1383 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1384
1385
1386 .. method:: run(result)
1387
1388 Run the tests associated with this suite, collecting the result into the
1389 test result object passed as *result*. Note that unlike
1390 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1391 be passed in.
1392
1393
1394 .. method:: debug()
1395
1396 Run the tests associated with this suite without collecting the
1397 result. This allows exceptions raised by the test to be propagated to the
1398 caller and can be used to support running tests under a debugger.
1399
1400
1401 .. method:: countTestCases()
1402
1403 Return the number of tests represented by this test object, including all
1404 individual tests and sub-suites.
1405
Georg Brandl9bc66822009-04-27 17:04:23 +00001406
1407 .. method:: __iter__()
1408
1409 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1410 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1411 that this method maybe called several times on a single suite
1412 (for example when counting tests or comparing for equality)
1413 so the tests returned must be the same for repeated iterations.
1414
1415 .. versionchanged:: 2.7
1416 In earlier versions the :class:`TestSuite` accessed tests directly rather
1417 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1418 for providing tests.
1419
Benjamin Peterson99721e02009-03-23 23:10:14 +00001420 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1421 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1422
1423
Benjamin Peterson99721e02009-03-23 23:10:14 +00001424Loading and running tests
1425~~~~~~~~~~~~~~~~~~~~~~~~~
1426
Georg Brandl8ec7f652007-08-15 14:28:01 +00001427.. class:: TestLoader()
1428
Benjamin Peterson99721e02009-03-23 23:10:14 +00001429 The :class:`TestLoader` class is used to create test suites from classes and
1430 modules. Normally, there is no need to create an instance of this class; the
1431 :mod:`unittest` module provides an instance that can be shared as
Ezio Melotti217e6a62012-04-29 10:52:18 +03001432 :data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
1433 allows customization of some configurable properties.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001434
1435 :class:`TestLoader` objects have the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001436
1437
Benjamin Peterson99721e02009-03-23 23:10:14 +00001438 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001439
Martin Panter1b31d282017-01-18 12:14:29 +00001440 Return a suite of all test cases contained in the :class:`TestCase`\ -derived
Benjamin Peterson99721e02009-03-23 23:10:14 +00001441 :class:`testCaseClass`.
1442
1443
1444 .. method:: loadTestsFromModule(module)
1445
Martin Panter1b31d282017-01-18 12:14:29 +00001446 Return a suite of all test cases contained in the given module. This
Benjamin Peterson99721e02009-03-23 23:10:14 +00001447 method searches *module* for classes derived from :class:`TestCase` and
1448 creates an instance of the class for each test method defined for the
1449 class.
1450
Georg Brandl16a57f62009-04-27 15:29:09 +00001451 .. note::
Benjamin Peterson99721e02009-03-23 23:10:14 +00001452
1453 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1454 convenient in sharing fixtures and helper functions, defining test
1455 methods on base classes that are not intended to be instantiated
1456 directly does not play well with this method. Doing so, however, can
1457 be useful when the fixtures are different and defined in subclasses.
1458
Michael Foordb4a81c82009-05-29 20:33:46 +00001459 If a module provides a ``load_tests`` function it will be called to
1460 load the tests. This allows modules to customize test loading.
1461 This is the `load_tests protocol`_.
1462
1463 .. versionchanged:: 2.7
1464 Support for ``load_tests`` added.
1465
Benjamin Peterson99721e02009-03-23 23:10:14 +00001466
Ezio Melottidd7c5932011-03-10 23:00:48 +02001467 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson99721e02009-03-23 23:10:14 +00001468
Martin Panter1b31d282017-01-18 12:14:29 +00001469 Return a suite of all test cases given a string specifier.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001470
1471 The specifier *name* is a "dotted name" that may resolve either to a
1472 module, a test case class, a test method within a test case class, a
1473 :class:`TestSuite` instance, or a callable object which returns a
1474 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1475 applied in the order listed here; that is, a method on a possible test
1476 case class will be picked up as "a test method within a test case class",
1477 rather than "a callable object".
1478
1479 For example, if you have a module :mod:`SampleTests` containing a
Georg Brandl2fcd1732009-05-30 10:45:40 +00001480 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1481 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1482 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1483 return a suite which will run all three test methods. Using the specifier
1484 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1485 suite which will run only the :meth:`test_two` test method. The specifier
1486 can refer to modules and packages which have not been imported; they will
1487 be imported as a side-effect.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001488
1489 The method optionally resolves *name* relative to the given *module*.
1490
1491
Ezio Melottidd7c5932011-03-10 23:00:48 +02001492 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson99721e02009-03-23 23:10:14 +00001493
1494 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1495 than a single name. The return value is a test suite which supports all
1496 the tests defined for each name.
1497
1498
1499 .. method:: getTestCaseNames(testCaseClass)
1500
1501 Return a sorted sequence of method names found within *testCaseClass*;
1502 this should be a subclass of :class:`TestCase`.
1503
Michael Foordb4a81c82009-05-29 20:33:46 +00001504
1505 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1506
R David Murray8de21182014-03-11 18:12:25 -04001507 Find all the test modules by recursing into subdirectories from the
1508 specified start directory, and return a TestSuite object containing them.
1509 Only test files that match *pattern* will be loaded. (Using shell style
1510 pattern matching.) Only module names that are importable (i.e. are valid
1511 Python identifiers) will be loaded.
Michael Foordb4a81c82009-05-29 20:33:46 +00001512
1513 All test modules must be importable from the top level of the project. If
1514 the start directory is not the top level directory then the top level
1515 directory must be specified separately.
1516
Michael Foorde91ea562009-09-13 19:07:03 +00001517 If importing a module fails, for example due to a syntax error, then this
1518 will be recorded as a single error and discovery will continue.
1519
Michael Foordb4a81c82009-05-29 20:33:46 +00001520 If a test package name (directory with :file:`__init__.py`) matches the
1521 pattern then the package will be checked for a ``load_tests``
1522 function. If this exists then it will be called with *loader*, *tests*,
1523 *pattern*.
1524
Michael Foorddc0460a2009-09-13 19:08:18 +00001525 If load_tests exists then discovery does *not* recurse into the package,
Michael Foordb4a81c82009-05-29 20:33:46 +00001526 ``load_tests`` is responsible for loading all tests in the package.
1527
1528 The pattern is deliberately not stored as a loader attribute so that
1529 packages can continue discovery themselves. *top_level_dir* is stored so
1530 ``load_tests`` does not need to pass this argument in to
1531 ``loader.discover()``.
1532
Michael Foordba097ec2010-04-03 17:03:11 +00001533 *start_dir* can be a dotted module name as well as a directory.
1534
Michael Foord17565e52009-09-27 20:08:23 +00001535 .. versionadded:: 2.7
Michael Foordb4a81c82009-05-29 20:33:46 +00001536
Benjamin Peterson99721e02009-03-23 23:10:14 +00001537 The following attributes of a :class:`TestLoader` can be configured either by
1538 subclassing or assignment on an instance:
1539
1540
1541 .. attribute:: testMethodPrefix
1542
1543 String giving the prefix of method names which will be interpreted as test
1544 methods. The default value is ``'test'``.
1545
1546 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1547 methods.
1548
1549
1550 .. attribute:: sortTestMethodsUsing
1551
1552 Function to be used to compare method names when sorting them in
1553 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
1554 default value is the built-in :func:`cmp` function; the attribute can also
1555 be set to :const:`None` to disable the sort.
1556
1557
1558 .. attribute:: suiteClass
1559
1560 Callable object that constructs a test suite from a list of tests. No
1561 methods on the resulting object are needed. The default value is the
1562 :class:`TestSuite` class.
1563
1564 This affects all the :meth:`loadTestsFrom\*` methods.
1565
1566
Benjamin Peterson99721e02009-03-23 23:10:14 +00001567.. class:: TestResult
1568
1569 This class is used to compile information about which tests have succeeded
1570 and which have failed.
1571
1572 A :class:`TestResult` object stores the results of a set of tests. The
1573 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1574 properly recorded; test authors do not need to worry about recording the
1575 outcome of tests.
1576
1577 Testing frameworks built on top of :mod:`unittest` may want access to the
1578 :class:`TestResult` object generated by running a set of tests for reporting
1579 purposes; a :class:`TestResult` instance is returned by the
1580 :meth:`TestRunner.run` method for this purpose.
1581
1582 :class:`TestResult` instances have the following attributes that will be of
1583 interest when inspecting the results of running a set of tests:
1584
1585
1586 .. attribute:: errors
1587
1588 A list containing 2-tuples of :class:`TestCase` instances and strings
1589 holding formatted tracebacks. Each tuple represents a test which raised an
1590 unexpected exception.
1591
1592 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001593 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1594
1595
1596 .. attribute:: failures
1597
1598 A list containing 2-tuples of :class:`TestCase` instances and strings
1599 holding formatted tracebacks. Each tuple represents a test where a failure
Ezio Melotti26765832013-09-07 15:19:30 +03001600 was explicitly signalled using the :meth:`TestCase.assert\*` methods.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001601
1602 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001603 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1604
1605 .. attribute:: skipped
1606
1607 A list containing 2-tuples of :class:`TestCase` instances and strings
1608 holding the reason for skipping the test.
1609
1610 .. versionadded:: 2.7
1611
1612 .. attribute:: expectedFailures
1613
Georg Brandl09302282010-10-06 09:32:48 +00001614 A list containing 2-tuples of :class:`TestCase` instances and strings
1615 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson99721e02009-03-23 23:10:14 +00001616 of the test case.
1617
1618 .. attribute:: unexpectedSuccesses
1619
1620 A list containing :class:`TestCase` instances that were marked as expected
1621 failures, but succeeded.
1622
1623 .. attribute:: shouldStop
1624
1625 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1626
1627
1628 .. attribute:: testsRun
1629
1630 The total number of tests run so far.
1631
1632
Michael Foordba097ec2010-04-03 17:03:11 +00001633 .. attribute:: buffer
1634
1635 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1636 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1637 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1638 fails or errors. Any output is also attached to the failure / error message.
1639
1640 .. versionadded:: 2.7
1641
1642
1643 .. attribute:: failfast
1644
1645 If set to true :meth:`stop` will be called on the first failure or error,
1646 halting the test run.
1647
1648 .. versionadded:: 2.7
1649
1650
Benjamin Peterson99721e02009-03-23 23:10:14 +00001651 .. method:: wasSuccessful()
1652
Ezio Melottidd7c5932011-03-10 23:00:48 +02001653 Return ``True`` if all tests run so far have passed, otherwise returns
1654 ``False``.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001655
1656
1657 .. method:: stop()
1658
1659 This method can be called to signal that the set of tests being run should
Ezio Melottidd7c5932011-03-10 23:00:48 +02001660 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001661 :class:`TestRunner` objects should respect this flag and return without
1662 running any additional tests.
1663
1664 For example, this feature is used by the :class:`TextTestRunner` class to
1665 stop the test framework when the user signals an interrupt from the
1666 keyboard. Interactive tools which provide :class:`TestRunner`
1667 implementations can use this in a similar manner.
1668
1669 The following methods of the :class:`TestResult` class are used to maintain
1670 the internal data structures, and may be extended in subclasses to support
1671 additional reporting requirements. This is particularly useful in building
1672 tools which support interactive reporting while tests are being run.
1673
1674
1675 .. method:: startTest(test)
1676
1677 Called when the test case *test* is about to be run.
1678
Benjamin Peterson99721e02009-03-23 23:10:14 +00001679 .. method:: stopTest(test)
1680
1681 Called after the test case *test* has been executed, regardless of the
1682 outcome.
1683
Terry Jan Reedy94fb85e2014-04-11 14:11:00 -04001684 .. method:: startTestRun()
Michael Foord07ef4872009-05-02 22:43:34 +00001685
1686 Called once before any tests are executed.
1687
1688 .. versionadded:: 2.7
1689
1690
Terry Jan Reedy94fb85e2014-04-11 14:11:00 -04001691 .. method:: stopTestRun()
Michael Foord07ef4872009-05-02 22:43:34 +00001692
Ezio Melotti7b4e02c2010-01-27 20:25:11 +00001693 Called once after all tests are executed.
Michael Foord07ef4872009-05-02 22:43:34 +00001694
1695 .. versionadded:: 2.7
1696
1697
Benjamin Peterson99721e02009-03-23 23:10:14 +00001698 .. method:: addError(test, err)
1699
Ezio Melottiad543072013-09-07 15:23:36 +03001700 Called when the test case *test* raises an unexpected exception. *err* is a
Benjamin Peterson99721e02009-03-23 23:10:14 +00001701 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1702 traceback)``.
1703
1704 The default implementation appends a tuple ``(test, formatted_err)`` to
1705 the instance's :attr:`errors` attribute, where *formatted_err* is a
1706 formatted traceback derived from *err*.
1707
1708
1709 .. method:: addFailure(test, err)
1710
Michael Foordb4a81c82009-05-29 20:33:46 +00001711 Called when the test case *test* signals a failure. *err* is a tuple of
1712 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001713
1714 The default implementation appends a tuple ``(test, formatted_err)`` to
1715 the instance's :attr:`failures` attribute, where *formatted_err* is a
1716 formatted traceback derived from *err*.
1717
1718
1719 .. method:: addSuccess(test)
1720
1721 Called when the test case *test* succeeds.
1722
1723 The default implementation does nothing.
1724
1725
1726 .. method:: addSkip(test, reason)
1727
1728 Called when the test case *test* is skipped. *reason* is the reason the
1729 test gave for skipping.
1730
1731 The default implementation appends a tuple ``(test, reason)`` to the
1732 instance's :attr:`skipped` attribute.
1733
1734
1735 .. method:: addExpectedFailure(test, err)
1736
1737 Called when the test case *test* fails, but was marked with the
1738 :func:`expectedFailure` decorator.
1739
1740 The default implementation appends a tuple ``(test, formatted_err)`` to
1741 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1742 is a formatted traceback derived from *err*.
1743
1744
1745 .. method:: addUnexpectedSuccess(test)
1746
1747 Called when the test case *test* was marked with the
1748 :func:`expectedFailure` decorator, but succeeded.
1749
1750 The default implementation appends the test to the instance's
1751 :attr:`unexpectedSuccesses` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001752
Michael Foorddb43b5a2010-02-10 14:25:12 +00001753.. class:: TextTestResult(stream, descriptions, verbosity)
1754
1755 A concrete implementation of :class:`TestResult` used by the
1756 :class:`TextTestRunner`.
1757
1758 .. versionadded:: 2.7
1759 This class was previously named ``_TextTestResult``. The old name still
1760 exists as an alias but is deprecated.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001761
1762.. data:: defaultTestLoader
1763
1764 Instance of the :class:`TestLoader` class intended to be shared. If no
1765 customization of the :class:`TestLoader` is needed, this instance can be used
1766 instead of repeatedly creating new instances.
1767
1768
Senthil Kumaran1826f632016-01-14 21:57:57 -08001769.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, \
1770 failfast=False, buffer=False, resultclass=None)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001771
Senthil Kumaran1826f632016-01-14 21:57:57 -08001772 A basic test runner implementation which prints results on standard error. It
Georg Brandl8ec7f652007-08-15 14:28:01 +00001773 has a few configurable parameters, but is essentially very simple. Graphical
1774 applications which run test suites should provide alternate implementations.
1775
Georg Brandl9bc66822009-04-27 17:04:23 +00001776 .. method:: _makeResult()
1777
1778 This method returns the instance of ``TestResult`` used by :meth:`run`.
1779 It is not intended to be called directly, but can be overridden in
1780 subclasses to provide a custom ``TestResult``.
1781
Michael Foorddb43b5a2010-02-10 14:25:12 +00001782 ``_makeResult()`` instantiates the class or callable passed in the
1783 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Michael Foordefc2f492010-04-08 04:33:20 +00001784 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foorddb43b5a2010-02-10 14:25:12 +00001785 The result class is instantiated with the following arguments::
1786
1787 stream, descriptions, verbosity
1788
Georg Brandl8ec7f652007-08-15 14:28:01 +00001789
Ezio Melotti30abb3a2012-04-30 19:05:57 +03001790.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit[, verbosity[, failfast[, catchbreak[, buffer]]]]]]]]]])
Michael Foord55430352010-04-05 00:39:50 +00001791
Ezio Melotti30abb3a2012-04-30 19:05:57 +03001792 A command-line program that loads a set of tests from *module* and runs them;
1793 this is primarily for making test modules conveniently executable.
1794 The simplest use for this function is to include the following line at the
1795 end of a test script::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001796
1797 if __name__ == '__main__':
1798 unittest.main()
1799
Michael Foord5d31e052009-05-11 17:59:43 +00001800 You can run tests with more detailed information by passing in the verbosity
1801 argument::
1802
1803 if __name__ == '__main__':
1804 unittest.main(verbosity=2)
1805
R David Murray58512182014-01-02 13:38:02 -05001806 The *defaultTest* argument is the name of the test to run if no test names
1807 are specified via *argv*. If not specified or ``None`` and no test names are
1808 provided via *argv*, all tests found in *module* are run.
1809
Ezio Melotti30abb3a2012-04-30 19:05:57 +03001810 The *argv* argument can be a list of options passed to the program, with the
1811 first element being the program name. If not specified or ``None``,
1812 the values of :data:`sys.argv` are used.
1813
Georg Brandl8ec7f652007-08-15 14:28:01 +00001814 The *testRunner* argument can either be a test runner class or an already
Michael Foord829f6b82009-05-02 11:43:06 +00001815 created instance of it. By default ``main`` calls :func:`sys.exit` with
1816 an exit code indicating success or failure of the tests run.
1817
Ezio Melotti30abb3a2012-04-30 19:05:57 +03001818 The *testLoader* argument has to be a :class:`TestLoader` instance,
1819 and defaults to :data:`defaultTestLoader`.
1820
Michael Foord829f6b82009-05-02 11:43:06 +00001821 ``main`` supports being used from the interactive interpreter by passing in the
1822 argument ``exit=False``. This displays the result on standard output without
1823 calling :func:`sys.exit`::
1824
1825 >>> from unittest import main
1826 >>> main(module='test_module', exit=False)
1827
Ezio Melotti30abb3a2012-04-30 19:05:57 +03001828 The *failfast*, *catchbreak* and *buffer* parameters have the same
Éric Araujoa8132ec2010-12-16 03:53:53 +00001829 effect as the same-name `command-line options`_.
Michael Foordddb20df2010-04-04 23:28:44 +00001830
Michael Foord829f6b82009-05-02 11:43:06 +00001831 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1832 This stores the result of the tests run as the ``result`` attribute.
1833
1834 .. versionchanged:: 2.7
Ezio Melotti30abb3a2012-04-30 19:05:57 +03001835 The *exit*, *verbosity*, *failfast*, *catchbreak* and *buffer*
Michael Foordddb20df2010-04-04 23:28:44 +00001836 parameters were added.
Michael Foordb4a81c82009-05-29 20:33:46 +00001837
1838
1839load_tests Protocol
1840###################
1841
Michael Foord17565e52009-09-27 20:08:23 +00001842.. versionadded:: 2.7
1843
Michael Foordb4a81c82009-05-29 20:33:46 +00001844Modules or packages can customize how tests are loaded from them during normal
1845test runs or test discovery by implementing a function called ``load_tests``.
1846
1847If a test module defines ``load_tests`` it will be called by
1848:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1849
1850 load_tests(loader, standard_tests, None)
1851
1852It should return a :class:`TestSuite`.
1853
1854*loader* is the instance of :class:`TestLoader` doing the loading.
1855*standard_tests* are the tests that would be loaded by default from the
1856module. It is common for test modules to only want to add or remove tests
1857from the standard set of tests.
1858The third argument is used when loading packages as part of test discovery.
1859
1860A typical ``load_tests`` function that loads tests from a specific set of
1861:class:`TestCase` classes may look like::
1862
1863 test_cases = (TestCase1, TestCase2, TestCase3)
1864
1865 def load_tests(loader, tests, pattern):
1866 suite = TestSuite()
1867 for test_class in test_cases:
1868 tests = loader.loadTestsFromTestCase(test_class)
1869 suite.addTests(tests)
1870 return suite
1871
1872If discovery is started, either from the command line or by calling
1873:meth:`TestLoader.discover`, with a pattern that matches a package
1874name then the package :file:`__init__.py` will be checked for ``load_tests``.
1875
1876.. note::
1877
Ezio Melotti79b2dba2013-02-28 08:28:11 +02001878 The default pattern is ``'test*.py'``. This matches all Python files
1879 that start with ``'test'`` but *won't* match any test directories.
Michael Foordb4a81c82009-05-29 20:33:46 +00001880
Ezio Melotti79b2dba2013-02-28 08:28:11 +02001881 A pattern like ``'test*'`` will match test packages as well as
Michael Foordb4a81c82009-05-29 20:33:46 +00001882 modules.
1883
1884If the package :file:`__init__.py` defines ``load_tests`` then it will be
1885called and discovery not continued into the package. ``load_tests``
1886is called with the following arguments::
1887
1888 load_tests(loader, standard_tests, pattern)
1889
1890This should return a :class:`TestSuite` representing all the tests
1891from the package. (``standard_tests`` will only contain tests
1892collected from :file:`__init__.py`.)
1893
1894Because the pattern is passed into ``load_tests`` the package is free to
1895continue (and potentially modify) test discovery. A 'do nothing'
1896``load_tests`` function for a test package would look like::
1897
1898 def load_tests(loader, standard_tests, pattern):
1899 # top level directory cached on loader instance
1900 this_dir = os.path.dirname(__file__)
1901 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1902 standard_tests.addTests(package_tests)
1903 return standard_tests
Michael Foordba097ec2010-04-03 17:03:11 +00001904
1905
1906Class and Module Fixtures
1907-------------------------
1908
Michael Foord09e29802010-04-04 22:41:54 +00001909Class and module level fixtures are implemented in :class:`TestSuite`. When
1910the test suite encounters a test from a new class then :meth:`tearDownClass`
1911from the previous class (if there is one) is called, followed by
1912:meth:`setUpClass` from the new class.
Michael Foordba097ec2010-04-03 17:03:11 +00001913
Michael Foord09e29802010-04-04 22:41:54 +00001914Similarly if a test is from a different module from the previous test then
1915``tearDownModule`` from the previous module is run, followed by
1916``setUpModule`` from the new module.
Michael Foordba097ec2010-04-03 17:03:11 +00001917
Michael Foord09e29802010-04-04 22:41:54 +00001918After all the tests have run the final ``tearDownClass`` and
1919``tearDownModule`` are run.
Michael Foordba097ec2010-04-03 17:03:11 +00001920
Michael Foord09e29802010-04-04 22:41:54 +00001921Note that shared fixtures do not play well with [potential] features like test
1922parallelization and they break test isolation. They should be used with care.
Michael Foordba097ec2010-04-03 17:03:11 +00001923
Michael Foord09e29802010-04-04 22:41:54 +00001924The default ordering of tests created by the unittest test loaders is to group
1925all tests from the same modules and classes together. This will lead to
1926``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
1927module. If you randomize the order, so that tests from different modules and
1928classes are adjacent to each other, then these shared fixture functions may be
1929called multiple times in a single test run.
Michael Foordba097ec2010-04-03 17:03:11 +00001930
Michael Foord09e29802010-04-04 22:41:54 +00001931Shared fixtures are not intended to work with suites with non-standard
1932ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
1933support shared fixtures.
Michael Foordba097ec2010-04-03 17:03:11 +00001934
Michael Foord09e29802010-04-04 22:41:54 +00001935If there are any exceptions raised during one of the shared fixture functions
1936the test is reported as an error. Because there is no corresponding test
1937instance an ``_ErrorHolder`` object (that has the same interface as a
1938:class:`TestCase`) is created to represent the error. If you are just using
1939the standard unittest test runner then this detail doesn't matter, but if you
1940are a framework author it may be relevant.
Michael Foordba097ec2010-04-03 17:03:11 +00001941
1942
1943setUpClass and tearDownClass
1944~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1945
1946These must be implemented as class methods::
1947
1948 import unittest
1949
1950 class Test(unittest.TestCase):
1951 @classmethod
1952 def setUpClass(cls):
1953 cls._connection = createExpensiveConnectionObject()
1954
1955 @classmethod
1956 def tearDownClass(cls):
1957 cls._connection.destroy()
1958
Michael Foord09e29802010-04-04 22:41:54 +00001959If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
1960then you must call up to them yourself. The implementations in
1961:class:`TestCase` are empty.
Michael Foordba097ec2010-04-03 17:03:11 +00001962
Michael Foord09e29802010-04-04 22:41:54 +00001963If an exception is raised during a ``setUpClass`` then the tests in the class
1964are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord8dde2012010-06-05 21:57:03 +00001965have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
Ezio Melotti352def02013-03-27 20:11:55 +02001966:exc:`SkipTest` exception then the class will be reported as having been skipped
Michael Foord8dde2012010-06-05 21:57:03 +00001967instead of as an error.
Michael Foordba097ec2010-04-03 17:03:11 +00001968
1969
1970setUpModule and tearDownModule
1971~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1972
1973These should be implemented as functions::
1974
1975 def setUpModule():
1976 createConnection()
1977
1978 def tearDownModule():
1979 closeConnection()
1980
Michael Foord09e29802010-04-04 22:41:54 +00001981If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord8dde2012010-06-05 21:57:03 +00001982module will be run and the ``tearDownModule`` will not be run. If the exception is a
Ezio Melotti352def02013-03-27 20:11:55 +02001983:exc:`SkipTest` exception then the module will be reported as having been skipped
Michael Foord8dde2012010-06-05 21:57:03 +00001984instead of as an error.
Michael Foordba097ec2010-04-03 17:03:11 +00001985
1986
Michael Foord55430352010-04-05 00:39:50 +00001987Signal Handling
1988---------------
1989
Éric Araujoa8132ec2010-12-16 03:53:53 +00001990The :option:`-c/--catch <unittest -c>` command-line option to unittest,
1991along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
1992more friendly handling of control-C during a test run. With catch break
1993behavior enabled control-C will allow the currently running test to complete,
1994and the test run will then end and report all the results so far. A second
1995control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Michael Foord55430352010-04-05 00:39:50 +00001996
Michael Foord5c322ec2010-04-25 19:02:46 +00001997The control-c handling signal handler attempts to remain compatible with code or
1998tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
1999handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2000i.e. it has been replaced by the system under test and delegated to, then it
2001calls the default handler. This will normally be the expected behavior by code
2002that replaces an installed handler and delegates to it. For individual tests
2003that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2004decorator can be used.
2005
2006There are a few utility functions for framework authors to enable control-c
2007handling functionality within test frameworks.
Michael Foord55430352010-04-05 00:39:50 +00002008
2009.. function:: installHandler()
2010
Michael Foord31655032010-04-05 10:26:26 +00002011 Install the control-c handler. When a :const:`signal.SIGINT` is received
2012 (usually in response to the user pressing control-c) all registered results
Michael Foord55430352010-04-05 00:39:50 +00002013 have :meth:`~TestResult.stop` called.
2014
Michael Foord47b54402010-04-26 23:36:47 +00002015 .. versionadded:: 2.7
2016
Michael Foord55430352010-04-05 00:39:50 +00002017.. function:: registerResult(result)
2018
Michael Foord31655032010-04-05 10:26:26 +00002019 Register a :class:`TestResult` object for control-c handling. Registering a
Michael Foord55430352010-04-05 00:39:50 +00002020 result stores a weak reference to it, so it doesn't prevent the result from
2021 being garbage collected.
2022
Michael Foord5c322ec2010-04-25 19:02:46 +00002023 Registering a :class:`TestResult` object has no side-effects if control-c
2024 handling is not enabled, so test frameworks can unconditionally register
2025 all results they create independently of whether or not handling is enabled.
2026
Michael Foord47b54402010-04-26 23:36:47 +00002027 .. versionadded:: 2.7
2028
Michael Foord55430352010-04-05 00:39:50 +00002029.. function:: removeResult(result)
2030
Michael Foord31655032010-04-05 10:26:26 +00002031 Remove a registered result. Once a result has been removed then
Michael Foordd341ec82010-04-05 10:30:14 +00002032 :meth:`~TestResult.stop` will no longer be called on that result object in
Michael Foord31655032010-04-05 10:26:26 +00002033 response to a control-c.
Michael Foord55430352010-04-05 00:39:50 +00002034
Michael Foord47b54402010-04-26 23:36:47 +00002035 .. versionadded:: 2.7
2036
Michael Foord5c322ec2010-04-25 19:02:46 +00002037.. function:: removeHandler(function=None)
2038
2039 When called without arguments this function removes the control-c handler
2040 if it has been installed. This function can also be used as a test decorator
2041 to temporarily remove the handler whilst the test is being executed::
2042
2043 @unittest.removeHandler
2044 def test_signal_handling(self):
2045 ...
2046
Michael Foord47b54402010-04-26 23:36:47 +00002047 .. versionadded:: 2.7
2048