blob: 85757820f0bd2bd13ab0ec7a94df03f7f2156fde [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
11
Benjamin Peterson5254c042009-03-23 22:25:03 +000012.. versionchanged:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +000013 Added test :ref:`skipping and expected failures <unittest-skipping>`.
Benjamin Peterson5254c042009-03-23 22:25:03 +000014
Georg Brandl116aa622007-08-15 14:28:22 +000015The Python unit testing framework, sometimes referred to as "PyUnit," is a
16Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
17turn, a Java version of Kent's Smalltalk testing framework. Each is the de
18facto standard unit testing framework for its respective language.
19
20:mod:`unittest` supports test automation, sharing of setup and shutdown code for
21tests, aggregation of tests into collections, and independence of the tests from
22the reporting framework. The :mod:`unittest` module provides classes that make
23it easy to support these qualities for a set of tests.
24
25To achieve this, :mod:`unittest` supports some important concepts:
26
27test fixture
28 A :dfn:`test fixture` represents the preparation needed to perform one or more
29 tests, and any associate cleanup actions. This may involve, for example,
30 creating temporary or proxy databases, directories, or starting a server
31 process.
32
33test case
34 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
35 response to a particular set of inputs. :mod:`unittest` provides a base class,
36 :class:`TestCase`, which may be used to create new test cases.
37
38test suite
39 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
40 used to aggregate tests that should be executed together.
41
42test runner
43 A :dfn:`test runner` is a component which orchestrates the execution of tests
44 and provides the outcome to the user. The runner may use a graphical interface,
45 a textual interface, or return a special value to indicate the results of
46 executing the tests.
47
48The test case and test fixture concepts are supported through the
49:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
50used when creating new tests, and the latter can be used when integrating
51existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson52baa292009-03-24 00:56:30 +000052fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
53:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
54and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
55can be passed to the constructor for these purposes. When the test is run, the
56fixture initialization is run first; if it succeeds, the cleanup method is run
57after the test has been executed, regardless of the outcome of the test. Each
58instance of the :class:`TestCase` will only be used to run a single test method,
59so a new fixture is created for each test.
Georg Brandl116aa622007-08-15 14:28:22 +000060
61Test suites are implemented by the :class:`TestSuite` class. This class allows
62individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson14a3dd72009-05-25 00:51:58 +000063all tests added directly to the suite and in "child" test suites are run.
Georg Brandl116aa622007-08-15 14:28:22 +000064
Benjamin Peterson52baa292009-03-24 00:56:30 +000065A test runner is an object that provides a single method,
66:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
67object as a parameter, and returns a result object. The class
68:class:`TestResult` is provided for use as the result object. :mod:`unittest`
69provides the :class:`TextTestRunner` as an example test runner which reports
70test results on the standard error stream by default. Alternate runners can be
71implemented for other environments (such as graphical environments) without any
72need to derive from a specific class.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74
75.. seealso::
76
77 Module :mod:`doctest`
78 Another test-support module with a very different flavor.
79
80 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
81 Kent Beck's original paper on testing frameworks using the pattern shared by
82 :mod:`unittest`.
83
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000084 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
85 Third-party unittest frameworks with a lighter-weight syntax
86 for writing tests. For example, ``assert func(10) == 42``.
87
88 `python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
89 Tools for creating mock test objects (objects simulating external resources).
Georg Brandl116aa622007-08-15 14:28:22 +000090
91.. _unittest-minimal-example:
92
93Basic example
94-------------
95
96The :mod:`unittest` module provides a rich set of tools for constructing and
97running tests. This section demonstrates that a small subset of the tools
98suffice to meet the needs of most users.
99
100Here is a short script to test three functions from the :mod:`random` module::
101
102 import random
103 import unittest
104
105 class TestSequenceFunctions(unittest.TestCase):
106
107 def setUp(self):
Georg Brandla08a3c52009-08-13 08:40:50 +0000108 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +0000109
Benjamin Peterson52baa292009-03-24 00:56:30 +0000110 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000111 # make sure the shuffled sequence does not lose any elements
112 random.shuffle(self.seq)
113 self.seq.sort()
Georg Brandla08a3c52009-08-13 08:40:50 +0000114 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Benjamin Peterson52baa292009-03-24 00:56:30 +0000116 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000117 element = random.choice(self.seq)
Ezio Melottid5031802010-02-04 20:29:01 +0000118 self.assertIn(element, self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000119
Benjamin Peterson52baa292009-03-24 00:56:30 +0000120 def test_sample(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000121 self.assertRaises(ValueError, random.sample, self.seq, 20)
122 for element in random.sample(self.seq, 5):
Ezio Melottid5031802010-02-04 20:29:01 +0000123 self.assertIn(element, self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125 if __name__ == '__main__':
126 unittest.main()
127
Benjamin Peterson52baa292009-03-24 00:56:30 +0000128A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000129individual tests are defined with methods whose names start with the letters
130``test``. This naming convention informs the test runner about which methods
131represent tests.
132
Benjamin Peterson52baa292009-03-24 00:56:30 +0000133The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
134expected result; :meth:`~TestCase.assert_` to verify a condition; or
135:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
136These methods are used instead of the :keyword:`assert` statement so the test
137runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Benjamin Peterson52baa292009-03-24 00:56:30 +0000139When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
140method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
141defined, the test runner will invoke that method after each test. In the
142example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
143test.
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145The final block shows a simple way to run the tests. :func:`unittest.main`
Éric Araujo3efdf062010-12-16 03:16:29 +0000146provides a command-line interface to the test script. When run from the command
Georg Brandl116aa622007-08-15 14:28:22 +0000147line, the above script produces an output that looks like this::
148
149 ...
150 ----------------------------------------------------------------------
151 Ran 3 tests in 0.000s
152
153 OK
154
155Instead of :func:`unittest.main`, there are other ways to run the tests with a
156finer level of control, less terse output, and no requirement to be run from the
157command line. For example, the last two lines may be replaced with::
158
159 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
160 unittest.TextTestRunner(verbosity=2).run(suite)
161
162Running the revised script from the interpreter or another script produces the
163following output::
164
Ezio Melottic08cae92010-02-28 03:48:50 +0000165 test_choice (__main__.TestSequenceFunctions) ... ok
166 test_sample (__main__.TestSequenceFunctions) ... ok
167 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl116aa622007-08-15 14:28:22 +0000168
169 ----------------------------------------------------------------------
170 Ran 3 tests in 0.110s
171
172 OK
173
174The above examples show the most commonly used :mod:`unittest` features which
175are sufficient to meet many everyday testing needs. The remainder of the
176documentation explores the full feature set from first principles.
177
178
Éric Araujo3efdf062010-12-16 03:16:29 +0000179.. _unittest-command-line-interface:
180
181Command-Line Interface
182----------------------
183
184The unittest module can be used from the command line to run tests from
185modules, classes or even individual test methods::
186
187 python -m unittest test_module1 test_module2
188 python -m unittest test_module.TestClass
189 python -m unittest test_module.TestClass.test_method
190
191You can pass in a list with any combination of module names, and fully
192qualified class or method names.
193
194You can run tests with more detail (higher verbosity) by passing in the -v flag::
195
196 python -m unittest -v test_module
197
198For a list of all the command-line options::
199
200 python -m unittest -h
201
202
Georg Brandl116aa622007-08-15 14:28:22 +0000203.. _organizing-tests:
204
205Organizing test code
206--------------------
207
208The basic building blocks of unit testing are :dfn:`test cases` --- single
209scenarios that must be set up and checked for correctness. In :mod:`unittest`,
210test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
211class. To make your own test cases you must write subclasses of
212:class:`TestCase`, or use :class:`FunctionTestCase`.
213
214An instance of a :class:`TestCase`\ -derived class is an object that can
215completely run a single test method, together with optional set-up and tidy-up
216code.
217
218The testing code of a :class:`TestCase` instance should be entirely self
219contained, such that it can be run either in isolation or in arbitrary
220combination with any number of other test cases.
221
Benjamin Peterson52baa292009-03-24 00:56:30 +0000222The simplest :class:`TestCase` subclass will simply override the
223:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225 import unittest
226
227 class DefaultWidgetSizeTestCase(unittest.TestCase):
228 def runTest(self):
229 widget = Widget('The widget')
230 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
231
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000232Note that in order to test something, we use the one of the :meth:`assert\*`
233methods provided by the :class:`TestCase` base class. If the
Georg Brandl116aa622007-08-15 14:28:22 +0000234test fails, an exception will be raised, and :mod:`unittest` will identify the
235test case as a :dfn:`failure`. Any other exceptions will be treated as
236:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
237caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
238caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
239function call.
240
241The way to run a test case will be described later. For now, note that to
242construct an instance of such a test case, we call its constructor without
243arguments::
244
245 testCase = DefaultWidgetSizeTestCase()
246
247Now, such test cases can be numerous, and their set-up can be repetitive. In
248the above case, constructing a :class:`Widget` in each of 100 Widget test case
249subclasses would mean unsightly duplication.
250
251Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000252:meth:`~TestCase.setUp`, which the testing framework will automatically call for
253us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255 import unittest
256
257 class SimpleWidgetTestCase(unittest.TestCase):
258 def setUp(self):
259 self.widget = Widget('The widget')
260
261 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
262 def runTest(self):
Ezio Melottid5031802010-02-04 20:29:01 +0000263 self.assertEqual(self.widget.size(), (50,50),
264 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266 class WidgetResizeTestCase(SimpleWidgetTestCase):
267 def runTest(self):
268 self.widget.resize(100,150)
Ezio Melottid5031802010-02-04 20:29:01 +0000269 self.assertEqual(self.widget.size(), (100,150),
270 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000271
Benjamin Peterson52baa292009-03-24 00:56:30 +0000272If the :meth:`~TestCase.setUp` method raises an exception while the test is
273running, the framework will consider the test to have suffered an error, and the
274:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Benjamin Peterson52baa292009-03-24 00:56:30 +0000276Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
277after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000278
279 import unittest
280
281 class SimpleWidgetTestCase(unittest.TestCase):
282 def setUp(self):
283 self.widget = Widget('The widget')
284
285 def tearDown(self):
286 self.widget.dispose()
287 self.widget = None
288
Benjamin Peterson52baa292009-03-24 00:56:30 +0000289If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
290be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000291
292Such a working environment for the testing code is called a :dfn:`fixture`.
293
294Often, many small test cases will use the same fixture. In this case, we would
295end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
296classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000297discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
298mechanism::
299
300 import unittest
301
302 class WidgetTestCase(unittest.TestCase):
303 def setUp(self):
304 self.widget = Widget('The widget')
305
306 def tearDown(self):
307 self.widget.dispose()
308 self.widget = None
309
Ezio Melottic08cae92010-02-28 03:48:50 +0000310 def test_default_size(self):
Ezio Melottid5031802010-02-04 20:29:01 +0000311 self.assertEqual(self.widget.size(), (50,50),
312 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Ezio Melottic08cae92010-02-28 03:48:50 +0000314 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000315 self.widget.resize(100,150)
Ezio Melottid5031802010-02-04 20:29:01 +0000316 self.assertEqual(self.widget.size(), (100,150),
317 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000318
Benjamin Peterson52baa292009-03-24 00:56:30 +0000319Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
320provided two different test methods. Class instances will now each run one of
Ezio Melottic08cae92010-02-28 03:48:50 +0000321the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000322separately for each instance. When creating an instance we must specify the
323test method it is to run. We do this by passing the method name in the
324constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000325
Ezio Melottic08cae92010-02-28 03:48:50 +0000326 defaultSizeTestCase = WidgetTestCase('test_default_size')
327 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000328
329Test case instances are grouped together according to the features they test.
330:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
331represented by :mod:`unittest`'s :class:`TestSuite` class::
332
333 widgetTestSuite = unittest.TestSuite()
Ezio Melottic08cae92010-02-28 03:48:50 +0000334 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
335 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337For the ease of running tests, as we will see later, it is a good idea to
338provide in each test module a callable object that returns a pre-built test
339suite::
340
341 def suite():
342 suite = unittest.TestSuite()
Ezio Melottic08cae92010-02-28 03:48:50 +0000343 suite.addTest(WidgetTestCase('test_default_size'))
344 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000345 return suite
346
347or even::
348
349 def suite():
Ezio Melottic08cae92010-02-28 03:48:50 +0000350 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352 return unittest.TestSuite(map(WidgetTestCase, tests))
353
354Since it is a common pattern to create a :class:`TestCase` subclass with many
355similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
356class that can be used to automate the process of creating a test suite and
357populating it with individual tests. For example, ::
358
359 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
360
Ezio Melottic08cae92010-02-28 03:48:50 +0000361will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
362``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000363name prefix to identify test methods automatically.
364
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000365Note that the order in which the various test cases will be run is
366determined by sorting the test function names with respect to the
367built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369Often it is desirable to group suites of test cases together, so as to run tests
370for the whole system at once. This is easy, since :class:`TestSuite` instances
371can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
372added to a :class:`TestSuite`::
373
374 suite1 = module1.TheTestSuite()
375 suite2 = module2.TheTestSuite()
376 alltests = unittest.TestSuite([suite1, suite2])
377
378You can place the definitions of test cases and test suites in the same modules
379as the code they are to test (such as :file:`widget.py`), but there are several
380advantages to placing the test code in a separate module, such as
381:file:`test_widget.py`:
382
383* The test module can be run standalone from the command line.
384
385* The test code can more easily be separated from shipped code.
386
387* There is less temptation to change test code to fit the code it tests without
388 a good reason.
389
390* Test code should be modified much less frequently than the code it tests.
391
392* Tested code can be refactored more easily.
393
394* Tests for modules written in C must be in separate modules anyway, so why not
395 be consistent?
396
397* If the testing strategy changes, there is no need to change the source code.
398
399
400.. _legacy-unit-tests:
401
402Re-using old test code
403----------------------
404
405Some users will find that they have existing test code that they would like to
406run from :mod:`unittest`, without converting every old test function to a
407:class:`TestCase` subclass.
408
409For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
410This subclass of :class:`TestCase` can be used to wrap an existing test
411function. Set-up and tear-down functions can also be provided.
412
413Given the following test function::
414
415 def testSomething():
416 something = makeSomething()
417 assert something.name is not None
418 # ...
419
420one can create an equivalent test case instance as follows::
421
422 testcase = unittest.FunctionTestCase(testSomething)
423
424If there are additional set-up and tear-down methods that should be called as
425part of the test case's operation, they can also be provided like so::
426
427 testcase = unittest.FunctionTestCase(testSomething,
428 setUp=makeSomethingDB,
429 tearDown=deleteSomethingDB)
430
431To make migrating existing test suites easier, :mod:`unittest` supports tests
432raising :exc:`AssertionError` to indicate test failure. However, it is
433recommended that you use the explicit :meth:`TestCase.fail\*` and
434:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
435may treat :exc:`AssertionError` differently.
436
437.. note::
438
439 Even though :class:`FunctionTestCase` can be used to quickly convert an existing
440 test base over to a :mod:`unittest`\ -based system, this approach is not
441 recommended. Taking the time to set up proper :class:`TestCase` subclasses will
442 make future test refactorings infinitely easier.
443
Benjamin Peterson52baa292009-03-24 00:56:30 +0000444In some cases, the existing tests may have been written using the :mod:`doctest`
445module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
446automatically build :class:`unittest.TestSuite` instances from the existing
447:mod:`doctest`\ -based tests.
448
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Benjamin Peterson5254c042009-03-23 22:25:03 +0000450.. _unittest-skipping:
451
452Skipping tests and expected failures
453------------------------------------
454
455Unittest supports skipping individual test methods and even whole classes of
456tests. In addition, it supports marking a test as a "expected failure," a test
457that is broken and will fail, but shouldn't be counted as a failure on a
458:class:`TestResult`.
459
460Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
461or one of its conditional variants.
462
463Basic skipping looks like this: ::
464
465 class MyTestCase(unittest.TestCase):
466
467 @unittest.skip("demonstrating skipping")
468 def test_nothing(self):
469 self.fail("shouldn't happen")
470
Benjamin Petersonded31c42009-03-30 15:04:16 +0000471 @unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version")
472 def test_format(self):
473 # Tests that work for only a certain version of the library.
474 pass
475
476 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
477 def test_windows_support(self):
478 # windows specific testing code
479 pass
480
Benjamin Peterson5254c042009-03-23 22:25:03 +0000481This is the output of running the example above in verbose mode: ::
482
Benjamin Petersonded31c42009-03-30 15:04:16 +0000483 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000484 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000485 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000486
487 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000488 Ran 3 tests in 0.005s
489
490 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000491
492Classes can be skipped just like methods: ::
493
494 @skip("showing class skipping")
495 class MySkippedTestCase(unittest.TestCase):
496 def test_not_run(self):
497 pass
498
Benjamin Peterson52baa292009-03-24 00:56:30 +0000499:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
500that needs to be set up is not available.
501
Benjamin Peterson5254c042009-03-23 22:25:03 +0000502Expected failures use the :func:`expectedFailure` decorator. ::
503
504 class ExpectedFailureTestCase(unittest.TestCase):
505 @unittest.expectedFailure
506 def test_fail(self):
507 self.assertEqual(1, 0, "broken")
508
509It's easy to roll your own skipping decorators by making a decorator that calls
510:func:`skip` on the test when it wants it to be skipped. This decorator skips
511the test unless the passed object has a certain attribute: ::
512
513 def skipUnlessHasattr(obj, attr):
514 if hasattr(obj, attr):
515 return lambda func: func
516 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
517
518The following decorators implement test skipping and expected failures:
519
520.. function:: skip(reason)
521
522 Unconditionally skip the decorated test. *reason* should describe why the
523 test is being skipped.
524
525.. function:: skipIf(condition, reason)
526
527 Skip the decorated test if *condition* is true.
528
529.. function:: skipUnless(condition, reason)
530
Georg Brandl4b054662010-10-06 08:56:53 +0000531 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000532
533.. function:: expectedFailure
534
535 Mark the test as an expected failure. If the test fails when run, the test
536 is not counted as a failure.
537
538
Georg Brandl116aa622007-08-15 14:28:22 +0000539.. _unittest-contents:
540
541Classes and functions
542---------------------
543
Benjamin Peterson52baa292009-03-24 00:56:30 +0000544This section describes in depth the API of :mod:`unittest`.
545
546
547.. _testcase-objects:
548
549Test cases
550~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000551
Georg Brandlb044b2a2009-09-16 16:05:59 +0000552.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000553
554 Instances of the :class:`TestCase` class represent the smallest testable units
555 in the :mod:`unittest` universe. This class is intended to be used as a base
556 class, with specific tests being implemented by concrete subclasses. This class
557 implements the interface needed by the test runner to allow it to drive the
558 test, and methods that the test code can use to check for and report various
559 kinds of failure.
560
561 Each instance of :class:`TestCase` will run a single test method: the method
562 named *methodName*. If you remember, we had an earlier example that went
563 something like this::
564
565 def suite():
566 suite = unittest.TestSuite()
Ezio Melottic08cae92010-02-28 03:48:50 +0000567 suite.addTest(WidgetTestCase('test_default_size'))
568 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000569 return suite
570
571 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
572 single test.
573
Benjamin Peterson52baa292009-03-24 00:56:30 +0000574 *methodName* defaults to :meth:`runTest`.
575
576 :class:`TestCase` instances provide three groups of methods: one group used
577 to run the test, another used by the test implementation to check conditions
578 and report failures, and some inquiry methods allowing information about the
579 test itself to be gathered.
580
581 Methods in the first group (running the test) are:
582
583
584 .. method:: setUp()
585
586 Method called to prepare the test fixture. This is called immediately
587 before calling the test method; any exception raised by this method will
588 be considered an error rather than a test failure. The default
589 implementation does nothing.
590
591
592 .. method:: tearDown()
593
594 Method called immediately after the test method has been called and the
595 result recorded. This is called even if the test method raised an
596 exception, so the implementation in subclasses may need to be particularly
597 careful about checking internal state. Any exception raised by this
598 method will be considered an error rather than a test failure. This
599 method will only be called if the :meth:`setUp` succeeds, regardless of
600 the outcome of the test method. The default implementation does nothing.
601
602
Georg Brandlb044b2a2009-09-16 16:05:59 +0000603 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000604
605 Run the test, collecting the result into the test result object passed as
606 *result*. If *result* is omitted or :const:`None`, a temporary result
Georg Brandlbcc484e2009-08-13 11:51:54 +0000607 object is created (by calling the :meth:`defaultTestResult` method) and
608 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000609
610 The same effect may be had by simply calling the :class:`TestCase`
611 instance.
612
613
Benjamin Petersone549ead2009-03-28 21:42:05 +0000614 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000615
Stefan Krah671b0162010-05-19 16:11:36 +0000616 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000617 test. See :ref:`unittest-skipping` for more information.
618
Ezio Melotti8d5c16a2010-04-20 09:36:13 +0000619 .. versionadded:: 3.1
620
Benjamin Peterson52baa292009-03-24 00:56:30 +0000621
622 .. method:: debug()
623
624 Run the test without collecting the result. This allows exceptions raised
625 by the test to be propagated to the caller, and can be used to support
626 running tests under a debugger.
627
628 The test code can use any of the following methods to check for and report
629 failures.
630
631
Georg Brandlb044b2a2009-09-16 16:05:59 +0000632 .. method:: assertTrue(expr, msg=None)
633 assert_(expr, msg=None)
634 failUnless(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000635
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000636 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson52baa292009-03-24 00:56:30 +0000637 will be *msg* if given, otherwise it will be :const:`None`.
638
Raymond Hettinger35a88362009-04-09 00:08:24 +0000639 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000640 :meth:`failUnless`.
641
Benjamin Peterson52baa292009-03-24 00:56:30 +0000642
Georg Brandlb044b2a2009-09-16 16:05:59 +0000643 .. method:: assertEqual(first, second, msg=None)
644 failUnlessEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000645
646 Test that *first* and *second* are equal. If the values do not compare
647 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000648 :const:`None`. Note that using :meth:`assertEqual` improves upon
649 doing the comparison as the first parameter to :meth:`assertTrue`: the
650 default value for *msg* include representations of both *first* and
651 *second*.
652
653 In addition, if *first* and *second* are the exact same type and one of
654 list, tuple, dict, set, or frozenset or any type that a subclass
655 registers :meth:`addTypeEqualityFunc` the type specific equality function
656 will be called in order to generate a more useful default error message.
657
Raymond Hettinger35a88362009-04-09 00:08:24 +0000658 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000659 Added the automatic calling of type specific equality function.
660
Raymond Hettinger35a88362009-04-09 00:08:24 +0000661 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000662 :meth:`failUnlessEqual`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000663
664
Georg Brandlb044b2a2009-09-16 16:05:59 +0000665 .. method:: assertNotEqual(first, second, msg=None)
666 failIfEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000667
668 Test that *first* and *second* are not equal. If the values do compare
669 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000670 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
671 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson52baa292009-03-24 00:56:30 +0000672 default value for *msg* can be computed to include representations of both
673 *first* and *second*.
674
Raymond Hettinger35a88362009-04-09 00:08:24 +0000675 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000676 :meth:`failIfEqual`.
677
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000678
Michael Foordb36f8322010-11-02 14:46:41 +0000679 .. method:: assertAlmostEqual(first, second, places=7, msg=None)
680 failUnlessAlmostEqual(first, second, places=7, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000681
682 Test that *first* and *second* are approximately equal by computing the
683 difference, rounding to the given number of decimal *places* (default 7),
684 and comparing to zero.
685
686 Note that comparing a given number of decimal places is not the same as
687 comparing a given number of significant digits. If the values do not
688 compare equal, the test will fail with the explanation given by *msg*, or
689 :const:`None`.
690
Raymond Hettinger35a88362009-04-09 00:08:24 +0000691 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000692 :meth:`failUnlessAlmostEqual`.
693
Benjamin Peterson52baa292009-03-24 00:56:30 +0000694
Michael Foordb36f8322010-11-02 14:46:41 +0000695 .. method:: assertNotAlmostEqual(first, second, places=7, msg=None)
696 failIfAlmostEqual(first, second, places=7, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000697
698 Test that *first* and *second* are not approximately equal by computing
699 the difference, rounding to the given number of decimal *places* (default
700 7), and comparing to zero.
701
702 Note that comparing a given number of decimal places is not the same as
703 comparing a given number of significant digits. If the values do not
704 compare equal, the test will fail with the explanation given by *msg*, or
705 :const:`None`.
706
Raymond Hettinger35a88362009-04-09 00:08:24 +0000707 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000708 :meth:`failIfAlmostEqual`.
709
710
711 .. method:: assertGreater(first, second, msg=None)
712 assertGreaterEqual(first, second, msg=None)
713 assertLess(first, second, msg=None)
714 assertLessEqual(first, second, msg=None)
715
716 Test that *first* is respectively >, >=, < or <= than *second* depending
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000717 on the method name. If not, the test will fail with an explanation
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000718 or with the explanation given by *msg*::
719
720 >>> self.assertGreaterEqual(3, 4)
721 AssertionError: "3" unexpectedly not greater than or equal to "4"
722
Raymond Hettinger35a88362009-04-09 00:08:24 +0000723 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000724
725
726 .. method:: assertMultiLineEqual(self, first, second, msg=None)
727
728 Test that the multiline string *first* is equal to the string *second*.
729 When not equal a diff of the two strings highlighting the differences
730 will be included in the error message.
731
732 If specified *msg* will be used as the error message on failure.
733
Raymond Hettinger35a88362009-04-09 00:08:24 +0000734 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000735
736
Georg Brandlb044b2a2009-09-16 16:05:59 +0000737 .. method:: assertRegexpMatches(text, regexp, msg=None):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000738
739 Verifies that a *regexp* search matches *text*. Fails with an error
740 message including the pattern and the *text*. *regexp* may be
741 a regular expression object or a string containing a regular expression
742 suitable for use by :func:`re.search`.
743
Raymond Hettinger35a88362009-04-09 00:08:24 +0000744 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000745
746
747 .. method:: assertIn(first, second, msg=None)
748 assertNotIn(first, second, msg=None)
749
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000750 Tests that *first* is or is not in *second* with an explanatory error
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000751 message as appropriate.
752
753 If specified *msg* will be used as the error message on failure.
754
Raymond Hettinger35a88362009-04-09 00:08:24 +0000755 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000756
757
Gregory P. Smith48a5ec42010-02-28 22:01:02 +0000758 .. method:: assertSameElements(actual, expected, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000759
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000760 Test that sequence *expected* contains the same elements as *actual*,
761 regardless of their order. When they don't, an error message listing
762 the differences between the sequences will be generated.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000763
Gregory P. Smith48a5ec42010-02-28 22:01:02 +0000764 Duplicate elements are ignored when comparing *actual* and *expected*.
765 It is the equivalent of ``assertEqual(set(expected), set(actual))``
766 but it works with sequences of unhashable objects as well.
767
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000768 If specified *msg* will be used as the error message on failure.
769
Raymond Hettinger35a88362009-04-09 00:08:24 +0000770 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000771
772
773 .. method:: assertSetEqual(set1, set2, msg=None)
774
775 Tests that two sets are equal. If not, an error message is constructed
776 that lists the differences between the sets.
777
778 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
779 method.
780
781 If specified *msg* will be used as the error message on failure.
782
Raymond Hettinger35a88362009-04-09 00:08:24 +0000783 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000784
785
786 .. method:: assertDictEqual(expected, actual, msg=None)
787
788 Test that two dictionaries are equal. If not, an error message is
789 constructed that shows the differences in the dictionaries.
790
791 If specified *msg* will be used as the error message on failure.
792
Raymond Hettinger35a88362009-04-09 00:08:24 +0000793 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000794
795
796 .. method:: assertDictContainsSubset(expected, actual, msg=None)
797
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000798 Tests whether the key/value pairs in dictionary *actual* are a
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000799 superset of those in *expected*. If not, an error message listing
800 the missing keys and mismatched values is generated.
801
802 If specified *msg* will be used as the error message on failure.
803
Raymond Hettinger35a88362009-04-09 00:08:24 +0000804 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000805
806
807 .. method:: assertListEqual(list1, list2, msg=None)
808 assertTupleEqual(tuple1, tuple2, msg=None)
809
810 Tests that two lists or tuples are equal. If not an error message is
811 constructed that shows only the differences between the two. An error
812 is also raised if either of the parameters are of the wrong type.
813
814 If specified *msg* will be used as the error message on failure.
815
Raymond Hettinger35a88362009-04-09 00:08:24 +0000816 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000817
818
819 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
820
821 Tests that two sequences are equal. If a *seq_type* is supplied, both
822 *seq1* and *seq2* must be instances of *seq_type* or a failure will
823 be raised. If the sequences are different an error message is
824 constructed that shows the difference between the two.
825
826 If specified *msg* will be used as the error message on failure.
827
828 This method is used to implement :meth:`assertListEqual` and
829 :meth:`assertTupleEqual`.
830
Raymond Hettinger35a88362009-04-09 00:08:24 +0000831 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000832
Benjamin Peterson52baa292009-03-24 00:56:30 +0000833
Georg Brandlb044b2a2009-09-16 16:05:59 +0000834 .. method:: assertRaises(exception, callable, *args, **kwds)
835 failUnlessRaises(exception, callable, *args, **kwds)
836 assertRaises(exception)
837 failUnlessRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000838
839 Test that an exception is raised when *callable* is called with any
840 positional or keyword arguments that are also passed to
841 :meth:`assertRaises`. The test passes if *exception* is raised, is an
842 error if another exception is raised, or fails if no exception is raised.
843 To catch any of a group of exceptions, a tuple containing the exception
844 classes may be passed as *exception*.
845
Georg Brandlb044b2a2009-09-16 16:05:59 +0000846 If only the *exception* argument is given, returns a context manager so
847 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000848
Ezio Melotti0f365732010-02-08 22:07:38 +0000849 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000850 do_something()
851
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000852 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000853 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000854
Raymond Hettinger35a88362009-04-09 00:08:24 +0000855 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000856 :meth:`failUnlessRaises`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000857
Benjamin Peterson52baa292009-03-24 00:56:30 +0000858
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000859 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
860
861 Like :meth:`assertRaises` but also tests that *regexp* matches
862 on the string representation of the raised exception. *regexp* may be
863 a regular expression object or a string containing a regular expression
864 suitable for use by :func:`re.search`. Examples::
865
866 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
867 int, 'XYZ')
868
869 or::
870
871 with self.assertRaisesRegexp(ValueError, 'literal'):
872 int('XYZ')
873
Raymond Hettinger35a88362009-04-09 00:08:24 +0000874 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000875
876
Georg Brandlb044b2a2009-09-16 16:05:59 +0000877 .. method:: assertIsNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000878
879 This signals a test failure if *expr* is not None.
880
Raymond Hettinger35a88362009-04-09 00:08:24 +0000881 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000882
883
Georg Brandlb044b2a2009-09-16 16:05:59 +0000884 .. method:: assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000885
886 The inverse of the :meth:`assertIsNone` method.
887 This signals a test failure if *expr* is None.
888
Raymond Hettinger35a88362009-04-09 00:08:24 +0000889 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000890
891
Georg Brandlb044b2a2009-09-16 16:05:59 +0000892 .. method:: assertIs(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000893
894 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
895 object.
896
Georg Brandl705d9d52009-05-05 09:29:50 +0000897 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000898
899
Georg Brandlb044b2a2009-09-16 16:05:59 +0000900 .. method:: assertIsNot(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000901
902 The inverse of the :meth:`assertIs` method.
903 This signals a test failure if *expr1* and *expr2* evaluate to the same
904 object.
905
Georg Brandl705d9d52009-05-05 09:29:50 +0000906 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000907
908
Georg Brandlb044b2a2009-09-16 16:05:59 +0000909 .. method:: assertFalse(expr, msg=None)
910 failIf(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000911
912 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000913 This signals a test failure if *expr* is true, with *msg* or :const:`None`
914 for the error message.
915
Raymond Hettinger35a88362009-04-09 00:08:24 +0000916 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000917 :meth:`failIf`.
918
Benjamin Peterson52baa292009-03-24 00:56:30 +0000919
Georg Brandlb044b2a2009-09-16 16:05:59 +0000920 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000921
922 Signals a test failure unconditionally, with *msg* or :const:`None` for
923 the error message.
924
925
926 .. attribute:: failureException
927
928 This class attribute gives the exception raised by the test method. If a
929 test framework needs to use a specialized exception, possibly to carry
930 additional information, it must subclass this exception in order to "play
931 fair" with the framework. The initial value of this attribute is
932 :exc:`AssertionError`.
933
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000934
935 .. attribute:: longMessage
936
937 If set to True then any explicit failure message you pass in to the
938 assert methods will be appended to the end of the normal failure message.
939 The normal messages contain useful information about the objects involved,
940 for example the message from assertEqual shows you the repr of the two
941 unequal objects. Setting this attribute to True allows you to have a
942 custom error message in addition to the normal one.
943
944 This attribute defaults to False, meaning that a custom message passed
945 to an assert method will silence the normal message.
946
947 The class setting can be overridden in individual tests by assigning an
948 instance attribute to True or False before calling the assert methods.
949
Raymond Hettinger35a88362009-04-09 00:08:24 +0000950 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000951
952
Benjamin Peterson52baa292009-03-24 00:56:30 +0000953 Testing frameworks can use the following methods to collect information on
954 the test:
955
956
957 .. method:: countTestCases()
958
959 Return the number of tests represented by this test object. For
960 :class:`TestCase` instances, this will always be ``1``.
961
962
963 .. method:: defaultTestResult()
964
965 Return an instance of the test result class that should be used for this
966 test case class (if no other result instance is provided to the
967 :meth:`run` method).
968
969 For :class:`TestCase` instances, this will always be an instance of
970 :class:`TestResult`; subclasses of :class:`TestCase` should override this
971 as necessary.
972
973
974 .. method:: id()
975
976 Return a string identifying the specific test case. This is usually the
977 full name of the test method, including the module and class name.
978
979
980 .. method:: shortDescription()
981
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000982 Returns a description of the test, or :const:`None` if no description
983 has been provided. The default implementation of this method
984 returns the first line of the test method's docstring, if available,
985 along with the method name.
986
Raymond Hettinger35a88362009-04-09 00:08:24 +0000987 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000988 In earlier versions this only returned the first line of the test
989 method's docstring, if available or the :const:`None`. That led to
990 undesirable behavior of not printing the test name when someone was
991 thoughtful enough to write a docstring.
992
993
994 .. method:: addTypeEqualityFunc(typeobj, function)
995
996 Registers a type specific :meth:`assertEqual` equality checking
997 function to be called by :meth:`assertEqual` when both objects it has
998 been asked to compare are exactly *typeobj* (not subclasses).
999 *function* must take two positional arguments and a third msg=None
1000 keyword argument just as :meth:`assertEqual` does. It must raise
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001001 ``self.failureException`` when inequality between the first two
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001002 parameters is detected.
1003
1004 One good use of custom equality checking functions for a type
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001005 is to raise ``self.failureException`` with an error message useful
1006 for debugging the problem by explaining the inequalities in detail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001007
Raymond Hettinger35a88362009-04-09 00:08:24 +00001008 .. versionadded:: 3.1
Georg Brandl116aa622007-08-15 14:28:22 +00001009
1010
Georg Brandlb044b2a2009-09-16 16:05:59 +00001011 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001012
1013 Add a function to be called after :meth:`tearDown` to cleanup resources
1014 used during the test. Functions will be called in reverse order to the
1015 order they are added (LIFO). They are called with any arguments and
1016 keyword arguments passed into :meth:`addCleanup` when they are
1017 added.
1018
1019 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1020 then any cleanup functions added will still be called.
1021
Ezio Melotti8da105e2010-03-21 07:31:49 +00001022 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001023
1024
1025 .. method:: doCleanups()
1026
Barry Warsaw14e0a432010-04-12 14:55:03 +00001027 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001028 after :meth:`setUp` if :meth:`setUp` raises an exception.
1029
1030 It is responsible for calling all the cleanup functions added by
1031 :meth:`addCleanup`. If you need cleanup functions to be called
1032 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1033 yourself.
1034
1035 :meth:`doCleanups` pops methods off the stack of cleanup
1036 functions one at a time, so it can be called at any time.
1037
Ezio Melotti8da105e2010-03-21 07:31:49 +00001038 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001039
1040
Georg Brandlb044b2a2009-09-16 16:05:59 +00001041.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001042
1043 This class implements the portion of the :class:`TestCase` interface which
1044 allows the test runner to drive the test, but does not provide the methods which
1045 test code can use to check and report errors. This is used to create test cases
1046 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
1047 -based test framework.
1048
1049
Benjamin Peterson52baa292009-03-24 00:56:30 +00001050.. _testsuite-objects:
1051
Benjamin Peterson52baa292009-03-24 00:56:30 +00001052Grouping tests
1053~~~~~~~~~~~~~~
1054
Georg Brandlb044b2a2009-09-16 16:05:59 +00001055.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001056
1057 This class represents an aggregation of individual tests cases and test suites.
1058 The class presents the interface needed by the test runner to allow it to be run
1059 as any other test case. Running a :class:`TestSuite` instance is the same as
1060 iterating over the suite, running each test individually.
1061
1062 If *tests* is given, it must be an iterable of individual test cases or other
1063 test suites that will be used to build the suite initially. Additional methods
1064 are provided to add test cases and suites to the collection later on.
1065
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001066 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1067 they do not actually implement a test. Instead, they are used to aggregate
1068 tests into groups of tests that should be run together. Some additional
1069 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001070
1071
1072 .. method:: TestSuite.addTest(test)
1073
1074 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1075
1076
1077 .. method:: TestSuite.addTests(tests)
1078
1079 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1080 instances to this test suite.
1081
1082 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
1083 element.
1084
1085 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1086
1087
1088 .. method:: run(result)
1089
1090 Run the tests associated with this suite, collecting the result into the
1091 test result object passed as *result*. Note that unlike
1092 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1093 be passed in.
1094
1095
1096 .. method:: debug()
1097
1098 Run the tests associated with this suite without collecting the
1099 result. This allows exceptions raised by the test to be propagated to the
1100 caller and can be used to support running tests under a debugger.
1101
1102
1103 .. method:: countTestCases()
1104
1105 Return the number of tests represented by this test object, including all
1106 individual tests and sub-suites.
1107
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001108
1109 .. method:: __iter__()
1110
1111 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1112 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1113 that this method maybe called several times on a single suite
1114 (for example when counting tests or comparing for equality)
1115 so the tests returned must be the same for repeated iterations.
1116
Ezio Melotti8da105e2010-03-21 07:31:49 +00001117 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001118 In earlier versions the :class:`TestSuite` accessed tests directly rather
1119 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1120 for providing tests.
1121
Benjamin Peterson52baa292009-03-24 00:56:30 +00001122 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1123 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1124
1125
Benjamin Peterson52baa292009-03-24 00:56:30 +00001126Loading and running tests
1127~~~~~~~~~~~~~~~~~~~~~~~~~
1128
Georg Brandl116aa622007-08-15 14:28:22 +00001129.. class:: TestLoader()
1130
Benjamin Peterson52baa292009-03-24 00:56:30 +00001131 The :class:`TestLoader` class is used to create test suites from classes and
1132 modules. Normally, there is no need to create an instance of this class; the
1133 :mod:`unittest` module provides an instance that can be shared as
1134 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1135 customization of some configurable properties.
1136
1137 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001138
1139
Benjamin Peterson52baa292009-03-24 00:56:30 +00001140 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001141
Benjamin Peterson52baa292009-03-24 00:56:30 +00001142 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1143 :class:`testCaseClass`.
1144
1145
1146 .. method:: loadTestsFromModule(module)
1147
1148 Return a suite of all tests cases contained in the given module. This
1149 method searches *module* for classes derived from :class:`TestCase` and
1150 creates an instance of the class for each test method defined for the
1151 class.
1152
Georg Brandle720c0a2009-04-27 16:20:50 +00001153 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001154
1155 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1156 convenient in sharing fixtures and helper functions, defining test
1157 methods on base classes that are not intended to be instantiated
1158 directly does not play well with this method. Doing so, however, can
1159 be useful when the fixtures are different and defined in subclasses.
1160
1161
Georg Brandlb044b2a2009-09-16 16:05:59 +00001162 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001163
1164 Return a suite of all tests cases given a string specifier.
1165
1166 The specifier *name* is a "dotted name" that may resolve either to a
1167 module, a test case class, a test method within a test case class, a
1168 :class:`TestSuite` instance, or a callable object which returns a
1169 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1170 applied in the order listed here; that is, a method on a possible test
1171 case class will be picked up as "a test method within a test case class",
1172 rather than "a callable object".
1173
1174 For example, if you have a module :mod:`SampleTests` containing a
1175 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1176 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1177 specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
1178 suite which will run all three test methods. Using the specifier
1179 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
1180 which will run only the :meth:`test_two` test method. The specifier can refer
1181 to modules and packages which have not been imported; they will be imported as a
1182 side-effect.
1183
1184 The method optionally resolves *name* relative to the given *module*.
1185
1186
Georg Brandlb044b2a2009-09-16 16:05:59 +00001187 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001188
1189 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1190 than a single name. The return value is a test suite which supports all
1191 the tests defined for each name.
1192
1193
1194 .. method:: getTestCaseNames(testCaseClass)
1195
1196 Return a sorted sequence of method names found within *testCaseClass*;
1197 this should be a subclass of :class:`TestCase`.
1198
1199 The following attributes of a :class:`TestLoader` can be configured either by
1200 subclassing or assignment on an instance:
1201
1202
1203 .. attribute:: testMethodPrefix
1204
1205 String giving the prefix of method names which will be interpreted as test
1206 methods. The default value is ``'test'``.
1207
1208 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1209 methods.
1210
1211
1212 .. attribute:: sortTestMethodsUsing
1213
1214 Function to be used to compare method names when sorting them in
1215 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1216
1217
1218 .. attribute:: suiteClass
1219
1220 Callable object that constructs a test suite from a list of tests. No
1221 methods on the resulting object are needed. The default value is the
1222 :class:`TestSuite` class.
1223
1224 This affects all the :meth:`loadTestsFrom\*` methods.
1225
1226
Benjamin Peterson52baa292009-03-24 00:56:30 +00001227.. class:: TestResult
1228
1229 This class is used to compile information about which tests have succeeded
1230 and which have failed.
1231
1232 A :class:`TestResult` object stores the results of a set of tests. The
1233 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1234 properly recorded; test authors do not need to worry about recording the
1235 outcome of tests.
1236
1237 Testing frameworks built on top of :mod:`unittest` may want access to the
1238 :class:`TestResult` object generated by running a set of tests for reporting
1239 purposes; a :class:`TestResult` instance is returned by the
1240 :meth:`TestRunner.run` method for this purpose.
1241
1242 :class:`TestResult` instances have the following attributes that will be of
1243 interest when inspecting the results of running a set of tests:
1244
1245
1246 .. attribute:: errors
1247
1248 A list containing 2-tuples of :class:`TestCase` instances and strings
1249 holding formatted tracebacks. Each tuple represents a test which raised an
1250 unexpected exception.
1251
Benjamin Peterson52baa292009-03-24 00:56:30 +00001252 .. attribute:: failures
1253
1254 A list containing 2-tuples of :class:`TestCase` instances and strings
1255 holding formatted tracebacks. Each tuple represents a test where a failure
1256 was explicitly signalled using the :meth:`TestCase.fail\*` or
1257 :meth:`TestCase.assert\*` methods.
1258
Benjamin Peterson52baa292009-03-24 00:56:30 +00001259 .. attribute:: skipped
1260
1261 A list containing 2-tuples of :class:`TestCase` instances and strings
1262 holding the reason for skipping the test.
1263
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001264 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001265
1266 .. attribute:: expectedFailures
1267
Georg Brandl4b054662010-10-06 08:56:53 +00001268 A list containing 2-tuples of :class:`TestCase` instances and strings
1269 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001270 of the test case.
1271
1272 .. attribute:: unexpectedSuccesses
1273
1274 A list containing :class:`TestCase` instances that were marked as expected
1275 failures, but succeeded.
1276
1277 .. attribute:: shouldStop
1278
1279 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1280
1281
1282 .. attribute:: testsRun
1283
1284 The total number of tests run so far.
1285
1286
1287 .. method:: wasSuccessful()
1288
1289 Return :const:`True` if all tests run so far have passed, otherwise returns
1290 :const:`False`.
1291
1292
1293 .. method:: stop()
1294
1295 This method can be called to signal that the set of tests being run should
1296 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1297 :class:`TestRunner` objects should respect this flag and return without
1298 running any additional tests.
1299
1300 For example, this feature is used by the :class:`TextTestRunner` class to
1301 stop the test framework when the user signals an interrupt from the
1302 keyboard. Interactive tools which provide :class:`TestRunner`
1303 implementations can use this in a similar manner.
1304
1305 The following methods of the :class:`TestResult` class are used to maintain
1306 the internal data structures, and may be extended in subclasses to support
1307 additional reporting requirements. This is particularly useful in building
1308 tools which support interactive reporting while tests are being run.
1309
1310
1311 .. method:: startTest(test)
1312
1313 Called when the test case *test* is about to be run.
1314
1315 The default implementation simply increments the instance's :attr:`testsRun`
1316 counter.
1317
1318
1319 .. method:: stopTest(test)
1320
1321 Called after the test case *test* has been executed, regardless of the
1322 outcome.
1323
1324 The default implementation does nothing.
1325
1326
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001327 .. method:: startTestRun(test)
1328
1329 Called once before any tests are executed.
1330
Ezio Melotti8da105e2010-03-21 07:31:49 +00001331 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001332
1333
1334 .. method:: stopTestRun(test)
1335
1336 Called once before any tests are executed.
1337
Ezio Melotti8da105e2010-03-21 07:31:49 +00001338 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001339
1340
Benjamin Peterson52baa292009-03-24 00:56:30 +00001341 .. method:: addError(test, err)
1342
1343 Called when the test case *test* raises an unexpected exception *err* is a
1344 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1345 traceback)``.
1346
1347 The default implementation appends a tuple ``(test, formatted_err)`` to
1348 the instance's :attr:`errors` attribute, where *formatted_err* is a
1349 formatted traceback derived from *err*.
1350
1351
1352 .. method:: addFailure(test, err)
1353
1354 Called when the test case *test* signals a failure. *err* is a tuple of the form
1355 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1356
1357 The default implementation appends a tuple ``(test, formatted_err)`` to
1358 the instance's :attr:`failures` attribute, where *formatted_err* is a
1359 formatted traceback derived from *err*.
1360
1361
1362 .. method:: addSuccess(test)
1363
1364 Called when the test case *test* succeeds.
1365
1366 The default implementation does nothing.
1367
1368
1369 .. method:: addSkip(test, reason)
1370
1371 Called when the test case *test* is skipped. *reason* is the reason the
1372 test gave for skipping.
1373
1374 The default implementation appends a tuple ``(test, reason)`` to the
1375 instance's :attr:`skipped` attribute.
1376
1377
1378 .. method:: addExpectedFailure(test, err)
1379
1380 Called when the test case *test* fails, but was marked with the
1381 :func:`expectedFailure` decorator.
1382
1383 The default implementation appends a tuple ``(test, formatted_err)`` to
1384 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1385 is a formatted traceback derived from *err*.
1386
1387
1388 .. method:: addUnexpectedSuccess(test)
1389
1390 Called when the test case *test* was marked with the
1391 :func:`expectedFailure` decorator, but succeeded.
1392
1393 The default implementation appends the test to the instance's
1394 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001395
1396
1397.. data:: defaultTestLoader
1398
1399 Instance of the :class:`TestLoader` class intended to be shared. If no
1400 customization of the :class:`TestLoader` is needed, this instance can be used
1401 instead of repeatedly creating new instances.
1402
1403
Georg Brandlb044b2a2009-09-16 16:05:59 +00001404.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001405
1406 A basic test runner implementation which prints results on standard error. It
1407 has a few configurable parameters, but is essentially very simple. Graphical
1408 applications which run test suites should provide alternate implementations.
1409
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001410 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001411
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001412 This method returns the instance of ``TestResult`` used by :meth:`run`.
1413 It is not intended to be called directly, but can be overridden in
1414 subclasses to provide a custom ``TestResult``.
1415
1416
Georg Brandlb044b2a2009-09-16 16:05:59 +00001417.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=TextTestRunner, testLoader=unittest.defaultTestLoader, exit=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001418
1419 A command-line program that runs a set of tests; this is primarily for making
1420 test modules conveniently executable. The simplest use for this function is to
1421 include the following line at the end of a test script::
1422
1423 if __name__ == '__main__':
1424 unittest.main()
1425
1426 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001427 created instance of it. By default ``main`` calls :func:`sys.exit` with
1428 an exit code indicating success or failure of the tests run.
1429
1430 ``main`` supports being used from the interactive interpreter by passing in the
1431 argument ``exit=False``. This displays the result on standard output without
1432 calling :func:`sys.exit`::
1433
1434 >>> from unittest import main
1435 >>> main(module='test_module', exit=False)
1436
1437 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1438 This stores the result of the tests run as the ``result`` attribute.
1439
Georg Brandlc62efa82010-07-11 10:41:07 +00001440 .. versionchanged:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001441 The ``exit`` parameter was added.