blob: 45270db55f2929683c6970eaf5c625cdca458445 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`unittest` --- Unit testing framework
2==========================================
3
4.. module:: unittest
5 :synopsis: Unit testing framework for Python.
6.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
7.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9.. sectionauthor:: Raymond Hettinger <python@rcn.com>
10
Ezio Melotti22170ed2010-11-20 09:57:27 +000011(If you are already familiar with the basic concepts of testing, you might want
12to skip to :ref:`the list of assert methods <assert-methods>`.)
Georg Brandl116aa622007-08-15 14:28:22 +000013
Georg Brandl116aa622007-08-15 14:28:22 +000014The Python unit testing framework, sometimes referred to as "PyUnit," is a
15Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
16turn, a Java version of Kent's Smalltalk testing framework. Each is the de
17facto standard unit testing framework for its respective language.
18
19:mod:`unittest` supports test automation, sharing of setup and shutdown code for
20tests, aggregation of tests into collections, and independence of the tests from
21the reporting framework. The :mod:`unittest` module provides classes that make
22it easy to support these qualities for a set of tests.
23
24To achieve this, :mod:`unittest` supports some important concepts:
25
26test fixture
27 A :dfn:`test fixture` represents the preparation needed to perform one or more
28 tests, and any associate cleanup actions. This may involve, for example,
29 creating temporary or proxy databases, directories, or starting a server
30 process.
31
32test case
33 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
34 response to a particular set of inputs. :mod:`unittest` provides a base class,
35 :class:`TestCase`, which may be used to create new test cases.
36
37test suite
38 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
39 used to aggregate tests that should be executed together.
40
41test runner
42 A :dfn:`test runner` is a component which orchestrates the execution of tests
43 and provides the outcome to the user. The runner may use a graphical interface,
44 a textual interface, or return a special value to indicate the results of
45 executing the tests.
46
47The test case and test fixture concepts are supported through the
48:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
49used when creating new tests, and the latter can be used when integrating
50existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson52baa292009-03-24 00:56:30 +000051fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
52:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
53and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
54can be passed to the constructor for these purposes. When the test is run, the
55fixture initialization is run first; if it succeeds, the cleanup method is run
56after the test has been executed, regardless of the outcome of the test. Each
57instance of the :class:`TestCase` will only be used to run a single test method,
58so a new fixture is created for each test.
Georg Brandl116aa622007-08-15 14:28:22 +000059
60Test suites are implemented by the :class:`TestSuite` class. This class allows
61individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson14a3dd72009-05-25 00:51:58 +000062all tests added directly to the suite and in "child" test suites are run.
Georg Brandl116aa622007-08-15 14:28:22 +000063
Benjamin Peterson52baa292009-03-24 00:56:30 +000064A test runner is an object that provides a single method,
65:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
66object as a parameter, and returns a result object. The class
67:class:`TestResult` is provided for use as the result object. :mod:`unittest`
68provides the :class:`TextTestRunner` as an example test runner which reports
69test results on the standard error stream by default. Alternate runners can be
70implemented for other environments (such as graphical environments) without any
71need to derive from a specific class.
Georg Brandl116aa622007-08-15 14:28:22 +000072
73
74.. seealso::
75
76 Module :mod:`doctest`
77 Another test-support module with a very different flavor.
78
Benjamin Petersonb48af542010-04-11 20:43:16 +000079 `unittest2: A backport of new unittest features for Python 2.4-2.6 <http://pypi.python.org/pypi/unittest2>`_
80 Many new features were added to unittest in Python 2.7, including test
81 discovery. unittest2 allows you to use these features with earlier
82 versions of Python.
83
Georg Brandl116aa622007-08-15 14:28:22 +000084 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000085 Kent Beck's original paper on testing frameworks using the pattern shared
86 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000087
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000088 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000089 Third-party unittest frameworks with a lighter-weight syntax for writing
90 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000091
Benjamin Petersonb48af542010-04-11 20:43:16 +000092 `The Python Testing Tools Taxonomy <http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy>`_
93 An extensive list of Python testing tools including functional testing
94 frameworks and mock object libraries.
Benjamin Petersond2397752009-06-27 23:45:02 +000095
Benjamin Petersonb48af542010-04-11 20:43:16 +000096 `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
97 A special-interest-group for discussion of testing, and testing tools,
98 in Python.
Benjamin Petersond2397752009-06-27 23:45:02 +000099
Michael Foord90efac72011-01-03 15:39:49 +0000100 The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is
101 a GUI tool for test discovery and execution. This is intended largely for ease of use
102 for those new to unit testing. For production environments it is recommended that
103 tests be driven by a continuous integration system such as `Hudson <http://hudson-ci.org/>`_
104 or `Buildbot <http://buildbot.net/trac>`_.
105
106
Georg Brandl116aa622007-08-15 14:28:22 +0000107.. _unittest-minimal-example:
108
109Basic example
110-------------
111
112The :mod:`unittest` module provides a rich set of tools for constructing and
113running tests. This section demonstrates that a small subset of the tools
114suffice to meet the needs of most users.
115
116Here is a short script to test three functions from the :mod:`random` module::
117
118 import random
119 import unittest
120
121 class TestSequenceFunctions(unittest.TestCase):
122
123 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000124 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +0000125
Benjamin Peterson52baa292009-03-24 00:56:30 +0000126 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000127 # make sure the shuffled sequence does not lose any elements
128 random.shuffle(self.seq)
129 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000130 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +0000131
Benjamin Peterson847a4112010-03-14 15:04:17 +0000132 # should raise an exception for an immutable sequence
133 self.assertRaises(TypeError, random.shuffle, (1,2,3))
134
Benjamin Peterson52baa292009-03-24 00:56:30 +0000135 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000136 element = random.choice(self.seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000137 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Benjamin Peterson52baa292009-03-24 00:56:30 +0000139 def test_sample(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000140 with self.assertRaises(ValueError):
141 random.sample(self.seq, 20)
Georg Brandl116aa622007-08-15 14:28:22 +0000142 for element in random.sample(self.seq, 5):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000143 self.assertTrue(element in self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145 if __name__ == '__main__':
146 unittest.main()
147
Benjamin Peterson52baa292009-03-24 00:56:30 +0000148A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000149individual tests are defined with methods whose names start with the letters
150``test``. This naming convention informs the test runner about which methods
151represent tests.
152
Benjamin Peterson52baa292009-03-24 00:56:30 +0000153The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
Michael Foord34c94622010-02-10 15:51:42 +0000154expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
Benjamin Peterson52baa292009-03-24 00:56:30 +0000155:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
156These methods are used instead of the :keyword:`assert` statement so the test
157runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000158
Benjamin Peterson52baa292009-03-24 00:56:30 +0000159When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
160method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
161defined, the test runner will invoke that method after each test. In the
162example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
163test.
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo713d3032010-11-18 16:38:46 +0000166provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000167line, the above script produces an output that looks like this::
168
169 ...
170 ----------------------------------------------------------------------
171 Ran 3 tests in 0.000s
172
173 OK
174
175Instead of :func:`unittest.main`, there are other ways to run the tests with a
176finer level of control, less terse output, and no requirement to be run from the
177command line. For example, the last two lines may be replaced with::
178
179 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
180 unittest.TextTestRunner(verbosity=2).run(suite)
181
182Running the revised script from the interpreter or another script produces the
183following output::
184
Ezio Melottid59e44a2010-02-28 03:46:13 +0000185 test_choice (__main__.TestSequenceFunctions) ... ok
186 test_sample (__main__.TestSequenceFunctions) ... ok
187 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189 ----------------------------------------------------------------------
190 Ran 3 tests in 0.110s
191
192 OK
193
194The above examples show the most commonly used :mod:`unittest` features which
195are sufficient to meet many everyday testing needs. The remainder of the
196documentation explores the full feature set from first principles.
197
Benjamin Petersonb48af542010-04-11 20:43:16 +0000198
199.. _unittest-command-line-interface:
200
Éric Araujo76338ec2010-11-26 23:46:18 +0000201Command-Line Interface
Benjamin Petersonb48af542010-04-11 20:43:16 +0000202----------------------
203
204The unittest module can be used from the command line to run tests from
205modules, classes or even individual test methods::
206
207 python -m unittest test_module1 test_module2
208 python -m unittest test_module.TestClass
209 python -m unittest test_module.TestClass.test_method
210
211You can pass in a list with any combination of module names, and fully
212qualified class or method names.
213
Michael Foord37d120a2010-12-04 01:11:21 +0000214Test modules can be specified by file path as well::
215
216 python -m unittest tests/test_something.py
217
218This allows you to use the shell filename completion to specify the test module.
219The file specified must still be importable as a module. The path is converted
220to a module name by removing the '.py' and converting path separators into '.'.
221If you want to execute a test file that isn't importable as a module you should
222execute the file directly instead.
223
Benjamin Petersonb48af542010-04-11 20:43:16 +0000224You can run tests with more detail (higher verbosity) by passing in the -v flag::
225
226 python -m unittest -v test_module
227
Michael Foord086f3082010-11-21 21:28:01 +0000228When executed without arguments :ref:`unittest-test-discovery` is started::
229
230 python -m unittest
231
Éric Araujo713d3032010-11-18 16:38:46 +0000232For a list of all the command-line options::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000233
234 python -m unittest -h
235
Georg Brandl67b21b72010-08-17 15:07:14 +0000236.. versionchanged:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000237 In earlier versions it was only possible to run individual test methods and
238 not modules or classes.
239
240
Éric Araujo76338ec2010-11-26 23:46:18 +0000241Command-line options
242~~~~~~~~~~~~~~~~~~~~
Benjamin Petersonb48af542010-04-11 20:43:16 +0000243
Éric Araujod3309df2010-11-21 03:09:17 +0000244:program:`unittest` supports these command-line options:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000245
Éric Araujo713d3032010-11-18 16:38:46 +0000246.. program:: unittest
Benjamin Petersonb48af542010-04-11 20:43:16 +0000247
Éric Araujo713d3032010-11-18 16:38:46 +0000248.. cmdoption:: -b, --buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +0000249
Éric Araujo713d3032010-11-18 16:38:46 +0000250 The standard output and standard error streams are buffered during the test
251 run. Output during a passing test is discarded. Output is echoed normally
252 on test fail or error and is added to the failure messages.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000253
Éric Araujo713d3032010-11-18 16:38:46 +0000254.. cmdoption:: -c, --catch
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000255
Éric Araujo713d3032010-11-18 16:38:46 +0000256 Control-C during the test run waits for the current test to end and then
257 reports all the results so far. A second control-C raises the normal
258 :exc:`KeyboardInterrupt` exception.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000259
Éric Araujo713d3032010-11-18 16:38:46 +0000260 See `Signal Handling`_ for the functions that provide this functionality.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000261
Éric Araujo713d3032010-11-18 16:38:46 +0000262.. cmdoption:: -f, --failfast
263
264 Stop the test run on the first error or failure.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000265
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000266.. versionadded:: 3.2
Éric Araujod6c5f742010-12-16 00:07:01 +0000267 The command-line options ``-b``, ``-c`` and ``-f`` were added.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000268
269The command line can also be used for test discovery, for running all of the
270tests in a project or just a subset.
271
272
273.. _unittest-test-discovery:
274
275Test Discovery
276--------------
277
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000278.. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +0000279
Ezio Melotti3d995842011-03-08 16:17:35 +0200280Unittest supports simple test discovery. In order to be compatible with test
281discovery, all of the test files must be :ref:`modules <tut-modules>` or
282:ref:`packages <tut-packages>` importable from the top-level directory of
283the project (this means that their filenames must be valid
284:ref:`identifiers <identifiers>`).
Benjamin Petersonb48af542010-04-11 20:43:16 +0000285
286Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
Éric Araujo713d3032010-11-18 16:38:46 +0000287used from the command line. The basic command-line usage is::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000288
289 cd project_directory
290 python -m unittest discover
291
Michael Foord086f3082010-11-21 21:28:01 +0000292.. note::
293
294 As a shortcut, ``python -m unittest`` is the equivalent of
295 ``python -m unittest discover``. If you want to pass arguments to test
Éric Araujo941afed2011-09-01 02:47:34 +0200296 discovery the ``discover`` sub-command must be used explicitly.
Michael Foord086f3082010-11-21 21:28:01 +0000297
Benjamin Petersonb48af542010-04-11 20:43:16 +0000298The ``discover`` sub-command has the following options:
299
Éric Araujo713d3032010-11-18 16:38:46 +0000300.. program:: unittest discover
301
302.. cmdoption:: -v, --verbose
303
304 Verbose output
305
306.. cmdoption:: -s directory
307
Éric Araujo941afed2011-09-01 02:47:34 +0200308 Directory to start discovery (``.`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000309
310.. cmdoption:: -p pattern
311
Éric Araujo941afed2011-09-01 02:47:34 +0200312 Pattern to match test files (``test*.py`` default)
Éric Araujo713d3032010-11-18 16:38:46 +0000313
314.. cmdoption:: -t directory
315
316 Top level directory of project (defaults to start directory)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000317
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000318The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
319as positional arguments in that order. The following two command lines
320are equivalent::
Benjamin Petersonb48af542010-04-11 20:43:16 +0000321
322 python -m unittest discover -s project_directory -p '*_test.py'
323 python -m unittest discover project_directory '*_test.py'
324
Michael Foord16f3e902010-05-08 15:13:42 +0000325As well as being a path it is possible to pass a package name, for example
326``myproject.subpackage.test``, as the start directory. The package name you
327supply will then be imported and its location on the filesystem will be used
328as the start directory.
329
330.. caution::
331
Senthil Kumaran916bd382010-10-15 12:55:19 +0000332 Test discovery loads tests by importing them. Once test discovery has found
333 all the test files from the start directory you specify it turns the paths
334 into package names to import. For example :file:`foo/bar/baz.py` will be
Michael Foord16f3e902010-05-08 15:13:42 +0000335 imported as ``foo.bar.baz``.
336
337 If you have a package installed globally and attempt test discovery on
338 a different copy of the package then the import *could* happen from the
339 wrong place. If this happens test discovery will warn you and exit.
340
341 If you supply the start directory as a package name rather than a
342 path to a directory then discover assumes that whichever location it
343 imports from is the location you intended, so you will not get the
344 warning.
345
Benjamin Petersonb48af542010-04-11 20:43:16 +0000346Test modules and packages can customize test loading and discovery by through
347the `load_tests protocol`_.
348
349
Georg Brandl116aa622007-08-15 14:28:22 +0000350.. _organizing-tests:
351
352Organizing test code
353--------------------
354
355The basic building blocks of unit testing are :dfn:`test cases` --- single
356scenarios that must be set up and checked for correctness. In :mod:`unittest`,
Raymond Hettinger833ad0e2011-02-06 21:00:38 +0000357test cases are represented by :class:`unittest.TestCase` instances.
358To make your own test cases you must write subclasses of
359:class:`TestCase` or use :class:`FunctionTestCase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361An instance of a :class:`TestCase`\ -derived class is an object that can
362completely run a single test method, together with optional set-up and tidy-up
363code.
364
365The testing code of a :class:`TestCase` instance should be entirely self
366contained, such that it can be run either in isolation or in arbitrary
367combination with any number of other test cases.
368
Benjamin Peterson52baa292009-03-24 00:56:30 +0000369The simplest :class:`TestCase` subclass will simply override the
370:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372 import unittest
373
374 class DefaultWidgetSizeTestCase(unittest.TestCase):
375 def runTest(self):
376 widget = Widget('The widget')
377 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
378
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000379Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000380methods provided by the :class:`TestCase` base class. If the test fails, an
381exception will be raised, and :mod:`unittest` will identify the test case as a
382:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
383helps you identify where the problem is: :dfn:`failures` are caused by incorrect
384results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
385code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387The way to run a test case will be described later. For now, note that to
388construct an instance of such a test case, we call its constructor without
389arguments::
390
391 testCase = DefaultWidgetSizeTestCase()
392
393Now, such test cases can be numerous, and their set-up can be repetitive. In
394the above case, constructing a :class:`Widget` in each of 100 Widget test case
395subclasses would mean unsightly duplication.
396
397Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000398:meth:`~TestCase.setUp`, which the testing framework will automatically call for
399us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401 import unittest
402
403 class SimpleWidgetTestCase(unittest.TestCase):
404 def setUp(self):
405 self.widget = Widget('The widget')
406
407 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
408 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000409 self.assertEqual(self.widget.size(), (50,50),
410 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412 class WidgetResizeTestCase(SimpleWidgetTestCase):
413 def runTest(self):
414 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000415 self.assertEqual(self.widget.size(), (100,150),
416 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Benjamin Peterson52baa292009-03-24 00:56:30 +0000418If the :meth:`~TestCase.setUp` method raises an exception while the test is
419running, the framework will consider the test to have suffered an error, and the
420:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000421
Benjamin Peterson52baa292009-03-24 00:56:30 +0000422Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
423after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425 import unittest
426
427 class SimpleWidgetTestCase(unittest.TestCase):
428 def setUp(self):
429 self.widget = Widget('The widget')
430
431 def tearDown(self):
432 self.widget.dispose()
433 self.widget = None
434
Benjamin Peterson52baa292009-03-24 00:56:30 +0000435If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
436be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438Such a working environment for the testing code is called a :dfn:`fixture`.
439
440Often, many small test cases will use the same fixture. In this case, we would
441end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
442classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000443discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
444mechanism::
445
446 import unittest
447
448 class WidgetTestCase(unittest.TestCase):
449 def setUp(self):
450 self.widget = Widget('The widget')
451
452 def tearDown(self):
453 self.widget.dispose()
454 self.widget = None
455
Ezio Melottid59e44a2010-02-28 03:46:13 +0000456 def test_default_size(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000457 self.assertEqual(self.widget.size(), (50,50),
458 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000459
Ezio Melottid59e44a2010-02-28 03:46:13 +0000460 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000461 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000462 self.assertEqual(self.widget.size(), (100,150),
463 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000464
Benjamin Peterson52baa292009-03-24 00:56:30 +0000465Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
466provided two different test methods. Class instances will now each run one of
Ezio Melottid59e44a2010-02-28 03:46:13 +0000467the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000468separately for each instance. When creating an instance we must specify the
469test method it is to run. We do this by passing the method name in the
470constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000471
Ezio Melottid59e44a2010-02-28 03:46:13 +0000472 defaultSizeTestCase = WidgetTestCase('test_default_size')
473 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000474
475Test case instances are grouped together according to the features they test.
476:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
477represented by :mod:`unittest`'s :class:`TestSuite` class::
478
479 widgetTestSuite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000480 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
481 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000482
483For the ease of running tests, as we will see later, it is a good idea to
484provide in each test module a callable object that returns a pre-built test
485suite::
486
487 def suite():
488 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000489 suite.addTest(WidgetTestCase('test_default_size'))
490 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000491 return suite
492
493or even::
494
495 def suite():
Ezio Melottid59e44a2010-02-28 03:46:13 +0000496 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498 return unittest.TestSuite(map(WidgetTestCase, tests))
499
500Since it is a common pattern to create a :class:`TestCase` subclass with many
501similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
502class that can be used to automate the process of creating a test suite and
503populating it with individual tests. For example, ::
504
505 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
506
Ezio Melottid59e44a2010-02-28 03:46:13 +0000507will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
508``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000509name prefix to identify test methods automatically.
510
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000511Note that the order in which the various test cases will be run is
512determined by sorting the test function names with respect to the
513built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515Often it is desirable to group suites of test cases together, so as to run tests
516for the whole system at once. This is easy, since :class:`TestSuite` instances
517can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
518added to a :class:`TestSuite`::
519
520 suite1 = module1.TheTestSuite()
521 suite2 = module2.TheTestSuite()
522 alltests = unittest.TestSuite([suite1, suite2])
523
524You can place the definitions of test cases and test suites in the same modules
525as the code they are to test (such as :file:`widget.py`), but there are several
526advantages to placing the test code in a separate module, such as
527:file:`test_widget.py`:
528
529* The test module can be run standalone from the command line.
530
531* The test code can more easily be separated from shipped code.
532
533* There is less temptation to change test code to fit the code it tests without
534 a good reason.
535
536* Test code should be modified much less frequently than the code it tests.
537
538* Tested code can be refactored more easily.
539
540* Tests for modules written in C must be in separate modules anyway, so why not
541 be consistent?
542
543* If the testing strategy changes, there is no need to change the source code.
544
545
546.. _legacy-unit-tests:
547
548Re-using old test code
549----------------------
550
551Some users will find that they have existing test code that they would like to
552run from :mod:`unittest`, without converting every old test function to a
553:class:`TestCase` subclass.
554
555For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
556This subclass of :class:`TestCase` can be used to wrap an existing test
557function. Set-up and tear-down functions can also be provided.
558
559Given the following test function::
560
561 def testSomething():
562 something = makeSomething()
563 assert something.name is not None
564 # ...
565
566one can create an equivalent test case instance as follows::
567
568 testcase = unittest.FunctionTestCase(testSomething)
569
570If there are additional set-up and tear-down methods that should be called as
571part of the test case's operation, they can also be provided like so::
572
573 testcase = unittest.FunctionTestCase(testSomething,
574 setUp=makeSomethingDB,
575 tearDown=deleteSomethingDB)
576
577To make migrating existing test suites easier, :mod:`unittest` supports tests
578raising :exc:`AssertionError` to indicate test failure. However, it is
579recommended that you use the explicit :meth:`TestCase.fail\*` and
580:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
581may treat :exc:`AssertionError` differently.
582
583.. note::
584
Benjamin Petersond2397752009-06-27 23:45:02 +0000585 Even though :class:`FunctionTestCase` can be used to quickly convert an
586 existing test base over to a :mod:`unittest`\ -based system, this approach is
587 not recommended. Taking the time to set up proper :class:`TestCase`
588 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000589
Benjamin Peterson52baa292009-03-24 00:56:30 +0000590In some cases, the existing tests may have been written using the :mod:`doctest`
591module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
592automatically build :class:`unittest.TestSuite` instances from the existing
593:mod:`doctest`\ -based tests.
594
Georg Brandl116aa622007-08-15 14:28:22 +0000595
Benjamin Peterson5254c042009-03-23 22:25:03 +0000596.. _unittest-skipping:
597
598Skipping tests and expected failures
599------------------------------------
600
Michael Foordf5c851a2010-02-05 21:48:03 +0000601.. versionadded:: 3.1
602
Benjamin Peterson5254c042009-03-23 22:25:03 +0000603Unittest supports skipping individual test methods and even whole classes of
604tests. In addition, it supports marking a test as a "expected failure," a test
605that is broken and will fail, but shouldn't be counted as a failure on a
606:class:`TestResult`.
607
608Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
609or one of its conditional variants.
610
611Basic skipping looks like this: ::
612
613 class MyTestCase(unittest.TestCase):
614
615 @unittest.skip("demonstrating skipping")
616 def test_nothing(self):
617 self.fail("shouldn't happen")
618
Benjamin Petersond2397752009-06-27 23:45:02 +0000619 @unittest.skipIf(mylib.__version__ < (1, 3),
620 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000621 def test_format(self):
622 # Tests that work for only a certain version of the library.
623 pass
624
625 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
626 def test_windows_support(self):
627 # windows specific testing code
628 pass
629
Benjamin Peterson5254c042009-03-23 22:25:03 +0000630This is the output of running the example above in verbose mode: ::
631
Benjamin Petersonded31c42009-03-30 15:04:16 +0000632 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000633 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000634 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000635
636 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000637 Ran 3 tests in 0.005s
638
639 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000640
641Classes can be skipped just like methods: ::
642
643 @skip("showing class skipping")
644 class MySkippedTestCase(unittest.TestCase):
645 def test_not_run(self):
646 pass
647
Benjamin Peterson52baa292009-03-24 00:56:30 +0000648:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
649that needs to be set up is not available.
650
Benjamin Peterson5254c042009-03-23 22:25:03 +0000651Expected failures use the :func:`expectedFailure` decorator. ::
652
653 class ExpectedFailureTestCase(unittest.TestCase):
654 @unittest.expectedFailure
655 def test_fail(self):
656 self.assertEqual(1, 0, "broken")
657
658It's easy to roll your own skipping decorators by making a decorator that calls
659:func:`skip` on the test when it wants it to be skipped. This decorator skips
660the test unless the passed object has a certain attribute: ::
661
662 def skipUnlessHasattr(obj, attr):
663 if hasattr(obj, attr):
664 return lambda func: func
665 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
666
667The following decorators implement test skipping and expected failures:
668
Georg Brandl8a1caa22010-07-29 16:01:11 +0000669.. decorator:: skip(reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000670
671 Unconditionally skip the decorated test. *reason* should describe why the
672 test is being skipped.
673
Georg Brandl8a1caa22010-07-29 16:01:11 +0000674.. decorator:: skipIf(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000675
676 Skip the decorated test if *condition* is true.
677
Georg Brandl8a1caa22010-07-29 16:01:11 +0000678.. decorator:: skipUnless(condition, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000679
Georg Brandl6faee4e2010-09-21 14:48:28 +0000680 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000681
Georg Brandl8a1caa22010-07-29 16:01:11 +0000682.. decorator:: expectedFailure
Benjamin Peterson5254c042009-03-23 22:25:03 +0000683
684 Mark the test as an expected failure. If the test fails when run, the test
685 is not counted as a failure.
686
Benjamin Petersonb48af542010-04-11 20:43:16 +0000687Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
688Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.
689
Benjamin Peterson5254c042009-03-23 22:25:03 +0000690
Georg Brandl116aa622007-08-15 14:28:22 +0000691.. _unittest-contents:
692
693Classes and functions
694---------------------
695
Benjamin Peterson52baa292009-03-24 00:56:30 +0000696This section describes in depth the API of :mod:`unittest`.
697
698
699.. _testcase-objects:
700
701Test cases
702~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Georg Brandl7f01a132009-09-16 15:58:14 +0000704.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706 Instances of the :class:`TestCase` class represent the smallest testable units
707 in the :mod:`unittest` universe. This class is intended to be used as a base
708 class, with specific tests being implemented by concrete subclasses. This class
709 implements the interface needed by the test runner to allow it to drive the
710 test, and methods that the test code can use to check for and report various
711 kinds of failure.
712
713 Each instance of :class:`TestCase` will run a single test method: the method
714 named *methodName*. If you remember, we had an earlier example that went
715 something like this::
716
717 def suite():
718 suite = unittest.TestSuite()
Ezio Melottid59e44a2010-02-28 03:46:13 +0000719 suite.addTest(WidgetTestCase('test_default_size'))
720 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000721 return suite
722
723 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
724 single test.
725
Michael Foord1341bb02011-03-14 19:01:46 -0400726 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +0200727 :class:`TestCase` can be instantiated successfully without providing a method
728 name. This makes it easier to experiment with :class:`TestCase` from the
Michael Foord32e1d832011-01-03 17:00:11 +0000729 interactive interpreter.
730
Benjamin Peterson52baa292009-03-24 00:56:30 +0000731 *methodName* defaults to :meth:`runTest`.
732
733 :class:`TestCase` instances provide three groups of methods: one group used
734 to run the test, another used by the test implementation to check conditions
735 and report failures, and some inquiry methods allowing information about the
736 test itself to be gathered.
737
738 Methods in the first group (running the test) are:
739
740
741 .. method:: setUp()
742
743 Method called to prepare the test fixture. This is called immediately
744 before calling the test method; any exception raised by this method will
745 be considered an error rather than a test failure. The default
746 implementation does nothing.
747
748
749 .. method:: tearDown()
750
751 Method called immediately after the test method has been called and the
752 result recorded. This is called even if the test method raised an
753 exception, so the implementation in subclasses may need to be particularly
754 careful about checking internal state. Any exception raised by this
755 method will be considered an error rather than a test failure. This
756 method will only be called if the :meth:`setUp` succeeds, regardless of
757 the outcome of the test method. The default implementation does nothing.
758
759
Benjamin Petersonb48af542010-04-11 20:43:16 +0000760 .. method:: setUpClass()
761
762 A class method called before tests in an individual class run.
763 ``setUpClass`` is called with the class as the only argument
764 and must be decorated as a :func:`classmethod`::
765
766 @classmethod
767 def setUpClass(cls):
768 ...
769
770 See `Class and Module Fixtures`_ for more details.
771
772 .. versionadded:: 3.2
773
774
775 .. method:: tearDownClass()
776
777 A class method called after tests in an individual class have run.
778 ``tearDownClass`` is called with the class as the only argument
779 and must be decorated as a :meth:`classmethod`::
780
781 @classmethod
782 def tearDownClass(cls):
783 ...
784
785 See `Class and Module Fixtures`_ for more details.
786
787 .. versionadded:: 3.2
788
789
Georg Brandl7f01a132009-09-16 15:58:14 +0000790 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000791
792 Run the test, collecting the result into the test result object passed as
Ezio Melotti75b2a5e2010-11-20 10:13:45 +0000793 *result*. If *result* is omitted or ``None``, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000794 object is created (by calling the :meth:`defaultTestResult` method) and
Michael Foord1341bb02011-03-14 19:01:46 -0400795 used. The result object is returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000796
797 The same effect may be had by simply calling the :class:`TestCase`
798 instance.
799
Michael Foord1341bb02011-03-14 19:01:46 -0400800 .. versionchanged:: 3.3
801 Previous versions of ``run`` did not return the result. Neither did
802 calling an instance.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000803
Benjamin Petersone549ead2009-03-28 21:42:05 +0000804 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000805
Stefan Kraha5bf3f52010-05-19 16:09:41 +0000806 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000807 test. See :ref:`unittest-skipping` for more information.
808
Ezio Melotti7afd3f52010-04-20 09:32:54 +0000809 .. versionadded:: 3.1
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000810
Benjamin Peterson52baa292009-03-24 00:56:30 +0000811
812 .. method:: debug()
813
814 Run the test without collecting the result. This allows exceptions raised
815 by the test to be propagated to the caller, and can be used to support
816 running tests under a debugger.
817
Ezio Melotti22170ed2010-11-20 09:57:27 +0000818 .. _assert-methods:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000819
Ezio Melotti4370b302010-11-03 20:39:14 +0000820 The :class:`TestCase` class provides a number of methods to check for and
821 report failures, such as:
Benjamin Peterson52baa292009-03-24 00:56:30 +0000822
Ezio Melotti4370b302010-11-03 20:39:14 +0000823 +-----------------------------------------+-----------------------------+---------------+
824 | Method | Checks that | New in |
825 +=========================================+=============================+===============+
826 | :meth:`assertEqual(a, b) | ``a == b`` | |
827 | <TestCase.assertEqual>` | | |
828 +-----------------------------------------+-----------------------------+---------------+
829 | :meth:`assertNotEqual(a, b) | ``a != b`` | |
830 | <TestCase.assertNotEqual>` | | |
831 +-----------------------------------------+-----------------------------+---------------+
832 | :meth:`assertTrue(x) | ``bool(x) is True`` | |
833 | <TestCase.assertTrue>` | | |
834 +-----------------------------------------+-----------------------------+---------------+
835 | :meth:`assertFalse(x) | ``bool(x) is False`` | |
836 | <TestCase.assertFalse>` | | |
837 +-----------------------------------------+-----------------------------+---------------+
838 | :meth:`assertIs(a, b) | ``a is b`` | 3.1 |
839 | <TestCase.assertIs>` | | |
840 +-----------------------------------------+-----------------------------+---------------+
841 | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 |
842 | <TestCase.assertIsNot>` | | |
843 +-----------------------------------------+-----------------------------+---------------+
844 | :meth:`assertIsNone(x) | ``x is None`` | 3.1 |
845 | <TestCase.assertIsNone>` | | |
846 +-----------------------------------------+-----------------------------+---------------+
847 | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 |
848 | <TestCase.assertIsNotNone>` | | |
849 +-----------------------------------------+-----------------------------+---------------+
850 | :meth:`assertIn(a, b) | ``a in b`` | 3.1 |
851 | <TestCase.assertIn>` | | |
852 +-----------------------------------------+-----------------------------+---------------+
853 | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 |
854 | <TestCase.assertNotIn>` | | |
855 +-----------------------------------------+-----------------------------+---------------+
856 | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 |
857 | <TestCase.assertIsInstance>` | | |
858 +-----------------------------------------+-----------------------------+---------------+
859 | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 |
860 | <TestCase.assertNotIsInstance>` | | |
861 +-----------------------------------------+-----------------------------+---------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000862
Ezio Melottib4dc2502011-05-06 15:01:41 +0300863 All the assert methods accept a *msg* argument that, if specified, is used
864 as the error message on failure (see also :data:`longMessage`).
865 Note that the *msg* keyword argument can be passed to :meth:`assertRaises`,
866 :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`
867 only when they are used as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000868
Michael Foorde180d392011-01-28 19:51:48 +0000869 .. method:: assertEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000870
Michael Foorde180d392011-01-28 19:51:48 +0000871 Test that *first* and *second* are equal. If the values do not
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000872 compare equal, the test will fail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000873
Michael Foorde180d392011-01-28 19:51:48 +0000874 In addition, if *first* and *second* are the exact same type and one of
Michael Foord02834952010-02-08 23:10:39 +0000875 list, tuple, dict, set, frozenset or str or any type that a subclass
876 registers with :meth:`addTypeEqualityFunc` the type specific equality
877 function will be called in order to generate a more useful default
Ezio Melotti22170ed2010-11-20 09:57:27 +0000878 error message (see also the :ref:`list of type-specific methods
879 <type-specific-methods>`).
Ezio Melotti4841fd62010-11-05 15:43:40 +0000880
Raymond Hettinger35a88362009-04-09 00:08:24 +0000881 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000882 Added the automatic calling of type specific equality function.
883
Michael Foord28a817e2010-02-09 00:03:57 +0000884 .. versionchanged:: 3.2
885 :meth:`assertMultiLineEqual` added as the default type equality
886 function for comparing strings.
Michael Foord02834952010-02-08 23:10:39 +0000887
Benjamin Peterson52baa292009-03-24 00:56:30 +0000888
Michael Foorde180d392011-01-28 19:51:48 +0000889 .. method:: assertNotEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000890
Michael Foorde180d392011-01-28 19:51:48 +0000891 Test that *first* and *second* are not equal. If the values do
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000892 compare equal, the test will fail.
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000893
Ezio Melotti4370b302010-11-03 20:39:14 +0000894 .. method:: assertTrue(expr, msg=None)
Ezio Melotti4841fd62010-11-05 15:43:40 +0000895 assertFalse(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000896
Ezio Melotti4841fd62010-11-05 15:43:40 +0000897 Test that *expr* is true (or false).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000898
Ezio Melotti4841fd62010-11-05 15:43:40 +0000899 Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
900 is True`` (use ``assertIs(expr, True)`` for the latter). This method
901 should also be avoided when more specific methods are available (e.g.
902 ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
903 provide a better error message in case of failure.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000904
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000905
Michael Foorde180d392011-01-28 19:51:48 +0000906 .. method:: assertIs(first, second, msg=None)
907 assertIsNot(first, second, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000908
Michael Foorde180d392011-01-28 19:51:48 +0000909 Test that *first* and *second* evaluate (or don't evaluate) to the
Ezio Melottiaddc6f52010-12-18 20:00:04 +0000910 same object.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000911
Raymond Hettinger35a88362009-04-09 00:08:24 +0000912 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000913
914
Ezio Melotti4370b302010-11-03 20:39:14 +0000915 .. method:: assertIsNone(expr, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000916 assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000917
Ezio Melotti9794a262010-11-04 14:52:13 +0000918 Test that *expr* is (or is not) None.
Benjamin Petersonb48af542010-04-11 20:43:16 +0000919
Ezio Melotti4370b302010-11-03 20:39:14 +0000920 .. versionadded:: 3.1
Benjamin Petersonb48af542010-04-11 20:43:16 +0000921
922
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000923 .. method:: assertIn(first, second, msg=None)
924 assertNotIn(first, second, msg=None)
925
Ezio Melotti4841fd62010-11-05 15:43:40 +0000926 Test that *first* is (or is not) in *second*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000927
Raymond Hettinger35a88362009-04-09 00:08:24 +0000928 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000929
930
Ezio Melotti9c02c2f2010-11-03 20:45:31 +0000931 .. method:: assertIsInstance(obj, cls, msg=None)
Ezio Melotti9794a262010-11-04 14:52:13 +0000932 assertNotIsInstance(obj, cls, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000933
Ezio Melotti9794a262010-11-04 14:52:13 +0000934 Test that *obj* is (or is not) an instance of *cls* (which can be a
935 class or a tuple of classes, as supported by :func:`isinstance`).
Ezio Melottifabf0272011-11-18 18:59:36 +0200936 To check for a specific type (without including superclasses) use
937 :func:`assertIs(type(obj), cls) <assertIs>`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000938
Ezio Melotti4370b302010-11-03 20:39:14 +0000939 .. versionadded:: 3.2
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000940
941
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000942
Ezio Melotti4370b302010-11-03 20:39:14 +0000943 It is also possible to check that exceptions and warnings are raised using
944 the following methods:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000945
Ezio Melotti4370b302010-11-03 20:39:14 +0000946 +---------------------------------------------------------+--------------------------------------+------------+
947 | Method | Checks that | New in |
948 +=========================================================+======================================+============+
Éric Araujo941afed2011-09-01 02:47:34 +0200949 | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000950 | <TestCase.assertRaises>` | | |
951 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200952 | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 |
953 | <TestCase.assertRaisesRegex>` | and the message matches *re* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000954 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200955 | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
Ezio Melotti4370b302010-11-03 20:39:14 +0000956 | <TestCase.assertWarns>` | | |
957 +---------------------------------------------------------+--------------------------------------+------------+
Éric Araujo941afed2011-09-01 02:47:34 +0200958 | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 |
959 | <TestCase.assertWarnsRegex>` | and the message matches *re* | |
Ezio Melotti4370b302010-11-03 20:39:14 +0000960 +---------------------------------------------------------+--------------------------------------+------------+
Benjamin Peterson52baa292009-03-24 00:56:30 +0000961
Georg Brandl7f01a132009-09-16 15:58:14 +0000962 .. method:: assertRaises(exception, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300963 assertRaises(exception, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000964
965 Test that an exception is raised when *callable* is called with any
966 positional or keyword arguments that are also passed to
967 :meth:`assertRaises`. The test passes if *exception* is raised, is an
968 error if another exception is raised, or fails if no exception is raised.
969 To catch any of a group of exceptions, a tuple containing the exception
970 classes may be passed as *exception*.
971
Ezio Melottib4dc2502011-05-06 15:01:41 +0300972 If only the *exception* and possibly the *msg* arguments are given,
973 return a context manager so that the code under test can be written
974 inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000975
Michael Foord41531f22010-02-05 21:13:40 +0000976 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000977 do_something()
978
Ezio Melottib4dc2502011-05-06 15:01:41 +0300979 When used as a context manager, :meth:`assertRaises` accepts the
980 additional keyword argument *msg*.
981
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000982 The context manager will store the caught exception object in its
Ezio Melotti49008232010-02-08 21:57:48 +0000983 :attr:`exception` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000984 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000985
Georg Brandl8a1caa22010-07-29 16:01:11 +0000986 with self.assertRaises(SomeException) as cm:
987 do_something()
Michael Foord41531f22010-02-05 21:13:40 +0000988
Georg Brandl8a1caa22010-07-29 16:01:11 +0000989 the_exception = cm.exception
990 self.assertEqual(the_exception.error_code, 3)
Michael Foord41531f22010-02-05 21:13:40 +0000991
Ezio Melotti49008232010-02-08 21:57:48 +0000992 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000993 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000994
Ezio Melotti49008232010-02-08 21:57:48 +0000995 .. versionchanged:: 3.2
996 Added the :attr:`exception` attribute.
997
Ezio Melottib4dc2502011-05-06 15:01:41 +0300998 .. versionchanged:: 3.3
999 Added the *msg* keyword argument when used as a context manager.
1000
Benjamin Peterson52baa292009-03-24 00:56:30 +00001001
Ezio Melottied3a7d22010-12-01 02:32:32 +00001002 .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001003 assertRaisesRegex(exception, regex, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001004
Ezio Melottied3a7d22010-12-01 02:32:32 +00001005 Like :meth:`assertRaises` but also tests that *regex* matches
1006 on the string representation of the raised exception. *regex* may be
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001007 a regular expression object or a string containing a regular expression
1008 suitable for use by :func:`re.search`. Examples::
1009
Ezio Melottied3a7d22010-12-01 02:32:32 +00001010 self.assertRaisesRegex(ValueError, 'invalid literal for.*XYZ$',
1011 int, 'XYZ')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001012
1013 or::
1014
Ezio Melottied3a7d22010-12-01 02:32:32 +00001015 with self.assertRaisesRegex(ValueError, 'literal'):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001016 int('XYZ')
1017
Georg Brandl419e3de2010-12-01 15:44:25 +00001018 .. versionadded:: 3.1
1019 under the name ``assertRaisesRegexp``.
Ezio Melottib4dc2502011-05-06 15:01:41 +03001020
Ezio Melottied3a7d22010-12-01 02:32:32 +00001021 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001022 Renamed to :meth:`assertRaisesRegex`.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001023
Ezio Melottib4dc2502011-05-06 15:01:41 +03001024 .. versionchanged:: 3.3
1025 Added the *msg* keyword argument when used as a context manager.
1026
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001027
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001028 .. method:: assertWarns(warning, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001029 assertWarns(warning, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001030
1031 Test that a warning is triggered when *callable* is called with any
1032 positional or keyword arguments that are also passed to
1033 :meth:`assertWarns`. The test passes if *warning* is triggered and
1034 fails if it isn't. Also, any unexpected exception is an error.
1035 To catch any of a group of warnings, a tuple containing the warning
1036 classes may be passed as *warnings*.
1037
Ezio Melottib4dc2502011-05-06 15:01:41 +03001038 If only the *warning* and possibly the *msg* arguments are given,
1039 returns a context manager so that the code under test can be written
1040 inline rather than as a function::
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001041
1042 with self.assertWarns(SomeWarning):
1043 do_something()
1044
Ezio Melottib4dc2502011-05-06 15:01:41 +03001045 When used as a context manager, :meth:`assertRaises` accepts the
1046 additional keyword argument *msg*.
1047
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001048 The context manager will store the caught warning object in its
1049 :attr:`warning` attribute, and the source line which triggered the
1050 warnings in the :attr:`filename` and :attr:`lineno` attributes.
1051 This can be useful if the intention is to perform additional checks
1052 on the exception raised::
1053
1054 with self.assertWarns(SomeWarning) as cm:
1055 do_something()
1056
1057 self.assertIn('myfile.py', cm.filename)
1058 self.assertEqual(320, cm.lineno)
1059
1060 This method works regardless of the warning filters in place when it
1061 is called.
1062
1063 .. versionadded:: 3.2
1064
Ezio Melottib4dc2502011-05-06 15:01:41 +03001065 .. versionchanged:: 3.3
1066 Added the *msg* keyword argument when used as a context manager.
1067
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001068
Ezio Melottied3a7d22010-12-01 02:32:32 +00001069 .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001070 assertWarnsRegex(warning, regex, msg=None)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001071
Ezio Melottied3a7d22010-12-01 02:32:32 +00001072 Like :meth:`assertWarns` but also tests that *regex* matches on the
1073 message of the triggered warning. *regex* may be a regular expression
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001074 object or a string containing a regular expression suitable for use
1075 by :func:`re.search`. Example::
1076
Ezio Melottied3a7d22010-12-01 02:32:32 +00001077 self.assertWarnsRegex(DeprecationWarning,
1078 r'legacy_function\(\) is deprecated',
1079 legacy_function, 'XYZ')
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001080
1081 or::
1082
Ezio Melottied3a7d22010-12-01 02:32:32 +00001083 with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001084 frobnicate('/etc/passwd')
1085
1086 .. versionadded:: 3.2
1087
Ezio Melottib4dc2502011-05-06 15:01:41 +03001088 .. versionchanged:: 3.3
1089 Added the *msg* keyword argument when used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001090
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001091
Ezio Melotti4370b302010-11-03 20:39:14 +00001092 There are also other methods used to perform more specific checks, such as:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001093
Ezio Melotti4370b302010-11-03 20:39:14 +00001094 +---------------------------------------+--------------------------------+--------------+
1095 | Method | Checks that | New in |
1096 +=======================================+================================+==============+
1097 | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | |
1098 | <TestCase.assertAlmostEqual>` | | |
1099 +---------------------------------------+--------------------------------+--------------+
1100 | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | |
1101 | <TestCase.assertNotAlmostEqual>` | | |
1102 +---------------------------------------+--------------------------------+--------------+
1103 | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 |
1104 | <TestCase.assertGreater>` | | |
1105 +---------------------------------------+--------------------------------+--------------+
1106 | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 |
1107 | <TestCase.assertGreaterEqual>` | | |
1108 +---------------------------------------+--------------------------------+--------------+
1109 | :meth:`assertLess(a, b) | ``a < b`` | 3.1 |
1110 | <TestCase.assertLess>` | | |
1111 +---------------------------------------+--------------------------------+--------------+
1112 | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
1113 | <TestCase.assertLessEqual>` | | |
1114 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001115 | :meth:`assertRegex(s, re) | ``regex.search(s)`` | 3.1 |
1116 | <TestCase.assertRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001117 +---------------------------------------+--------------------------------+--------------+
Ezio Melottied3a7d22010-12-01 02:32:32 +00001118 | :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 |
1119 | <TestCase.assertNotRegex>` | | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001120 +---------------------------------------+--------------------------------+--------------+
Éric Araujo941afed2011-09-01 02:47:34 +02001121 | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 |
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001122 | <TestCase.assertCountEqual>` | elements in the same number, | |
Ezio Melotti4370b302010-11-03 20:39:14 +00001123 | | regardless of their order | |
1124 +---------------------------------------+--------------------------------+--------------+
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001125
1126
Michael Foorde180d392011-01-28 19:51:48 +00001127 .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
1128 assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001129
Michael Foorde180d392011-01-28 19:51:48 +00001130 Test that *first* and *second* are approximately (or not approximately)
Ezio Melotti4841fd62010-11-05 15:43:40 +00001131 equal by computing the difference, rounding to the given number of
1132 decimal *places* (default 7), and comparing to zero. Note that these
1133 methods round the values to the given number of *decimal places* (i.e.
1134 like the :func:`round` function) and not *significant digits*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001135
Ezio Melotti4370b302010-11-03 20:39:14 +00001136 If *delta* is supplied instead of *places* then the difference
Michael Foorde180d392011-01-28 19:51:48 +00001137 between *first* and *second* must be less (or more) than *delta*.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001138
Ezio Melotti4370b302010-11-03 20:39:14 +00001139 Supplying both *delta* and *places* raises a ``TypeError``.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001140
Ezio Melotti4370b302010-11-03 20:39:14 +00001141 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001142 :meth:`assertAlmostEqual` automatically considers almost equal objects
1143 that compare equal. :meth:`assertNotAlmostEqual` automatically fails
1144 if the objects compare equal. Added the *delta* keyword argument.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001145
Ezio Melotti4370b302010-11-03 20:39:14 +00001146
Michael Foorde180d392011-01-28 19:51:48 +00001147 .. method:: assertGreater(first, second, msg=None)
1148 assertGreaterEqual(first, second, msg=None)
1149 assertLess(first, second, msg=None)
1150 assertLessEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001151
Michael Foorde180d392011-01-28 19:51:48 +00001152 Test that *first* is respectively >, >=, < or <= than *second* depending
Ezio Melotti4841fd62010-11-05 15:43:40 +00001153 on the method name. If not, the test will fail::
Ezio Melotti4370b302010-11-03 20:39:14 +00001154
1155 >>> self.assertGreaterEqual(3, 4)
1156 AssertionError: "3" unexpectedly not greater than or equal to "4"
1157
1158 .. versionadded:: 3.1
1159
1160
Ezio Melottied3a7d22010-12-01 02:32:32 +00001161 .. method:: assertRegex(text, regex, msg=None)
1162 assertNotRegex(text, regex, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001163
Ezio Melottied3a7d22010-12-01 02:32:32 +00001164 Test that a *regex* search matches (or does not match) *text*. In case
Ezio Melotti4841fd62010-11-05 15:43:40 +00001165 of failure, the error message will include the pattern and the *text* (or
Ezio Melottied3a7d22010-12-01 02:32:32 +00001166 the pattern and the part of *text* that unexpectedly matched). *regex*
Ezio Melotti4370b302010-11-03 20:39:14 +00001167 may be a regular expression object or a string containing a regular
1168 expression suitable for use by :func:`re.search`.
1169
Georg Brandl419e3de2010-12-01 15:44:25 +00001170 .. versionadded:: 3.1
1171 under the name ``assertRegexpMatches``.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001172 .. versionchanged:: 3.2
Georg Brandl419e3de2010-12-01 15:44:25 +00001173 The method ``assertRegexpMatches()`` has been renamed to
1174 :meth:`.assertRegex`.
1175 .. versionadded:: 3.2
1176 :meth:`.assertNotRegex`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001177
1178
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001179 .. method:: assertDictContainsSubset(subset, dictionary, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001180
Ezio Melottiaddc6f52010-12-18 20:00:04 +00001181 Tests whether the key/value pairs in *dictionary* are a superset of
1182 those in *subset*. If not, an error message listing the missing keys
1183 and mismatched values is generated.
Ezio Melotti4370b302010-11-03 20:39:14 +00001184
Raymond Hettinger8ebe27f2010-12-21 19:24:26 +00001185 Note, the arguments are in the opposite order of what the method name
1186 dictates. Instead, consider using the set-methods on :ref:`dictionary
1187 views <dict-views>`, for example: ``d.keys() <= e.keys()`` or
1188 ``d.items() <= d.items()``.
1189
Ezio Melotti4370b302010-11-03 20:39:14 +00001190 .. versionadded:: 3.1
Raymond Hettinger8ebe27f2010-12-21 19:24:26 +00001191 .. deprecated:: 3.2
Ezio Melotti4370b302010-11-03 20:39:14 +00001192
1193
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001194 .. method:: assertCountEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001195
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001196 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001197 regardless of their order. When they don't, an error message listing the
1198 differences between the sequences will be generated.
1199
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001200 Duplicate elements are *not* ignored when comparing *first* and
1201 *second*. It verifies whether each element has the same count in both
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001202 sequences. Equivalent to:
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001203 ``assertEqual(Counter(list(first)), Counter(list(second)))``
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001204 but works with sequences of unhashable objects as well.
Ezio Melotti4370b302010-11-03 20:39:14 +00001205
Ezio Melotti4370b302010-11-03 20:39:14 +00001206 .. versionadded:: 3.2
1207
Michael Foorde180d392011-01-28 19:51:48 +00001208 .. method:: assertSameElements(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001209
Michael Foorde180d392011-01-28 19:51:48 +00001210 Test that sequence *first* contains the same elements as *second*,
Ezio Melotti4370b302010-11-03 20:39:14 +00001211 regardless of their order. When they don't, an error message listing
1212 the differences between the sequences will be generated.
1213
Michael Foorde180d392011-01-28 19:51:48 +00001214 Duplicate elements are ignored when comparing *first* and *second*.
1215 It is the equivalent of ``assertEqual(set(first), set(second))``
Ezio Melotti4370b302010-11-03 20:39:14 +00001216 but it works with sequences of unhashable objects as well. Because
1217 duplicates are ignored, this method has been deprecated in favour of
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001218 :meth:`assertCountEqual`.
Ezio Melotti4370b302010-11-03 20:39:14 +00001219
Ezio Melotti4370b302010-11-03 20:39:14 +00001220 .. versionadded:: 3.1
1221 .. deprecated:: 3.2
1222
1223
Ezio Melotti22170ed2010-11-20 09:57:27 +00001224 .. _type-specific-methods:
Ezio Melotti4370b302010-11-03 20:39:14 +00001225
Ezio Melotti22170ed2010-11-20 09:57:27 +00001226 The :meth:`assertEqual` method dispatches the equality check for objects of
1227 the same type to different type-specific methods. These methods are already
1228 implemented for most of the built-in types, but it's also possible to
1229 register new methods using :meth:`addTypeEqualityFunc`:
1230
1231 .. method:: addTypeEqualityFunc(typeobj, function)
1232
1233 Registers a type-specific method called by :meth:`assertEqual` to check
1234 if two objects of exactly the same *typeobj* (not subclasses) compare
1235 equal. *function* must take two positional arguments and a third msg=None
1236 keyword argument just as :meth:`assertEqual` does. It must raise
1237 :data:`self.failureException(msg) <failureException>` when inequality
1238 between the first two parameters is detected -- possibly providing useful
1239 information and explaining the inequalities in details in the error
1240 message.
1241
1242 .. versionadded:: 3.1
1243
1244 The list of type-specific methods automatically used by
1245 :meth:`~TestCase.assertEqual` are summarized in the following table. Note
1246 that it's usually not necessary to invoke these methods directly.
Ezio Melotti4370b302010-11-03 20:39:14 +00001247
1248 +-----------------------------------------+-----------------------------+--------------+
1249 | Method | Used to compare | New in |
1250 +=========================================+=============================+==============+
1251 | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 |
1252 | <TestCase.assertMultiLineEqual>` | | |
1253 +-----------------------------------------+-----------------------------+--------------+
1254 | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 |
1255 | <TestCase.assertSequenceEqual>` | | |
1256 +-----------------------------------------+-----------------------------+--------------+
1257 | :meth:`assertListEqual(a, b) | lists | 3.1 |
1258 | <TestCase.assertListEqual>` | | |
1259 +-----------------------------------------+-----------------------------+--------------+
1260 | :meth:`assertTupleEqual(a, b) | tuples | 3.1 |
1261 | <TestCase.assertTupleEqual>` | | |
1262 +-----------------------------------------+-----------------------------+--------------+
1263 | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 |
1264 | <TestCase.assertSetEqual>` | | |
1265 +-----------------------------------------+-----------------------------+--------------+
1266 | :meth:`assertDictEqual(a, b) | dicts | 3.1 |
1267 | <TestCase.assertDictEqual>` | | |
1268 +-----------------------------------------+-----------------------------+--------------+
1269
1270
1271
Michael Foorde180d392011-01-28 19:51:48 +00001272 .. method:: assertMultiLineEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001273
Michael Foorde180d392011-01-28 19:51:48 +00001274 Test that the multiline string *first* is equal to the string *second*.
Ezio Melotti4370b302010-11-03 20:39:14 +00001275 When not equal a diff of the two strings highlighting the differences
1276 will be included in the error message. This method is used by default
1277 when comparing strings with :meth:`assertEqual`.
1278
Ezio Melotti4370b302010-11-03 20:39:14 +00001279 .. versionadded:: 3.1
1280
1281
Michael Foorde180d392011-01-28 19:51:48 +00001282 .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001283
1284 Tests that two sequences are equal. If a *seq_type* is supplied, both
Michael Foorde180d392011-01-28 19:51:48 +00001285 *first* and *second* must be instances of *seq_type* or a failure will
Ezio Melotti4370b302010-11-03 20:39:14 +00001286 be raised. If the sequences are different an error message is
1287 constructed that shows the difference between the two.
1288
Ezio Melotti22170ed2010-11-20 09:57:27 +00001289 This method is not called directly by :meth:`assertEqual`, but
1290 it's used to implement :meth:`assertListEqual` and
Ezio Melotti4370b302010-11-03 20:39:14 +00001291 :meth:`assertTupleEqual`.
1292
1293 .. versionadded:: 3.1
1294
1295
Michael Foorde180d392011-01-28 19:51:48 +00001296 .. method:: assertListEqual(first, second, msg=None)
1297 assertTupleEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001298
1299 Tests that two lists or tuples are equal. If not an error message is
1300 constructed that shows only the differences between the two. An error
1301 is also raised if either of the parameters are of the wrong type.
1302 These methods are used by default when comparing lists or tuples with
1303 :meth:`assertEqual`.
1304
Ezio Melotti4370b302010-11-03 20:39:14 +00001305 .. versionadded:: 3.1
1306
1307
Michael Foorde180d392011-01-28 19:51:48 +00001308 .. method:: assertSetEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001309
1310 Tests that two sets are equal. If not, an error message is constructed
1311 that lists the differences between the sets. This method is used by
1312 default when comparing sets or frozensets with :meth:`assertEqual`.
1313
Michael Foorde180d392011-01-28 19:51:48 +00001314 Fails if either of *first* or *second* does not have a :meth:`set.difference`
Ezio Melotti4370b302010-11-03 20:39:14 +00001315 method.
1316
Ezio Melotti4370b302010-11-03 20:39:14 +00001317 .. versionadded:: 3.1
1318
1319
Michael Foorde180d392011-01-28 19:51:48 +00001320 .. method:: assertDictEqual(first, second, msg=None)
Ezio Melotti4370b302010-11-03 20:39:14 +00001321
1322 Test that two dictionaries are equal. If not, an error message is
1323 constructed that shows the differences in the dictionaries. This
1324 method will be used by default to compare dictionaries in
1325 calls to :meth:`assertEqual`.
1326
Ezio Melotti4370b302010-11-03 20:39:14 +00001327 .. versionadded:: 3.1
1328
1329
1330
Ezio Melotti22170ed2010-11-20 09:57:27 +00001331 .. _other-methods-and-attrs:
1332
Ezio Melotti4370b302010-11-03 20:39:14 +00001333 Finally the :class:`TestCase` provides the following methods and attributes:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001334
Benjamin Peterson52baa292009-03-24 00:56:30 +00001335
Georg Brandl7f01a132009-09-16 15:58:14 +00001336 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001337
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001338 Signals a test failure unconditionally, with *msg* or ``None`` for
Benjamin Peterson52baa292009-03-24 00:56:30 +00001339 the error message.
1340
1341
1342 .. attribute:: failureException
1343
1344 This class attribute gives the exception raised by the test method. If a
1345 test framework needs to use a specialized exception, possibly to carry
1346 additional information, it must subclass this exception in order to "play
1347 fair" with the framework. The initial value of this attribute is
1348 :exc:`AssertionError`.
1349
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001350
1351 .. attribute:: longMessage
1352
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001353 If set to ``True`` then any explicit failure message you pass in to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001354 :ref:`assert methods <assert-methods>` will be appended to the end of the
1355 normal failure message. The normal messages contain useful information
1356 about the objects involved, for example the message from assertEqual
1357 shows you the repr of the two unequal objects. Setting this attribute
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001358 to ``True`` allows you to have a custom error message in addition to the
Ezio Melotti22170ed2010-11-20 09:57:27 +00001359 normal one.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001360
Michael Foord5074df62010-12-03 00:53:09 +00001361 This attribute defaults to ``True``. If set to False then a custom message
1362 passed to an assert method will silence the normal message.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001363
1364 The class setting can be overridden in individual tests by assigning an
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001365 instance attribute to ``True`` or ``False`` before calling the assert methods.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001366
Raymond Hettinger35a88362009-04-09 00:08:24 +00001367 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001368
1369
Michael Foord98b3e762010-06-05 21:59:55 +00001370 .. attribute:: maxDiff
1371
1372 This attribute controls the maximum length of diffs output by assert
1373 methods that report diffs on failure. It defaults to 80*8 characters.
1374 Assert methods affected by this attribute are
1375 :meth:`assertSequenceEqual` (including all the sequence comparison
1376 methods that delegate to it), :meth:`assertDictEqual` and
1377 :meth:`assertMultiLineEqual`.
1378
1379 Setting ``maxDiff`` to None means that there is no maximum length of
1380 diffs.
1381
1382 .. versionadded:: 3.2
1383
1384
Benjamin Peterson52baa292009-03-24 00:56:30 +00001385 Testing frameworks can use the following methods to collect information on
1386 the test:
1387
1388
1389 .. method:: countTestCases()
1390
1391 Return the number of tests represented by this test object. For
1392 :class:`TestCase` instances, this will always be ``1``.
1393
1394
1395 .. method:: defaultTestResult()
1396
1397 Return an instance of the test result class that should be used for this
1398 test case class (if no other result instance is provided to the
1399 :meth:`run` method).
1400
1401 For :class:`TestCase` instances, this will always be an instance of
1402 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1403 as necessary.
1404
1405
1406 .. method:: id()
1407
1408 Return a string identifying the specific test case. This is usually the
1409 full name of the test method, including the module and class name.
1410
1411
1412 .. method:: shortDescription()
1413
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001414 Returns a description of the test, or ``None`` if no description
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001415 has been provided. The default implementation of this method
1416 returns the first line of the test method's docstring, if available,
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001417 or ``None``.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001418
Georg Brandl419e3de2010-12-01 15:44:25 +00001419 .. versionchanged:: 3.1
Michael Foord34c94622010-02-10 15:51:42 +00001420 In 3.1 this was changed to add the test name to the short description
Georg Brandl419e3de2010-12-01 15:44:25 +00001421 even in the presence of a docstring. This caused compatibility issues
Michael Foord34c94622010-02-10 15:51:42 +00001422 with unittest extensions and adding the test name was moved to the
Georg Brandl419e3de2010-12-01 15:44:25 +00001423 :class:`TextTestResult` in Python 3.2.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001424
Georg Brandl116aa622007-08-15 14:28:22 +00001425
Georg Brandl7f01a132009-09-16 15:58:14 +00001426 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001427
1428 Add a function to be called after :meth:`tearDown` to cleanup resources
1429 used during the test. Functions will be called in reverse order to the
1430 order they are added (LIFO). They are called with any arguments and
1431 keyword arguments passed into :meth:`addCleanup` when they are
1432 added.
1433
1434 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1435 then any cleanup functions added will still be called.
1436
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001437 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001438
1439
1440 .. method:: doCleanups()
1441
Barry Warsaw0c9fd632010-04-12 14:50:57 +00001442 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001443 after :meth:`setUp` if :meth:`setUp` raises an exception.
1444
1445 It is responsible for calling all the cleanup functions added by
1446 :meth:`addCleanup`. If you need cleanup functions to be called
1447 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1448 yourself.
1449
1450 :meth:`doCleanups` pops methods off the stack of cleanup
1451 functions one at a time, so it can be called at any time.
1452
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001453 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001454
1455
Georg Brandl7f01a132009-09-16 15:58:14 +00001456.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001457
1458 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001459 allows the test runner to drive the test, but does not provide the methods
1460 which test code can use to check and report errors. This is used to create
1461 test cases using legacy test code, allowing it to be integrated into a
1462 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001463
1464
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001465.. _deprecated-aliases:
1466
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001467Deprecated aliases
1468##################
1469
1470For historical reasons, some of the :class:`TestCase` methods had one or more
1471aliases that are now deprecated. The following table lists the correct names
1472along with their deprecated aliases:
1473
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001474 ============================== ====================== ======================
1475 Method Name Deprecated alias Deprecated alias
1476 ============================== ====================== ======================
1477 :meth:`.assertEqual` failUnlessEqual assertEquals
1478 :meth:`.assertNotEqual` failIfEqual assertNotEquals
1479 :meth:`.assertTrue` failUnless assert\_
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001480 :meth:`.assertFalse` failIf
1481 :meth:`.assertRaises` failUnlessRaises
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001482 :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
1483 :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
Ezio Melottied3a7d22010-12-01 02:32:32 +00001484 :meth:`.assertRegex` assertRegexpMatches
1485 :meth:`.assertRaisesRegex` assertRaisesRegexp
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001486 ============================== ====================== ======================
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001487
Ezio Melotti361467e2011-04-03 17:37:58 +03001488 .. deprecated:: 3.1
Ezio Melotti2baf1a62010-11-22 12:56:58 +00001489 the fail* aliases listed in the second column.
1490 .. deprecated:: 3.2
1491 the assert* aliases listed in the third column.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001492 .. deprecated:: 3.2
1493 ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
1494 :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
Ezio Melotti8f2e07b2010-11-04 19:09:28 +00001495
1496
Benjamin Peterson52baa292009-03-24 00:56:30 +00001497.. _testsuite-objects:
1498
Benjamin Peterson52baa292009-03-24 00:56:30 +00001499Grouping tests
1500~~~~~~~~~~~~~~
1501
Georg Brandl7f01a132009-09-16 15:58:14 +00001502.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001503
1504 This class represents an aggregation of individual tests cases and test suites.
1505 The class presents the interface needed by the test runner to allow it to be run
1506 as any other test case. Running a :class:`TestSuite` instance is the same as
1507 iterating over the suite, running each test individually.
1508
1509 If *tests* is given, it must be an iterable of individual test cases or other
1510 test suites that will be used to build the suite initially. Additional methods
1511 are provided to add test cases and suites to the collection later on.
1512
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001513 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1514 they do not actually implement a test. Instead, they are used to aggregate
1515 tests into groups of tests that should be run together. Some additional
1516 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001517
1518
1519 .. method:: TestSuite.addTest(test)
1520
1521 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1522
1523
1524 .. method:: TestSuite.addTests(tests)
1525
1526 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1527 instances to this test suite.
1528
Benjamin Petersond2397752009-06-27 23:45:02 +00001529 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1530 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001531
1532 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1533
1534
1535 .. method:: run(result)
1536
1537 Run the tests associated with this suite, collecting the result into the
1538 test result object passed as *result*. Note that unlike
1539 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1540 be passed in.
1541
1542
1543 .. method:: debug()
1544
1545 Run the tests associated with this suite without collecting the
1546 result. This allows exceptions raised by the test to be propagated to the
1547 caller and can be used to support running tests under a debugger.
1548
1549
1550 .. method:: countTestCases()
1551
1552 Return the number of tests represented by this test object, including all
1553 individual tests and sub-suites.
1554
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001555
1556 .. method:: __iter__()
1557
1558 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1559 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1560 that this method maybe called several times on a single suite
1561 (for example when counting tests or comparing for equality)
1562 so the tests returned must be the same for repeated iterations.
1563
Georg Brandl853947a2010-01-31 18:53:23 +00001564 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001565 In earlier versions the :class:`TestSuite` accessed tests directly rather
1566 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1567 for providing tests.
1568
Benjamin Peterson52baa292009-03-24 00:56:30 +00001569 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1570 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1571
1572
Benjamin Peterson52baa292009-03-24 00:56:30 +00001573Loading and running tests
1574~~~~~~~~~~~~~~~~~~~~~~~~~
1575
Georg Brandl116aa622007-08-15 14:28:22 +00001576.. class:: TestLoader()
1577
Benjamin Peterson52baa292009-03-24 00:56:30 +00001578 The :class:`TestLoader` class is used to create test suites from classes and
1579 modules. Normally, there is no need to create an instance of this class; the
1580 :mod:`unittest` module provides an instance that can be shared as
1581 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1582 customization of some configurable properties.
1583
1584 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001585
Ezio Melotti9c02c2f2010-11-03 20:45:31 +00001586
Benjamin Peterson52baa292009-03-24 00:56:30 +00001587 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001588
Benjamin Peterson52baa292009-03-24 00:56:30 +00001589 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1590 :class:`testCaseClass`.
1591
1592
1593 .. method:: loadTestsFromModule(module)
1594
1595 Return a suite of all tests cases contained in the given module. This
1596 method searches *module* for classes derived from :class:`TestCase` and
1597 creates an instance of the class for each test method defined for the
1598 class.
1599
Georg Brandle720c0a2009-04-27 16:20:50 +00001600 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001601
1602 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1603 convenient in sharing fixtures and helper functions, defining test
1604 methods on base classes that are not intended to be instantiated
1605 directly does not play well with this method. Doing so, however, can
1606 be useful when the fixtures are different and defined in subclasses.
1607
Benjamin Petersond2397752009-06-27 23:45:02 +00001608 If a module provides a ``load_tests`` function it will be called to
1609 load the tests. This allows modules to customize test loading.
1610 This is the `load_tests protocol`_.
1611
Georg Brandl853947a2010-01-31 18:53:23 +00001612 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001613 Support for ``load_tests`` added.
1614
Benjamin Peterson52baa292009-03-24 00:56:30 +00001615
Georg Brandl7f01a132009-09-16 15:58:14 +00001616 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001617
1618 Return a suite of all tests cases given a string specifier.
1619
1620 The specifier *name* is a "dotted name" that may resolve either to a
1621 module, a test case class, a test method within a test case class, a
1622 :class:`TestSuite` instance, or a callable object which returns a
1623 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1624 applied in the order listed here; that is, a method on a possible test
1625 case class will be picked up as "a test method within a test case class",
1626 rather than "a callable object".
1627
1628 For example, if you have a module :mod:`SampleTests` containing a
1629 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1630 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001631 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1632 return a suite which will run all three test methods. Using the specifier
1633 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1634 suite which will run only the :meth:`test_two` test method. The specifier
1635 can refer to modules and packages which have not been imported; they will
1636 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001637
1638 The method optionally resolves *name* relative to the given *module*.
1639
1640
Georg Brandl7f01a132009-09-16 15:58:14 +00001641 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001642
1643 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1644 than a single name. The return value is a test suite which supports all
1645 the tests defined for each name.
1646
1647
1648 .. method:: getTestCaseNames(testCaseClass)
1649
1650 Return a sorted sequence of method names found within *testCaseClass*;
1651 this should be a subclass of :class:`TestCase`.
1652
Benjamin Petersond2397752009-06-27 23:45:02 +00001653
1654 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1655
1656 Find and return all test modules from the specified start directory,
1657 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001658 *pattern* will be loaded. (Using shell style pattern matching.) Only
1659 module names that are importable (i.e. are valid Python identifiers) will
1660 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001661
1662 All test modules must be importable from the top level of the project. If
1663 the start directory is not the top level directory then the top level
1664 directory must be specified separately.
1665
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001666 If importing a module fails, for example due to a syntax error, then this
1667 will be recorded as a single error and discovery will continue.
1668
Benjamin Petersond2397752009-06-27 23:45:02 +00001669 If a test package name (directory with :file:`__init__.py`) matches the
1670 pattern then the package will be checked for a ``load_tests``
1671 function. If this exists then it will be called with *loader*, *tests*,
1672 *pattern*.
1673
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001674 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001675 ``load_tests`` is responsible for loading all tests in the package.
1676
1677 The pattern is deliberately not stored as a loader attribute so that
1678 packages can continue discovery themselves. *top_level_dir* is stored so
1679 ``load_tests`` does not need to pass this argument in to
1680 ``loader.discover()``.
1681
Benjamin Petersonb48af542010-04-11 20:43:16 +00001682 *start_dir* can be a dotted module name as well as a directory.
1683
Georg Brandl853947a2010-01-31 18:53:23 +00001684 .. versionadded:: 3.2
1685
Benjamin Petersond2397752009-06-27 23:45:02 +00001686
Benjamin Peterson52baa292009-03-24 00:56:30 +00001687 The following attributes of a :class:`TestLoader` can be configured either by
1688 subclassing or assignment on an instance:
1689
1690
1691 .. attribute:: testMethodPrefix
1692
1693 String giving the prefix of method names which will be interpreted as test
1694 methods. The default value is ``'test'``.
1695
1696 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1697 methods.
1698
1699
1700 .. attribute:: sortTestMethodsUsing
1701
1702 Function to be used to compare method names when sorting them in
1703 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1704
1705
1706 .. attribute:: suiteClass
1707
1708 Callable object that constructs a test suite from a list of tests. No
1709 methods on the resulting object are needed. The default value is the
1710 :class:`TestSuite` class.
1711
1712 This affects all the :meth:`loadTestsFrom\*` methods.
1713
1714
Benjamin Peterson52baa292009-03-24 00:56:30 +00001715.. class:: TestResult
1716
1717 This class is used to compile information about which tests have succeeded
1718 and which have failed.
1719
1720 A :class:`TestResult` object stores the results of a set of tests. The
1721 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1722 properly recorded; test authors do not need to worry about recording the
1723 outcome of tests.
1724
1725 Testing frameworks built on top of :mod:`unittest` may want access to the
1726 :class:`TestResult` object generated by running a set of tests for reporting
1727 purposes; a :class:`TestResult` instance is returned by the
1728 :meth:`TestRunner.run` method for this purpose.
1729
1730 :class:`TestResult` instances have the following attributes that will be of
1731 interest when inspecting the results of running a set of tests:
1732
1733
1734 .. attribute:: errors
1735
1736 A list containing 2-tuples of :class:`TestCase` instances and strings
1737 holding formatted tracebacks. Each tuple represents a test which raised an
1738 unexpected exception.
1739
Benjamin Peterson52baa292009-03-24 00:56:30 +00001740 .. attribute:: failures
1741
1742 A list containing 2-tuples of :class:`TestCase` instances and strings
1743 holding formatted tracebacks. Each tuple represents a test where a failure
1744 was explicitly signalled using the :meth:`TestCase.fail\*` or
1745 :meth:`TestCase.assert\*` methods.
1746
Benjamin Peterson52baa292009-03-24 00:56:30 +00001747 .. attribute:: skipped
1748
1749 A list containing 2-tuples of :class:`TestCase` instances and strings
1750 holding the reason for skipping the test.
1751
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001752 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001753
1754 .. attribute:: expectedFailures
1755
Georg Brandl6faee4e2010-09-21 14:48:28 +00001756 A list containing 2-tuples of :class:`TestCase` instances and strings
1757 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001758 of the test case.
1759
1760 .. attribute:: unexpectedSuccesses
1761
1762 A list containing :class:`TestCase` instances that were marked as expected
1763 failures, but succeeded.
1764
1765 .. attribute:: shouldStop
1766
1767 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1768
1769
1770 .. attribute:: testsRun
1771
1772 The total number of tests run so far.
1773
1774
Georg Brandl12037202010-12-02 22:35:25 +00001775 .. attribute:: buffer
Benjamin Petersonb48af542010-04-11 20:43:16 +00001776
1777 If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
1778 :meth:`startTest` and :meth:`stopTest` being called. Collected output will
1779 only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
1780 fails or errors. Any output is also attached to the failure / error message.
1781
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001782 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001783
1784
1785 .. attribute:: failfast
1786
1787 If set to true :meth:`stop` will be called on the first failure or error,
1788 halting the test run.
1789
Ezio Melotti7afd3f52010-04-20 09:32:54 +00001790 .. versionadded:: 3.2
Benjamin Petersonb48af542010-04-11 20:43:16 +00001791
1792
Benjamin Peterson52baa292009-03-24 00:56:30 +00001793 .. method:: wasSuccessful()
1794
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001795 Return ``True`` if all tests run so far have passed, otherwise returns
1796 ``False``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001797
1798
1799 .. method:: stop()
1800
1801 This method can be called to signal that the set of tests being run should
Ezio Melotti75b2a5e2010-11-20 10:13:45 +00001802 be aborted by setting the :attr:`shouldStop` attribute to ``True``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001803 :class:`TestRunner` objects should respect this flag and return without
1804 running any additional tests.
1805
1806 For example, this feature is used by the :class:`TextTestRunner` class to
1807 stop the test framework when the user signals an interrupt from the
1808 keyboard. Interactive tools which provide :class:`TestRunner`
1809 implementations can use this in a similar manner.
1810
1811 The following methods of the :class:`TestResult` class are used to maintain
1812 the internal data structures, and may be extended in subclasses to support
1813 additional reporting requirements. This is particularly useful in building
1814 tools which support interactive reporting while tests are being run.
1815
1816
1817 .. method:: startTest(test)
1818
1819 Called when the test case *test* is about to be run.
1820
Benjamin Peterson52baa292009-03-24 00:56:30 +00001821 .. method:: stopTest(test)
1822
1823 Called after the test case *test* has been executed, regardless of the
1824 outcome.
1825
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001826 .. method:: startTestRun(test)
1827
1828 Called once before any tests are executed.
1829
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001830 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001831
1832
1833 .. method:: stopTestRun(test)
1834
Ezio Melotti176d6c42010-01-27 20:58:07 +00001835 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001836
Ezio Melotti2d1e88a2011-03-10 12:16:35 +02001837 .. versionadded:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001838
1839
Benjamin Peterson52baa292009-03-24 00:56:30 +00001840 .. method:: addError(test, err)
1841
1842 Called when the test case *test* raises an unexpected exception *err* is a
1843 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1844 traceback)``.
1845
1846 The default implementation appends a tuple ``(test, formatted_err)`` to
1847 the instance's :attr:`errors` attribute, where *formatted_err* is a
1848 formatted traceback derived from *err*.
1849
1850
1851 .. method:: addFailure(test, err)
1852
Benjamin Petersond2397752009-06-27 23:45:02 +00001853 Called when the test case *test* signals a failure. *err* is a tuple of
1854 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001855
1856 The default implementation appends a tuple ``(test, formatted_err)`` to
1857 the instance's :attr:`failures` attribute, where *formatted_err* is a
1858 formatted traceback derived from *err*.
1859
1860
1861 .. method:: addSuccess(test)
1862
1863 Called when the test case *test* succeeds.
1864
1865 The default implementation does nothing.
1866
1867
1868 .. method:: addSkip(test, reason)
1869
1870 Called when the test case *test* is skipped. *reason* is the reason the
1871 test gave for skipping.
1872
1873 The default implementation appends a tuple ``(test, reason)`` to the
1874 instance's :attr:`skipped` attribute.
1875
1876
1877 .. method:: addExpectedFailure(test, err)
1878
1879 Called when the test case *test* fails, but was marked with the
1880 :func:`expectedFailure` decorator.
1881
1882 The default implementation appends a tuple ``(test, formatted_err)`` to
1883 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1884 is a formatted traceback derived from *err*.
1885
1886
1887 .. method:: addUnexpectedSuccess(test)
1888
1889 Called when the test case *test* was marked with the
1890 :func:`expectedFailure` decorator, but succeeded.
1891
1892 The default implementation appends the test to the instance's
1893 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001894
Georg Brandl67b21b72010-08-17 15:07:14 +00001895
Michael Foord34c94622010-02-10 15:51:42 +00001896.. class:: TextTestResult(stream, descriptions, verbosity)
1897
Georg Brandl67b21b72010-08-17 15:07:14 +00001898 A concrete implementation of :class:`TestResult` used by the
1899 :class:`TextTestRunner`.
Michael Foord34c94622010-02-10 15:51:42 +00001900
Georg Brandl67b21b72010-08-17 15:07:14 +00001901 .. versionadded:: 3.2
1902 This class was previously named ``_TextTestResult``. The old name still
1903 exists as an alias but is deprecated.
1904
Georg Brandl116aa622007-08-15 14:28:22 +00001905
1906.. data:: defaultTestLoader
1907
1908 Instance of the :class:`TestLoader` class intended to be shared. If no
1909 customization of the :class:`TestLoader` is needed, this instance can be used
1910 instead of repeatedly creating new instances.
1911
1912
Michael Foordd218e952011-01-03 12:55:11 +00001913.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, runnerclass=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001914
Michael Foordd218e952011-01-03 12:55:11 +00001915 A basic test runner implementation that outputs results to a stream. If *stream*
Éric Araujo941afed2011-09-01 02:47:34 +02001916 is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class
Georg Brandl116aa622007-08-15 14:28:22 +00001917 has a few configurable parameters, but is essentially very simple. Graphical
1918 applications which run test suites should provide alternate implementations.
1919
Ezio Melotti60901872010-12-01 00:56:10 +00001920 By default this runner shows :exc:`DeprecationWarning`,
1921 :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` even if they are
1922 :ref:`ignored by default <warning-ignored>`. Deprecation warnings caused by
1923 :ref:`deprecated unittest methods <deprecated-aliases>` are also
1924 special-cased and, when the warning filters are ``'default'`` or ``'always'``,
1925 they will appear only once per-module, in order to avoid too many warning
Georg Brandl46402372010-12-04 19:06:18 +00001926 messages. This behavior can be overridden using the :option:`-Wd` or
Ezio Melotti60901872010-12-01 00:56:10 +00001927 :option:`-Wa` options and leaving *warnings* to ``None``.
1928
Michael Foordd218e952011-01-03 12:55:11 +00001929 .. versionchanged:: 3.2
1930 Added the ``warnings`` argument.
1931
1932 .. versionchanged:: 3.2
Éric Araujo941afed2011-09-01 02:47:34 +02001933 The default stream is set to :data:`sys.stderr` at instantiation time rather
Michael Foordd218e952011-01-03 12:55:11 +00001934 than import time.
1935
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001936 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001937
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001938 This method returns the instance of ``TestResult`` used by :meth:`run`.
1939 It is not intended to be called directly, but can be overridden in
1940 subclasses to provide a custom ``TestResult``.
1941
Michael Foord34c94622010-02-10 15:51:42 +00001942 ``_makeResult()`` instantiates the class or callable passed in the
1943 ``TextTestRunner`` constructor as the ``resultclass`` argument. It
Benjamin Petersonb48af542010-04-11 20:43:16 +00001944 defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
Michael Foord34c94622010-02-10 15:51:42 +00001945 The result class is instantiated with the following arguments::
1946
1947 stream, descriptions, verbosity
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001948
Ezio Melotti60901872010-12-01 00:56:10 +00001949
Georg Brandl419e3de2010-12-01 15:44:25 +00001950.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
Ezio Melotti40dcb1d2011-03-10 13:46:50 +02001951 testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \
Georg Brandl419e3de2010-12-01 15:44:25 +00001952 failfast=None, catchbreak=None, buffer=None, warnings=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001953
1954 A command-line program that runs a set of tests; this is primarily for making
1955 test modules conveniently executable. The simplest use for this function is to
1956 include the following line at the end of a test script::
1957
1958 if __name__ == '__main__':
1959 unittest.main()
1960
Benjamin Petersond2397752009-06-27 23:45:02 +00001961 You can run tests with more detailed information by passing in the verbosity
1962 argument::
1963
1964 if __name__ == '__main__':
1965 unittest.main(verbosity=2)
1966
Georg Brandl116aa622007-08-15 14:28:22 +00001967 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001968 created instance of it. By default ``main`` calls :func:`sys.exit` with
1969 an exit code indicating success or failure of the tests run.
1970
1971 ``main`` supports being used from the interactive interpreter by passing in the
1972 argument ``exit=False``. This displays the result on standard output without
1973 calling :func:`sys.exit`::
1974
1975 >>> from unittest import main
1976 >>> main(module='test_module', exit=False)
1977
Benjamin Petersonb48af542010-04-11 20:43:16 +00001978 The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
Éric Araujo76338ec2010-11-26 23:46:18 +00001979 effect as the same-name `command-line options`_.
Benjamin Petersonb48af542010-04-11 20:43:16 +00001980
Ezio Melotti60901872010-12-01 00:56:10 +00001981 The *warning* argument specifies the :ref:`warning filter <warning-filter>`
1982 that should be used while running the tests. If it's not specified, it will
1983 remain ``None`` if a :option:`-W` option is passed to :program:`python`,
1984 otherwise it will be set to ``'default'``.
1985
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001986 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1987 This stores the result of the tests run as the ``result`` attribute.
1988
Éric Araujo971dc012010-12-16 03:13:05 +00001989 .. versionchanged:: 3.1
1990 The ``exit`` parameter was added.
1991
Georg Brandl853947a2010-01-31 18:53:23 +00001992 .. versionchanged:: 3.2
Éric Araujo971dc012010-12-16 03:13:05 +00001993 The ``verbosity``, ``failfast``, ``catchbreak``, ``buffer``
Ezio Melotti60901872010-12-01 00:56:10 +00001994 and ``warnings`` parameters were added.
Benjamin Petersond2397752009-06-27 23:45:02 +00001995
1996
1997load_tests Protocol
1998###################
1999
Georg Brandl853947a2010-01-31 18:53:23 +00002000.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002001
Benjamin Petersond2397752009-06-27 23:45:02 +00002002Modules or packages can customize how tests are loaded from them during normal
2003test runs or test discovery by implementing a function called ``load_tests``.
2004
2005If a test module defines ``load_tests`` it will be called by
2006:meth:`TestLoader.loadTestsFromModule` with the following arguments::
2007
2008 load_tests(loader, standard_tests, None)
2009
2010It should return a :class:`TestSuite`.
2011
2012*loader* is the instance of :class:`TestLoader` doing the loading.
2013*standard_tests* are the tests that would be loaded by default from the
2014module. It is common for test modules to only want to add or remove tests
2015from the standard set of tests.
2016The third argument is used when loading packages as part of test discovery.
2017
2018A typical ``load_tests`` function that loads tests from a specific set of
2019:class:`TestCase` classes may look like::
2020
2021 test_cases = (TestCase1, TestCase2, TestCase3)
2022
2023 def load_tests(loader, tests, pattern):
2024 suite = TestSuite()
2025 for test_class in test_cases:
2026 tests = loader.loadTestsFromTestCase(test_class)
2027 suite.addTests(tests)
2028 return suite
2029
2030If discovery is started, either from the command line or by calling
2031:meth:`TestLoader.discover`, with a pattern that matches a package
2032name then the package :file:`__init__.py` will be checked for ``load_tests``.
2033
2034.. note::
2035
Ezio Melotti0639d5a2009-12-19 23:26:38 +00002036 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00002037 that start with 'test' but *won't* match any test directories.
2038
2039 A pattern like 'test*' will match test packages as well as
2040 modules.
2041
2042If the package :file:`__init__.py` defines ``load_tests`` then it will be
2043called and discovery not continued into the package. ``load_tests``
2044is called with the following arguments::
2045
2046 load_tests(loader, standard_tests, pattern)
2047
2048This should return a :class:`TestSuite` representing all the tests
2049from the package. (``standard_tests`` will only contain tests
2050collected from :file:`__init__.py`.)
2051
2052Because the pattern is passed into ``load_tests`` the package is free to
2053continue (and potentially modify) test discovery. A 'do nothing'
2054``load_tests`` function for a test package would look like::
2055
2056 def load_tests(loader, standard_tests, pattern):
2057 # top level directory cached on loader instance
2058 this_dir = os.path.dirname(__file__)
2059 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
2060 standard_tests.addTests(package_tests)
2061 return standard_tests
Benjamin Petersonb48af542010-04-11 20:43:16 +00002062
2063
2064Class and Module Fixtures
2065-------------------------
2066
2067Class and module level fixtures are implemented in :class:`TestSuite`. When
2068the test suite encounters a test from a new class then :meth:`tearDownClass`
2069from the previous class (if there is one) is called, followed by
2070:meth:`setUpClass` from the new class.
2071
2072Similarly if a test is from a different module from the previous test then
2073``tearDownModule`` from the previous module is run, followed by
2074``setUpModule`` from the new module.
2075
2076After all the tests have run the final ``tearDownClass`` and
2077``tearDownModule`` are run.
2078
2079Note that shared fixtures do not play well with [potential] features like test
2080parallelization and they break test isolation. They should be used with care.
2081
2082The default ordering of tests created by the unittest test loaders is to group
2083all tests from the same modules and classes together. This will lead to
2084``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
2085module. If you randomize the order, so that tests from different modules and
2086classes are adjacent to each other, then these shared fixture functions may be
2087called multiple times in a single test run.
2088
2089Shared fixtures are not intended to work with suites with non-standard
2090ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
2091support shared fixtures.
2092
2093If there are any exceptions raised during one of the shared fixture functions
2094the test is reported as an error. Because there is no corresponding test
2095instance an ``_ErrorHolder`` object (that has the same interface as a
2096:class:`TestCase`) is created to represent the error. If you are just using
2097the standard unittest test runner then this detail doesn't matter, but if you
2098are a framework author it may be relevant.
2099
2100
2101setUpClass and tearDownClass
2102~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2103
2104These must be implemented as class methods::
2105
2106 import unittest
2107
2108 class Test(unittest.TestCase):
2109 @classmethod
2110 def setUpClass(cls):
2111 cls._connection = createExpensiveConnectionObject()
2112
2113 @classmethod
2114 def tearDownClass(cls):
2115 cls._connection.destroy()
2116
2117If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
2118then you must call up to them yourself. The implementations in
2119:class:`TestCase` are empty.
2120
2121If an exception is raised during a ``setUpClass`` then the tests in the class
2122are not run and the ``tearDownClass`` is not run. Skipped classes will not
Michael Foord98b3e762010-06-05 21:59:55 +00002123have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
2124``SkipTest`` exception then the class will be reported as having been skipped
2125instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002126
2127
2128setUpModule and tearDownModule
2129~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2130
2131These should be implemented as functions::
2132
2133 def setUpModule():
2134 createConnection()
2135
2136 def tearDownModule():
2137 closeConnection()
2138
2139If an exception is raised in a ``setUpModule`` then none of the tests in the
Michael Foord98b3e762010-06-05 21:59:55 +00002140module will be run and the ``tearDownModule`` will not be run. If the exception is a
2141``SkipTest`` exception then the module will be reported as having been skipped
2142instead of as an error.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002143
2144
2145Signal Handling
2146---------------
2147
Georg Brandl419e3de2010-12-01 15:44:25 +00002148.. versionadded:: 3.2
2149
Éric Araujo8acb67c2010-11-26 23:31:07 +00002150The :option:`-c/--catch <unittest -c>` command-line option to unittest,
Éric Araujo76338ec2010-11-26 23:46:18 +00002151along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
2152more friendly handling of control-C during a test run. With catch break
2153behavior enabled control-C will allow the currently running test to complete,
2154and the test run will then end and report all the results so far. A second
2155control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002156
Michael Foordde4ceab2010-04-25 19:53:49 +00002157The control-c handling signal handler attempts to remain compatible with code or
2158tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
2159handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
2160i.e. it has been replaced by the system under test and delegated to, then it
2161calls the default handler. This will normally be the expected behavior by code
2162that replaces an installed handler and delegates to it. For individual tests
2163that need ``unittest`` control-c handling disabled the :func:`removeHandler`
2164decorator can be used.
2165
2166There are a few utility functions for framework authors to enable control-c
2167handling functionality within test frameworks.
Benjamin Petersonb48af542010-04-11 20:43:16 +00002168
2169.. function:: installHandler()
2170
2171 Install the control-c handler. When a :const:`signal.SIGINT` is received
2172 (usually in response to the user pressing control-c) all registered results
2173 have :meth:`~TestResult.stop` called.
2174
Michael Foord469b1f02010-04-26 23:41:26 +00002175
Benjamin Petersonb48af542010-04-11 20:43:16 +00002176.. function:: registerResult(result)
2177
2178 Register a :class:`TestResult` object for control-c handling. Registering a
2179 result stores a weak reference to it, so it doesn't prevent the result from
2180 being garbage collected.
2181
Michael Foordde4ceab2010-04-25 19:53:49 +00002182 Registering a :class:`TestResult` object has no side-effects if control-c
2183 handling is not enabled, so test frameworks can unconditionally register
2184 all results they create independently of whether or not handling is enabled.
2185
Michael Foord469b1f02010-04-26 23:41:26 +00002186
Benjamin Petersonb48af542010-04-11 20:43:16 +00002187.. function:: removeResult(result)
2188
2189 Remove a registered result. Once a result has been removed then
2190 :meth:`~TestResult.stop` will no longer be called on that result object in
2191 response to a control-c.
2192
Michael Foord469b1f02010-04-26 23:41:26 +00002193
Michael Foordde4ceab2010-04-25 19:53:49 +00002194.. function:: removeHandler(function=None)
2195
2196 When called without arguments this function removes the control-c handler
2197 if it has been installed. This function can also be used as a test decorator
2198 to temporarily remove the handler whilst the test is being executed::
2199
2200 @unittest.removeHandler
2201 def test_signal_handling(self):
2202 ...