blob: d88b8230b596f833923f8428b08febd6835ab9df [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`
146provides a command line interface to the test script. When run from the command
147line, 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
179.. _organizing-tests:
180
181Organizing test code
182--------------------
183
184The basic building blocks of unit testing are :dfn:`test cases` --- single
185scenarios that must be set up and checked for correctness. In :mod:`unittest`,
186test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
187class. To make your own test cases you must write subclasses of
188:class:`TestCase`, or use :class:`FunctionTestCase`.
189
190An instance of a :class:`TestCase`\ -derived class is an object that can
191completely run a single test method, together with optional set-up and tidy-up
192code.
193
194The testing code of a :class:`TestCase` instance should be entirely self
195contained, such that it can be run either in isolation or in arbitrary
196combination with any number of other test cases.
197
Benjamin Peterson52baa292009-03-24 00:56:30 +0000198The simplest :class:`TestCase` subclass will simply override the
199:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201 import unittest
202
203 class DefaultWidgetSizeTestCase(unittest.TestCase):
204 def runTest(self):
205 widget = Widget('The widget')
206 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
207
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000208Note that in order to test something, we use the one of the :meth:`assert\*`
209methods provided by the :class:`TestCase` base class. If the
Georg Brandl116aa622007-08-15 14:28:22 +0000210test fails, an exception will be raised, and :mod:`unittest` will identify the
211test case as a :dfn:`failure`. Any other exceptions will be treated as
212:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
213caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
214caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
215function call.
216
217The way to run a test case will be described later. For now, note that to
218construct an instance of such a test case, we call its constructor without
219arguments::
220
221 testCase = DefaultWidgetSizeTestCase()
222
223Now, such test cases can be numerous, and their set-up can be repetitive. In
224the above case, constructing a :class:`Widget` in each of 100 Widget test case
225subclasses would mean unsightly duplication.
226
227Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000228:meth:`~TestCase.setUp`, which the testing framework will automatically call for
229us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231 import unittest
232
233 class SimpleWidgetTestCase(unittest.TestCase):
234 def setUp(self):
235 self.widget = Widget('The widget')
236
237 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
238 def runTest(self):
Ezio Melottid5031802010-02-04 20:29:01 +0000239 self.assertEqual(self.widget.size(), (50,50),
240 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242 class WidgetResizeTestCase(SimpleWidgetTestCase):
243 def runTest(self):
244 self.widget.resize(100,150)
Ezio Melottid5031802010-02-04 20:29:01 +0000245 self.assertEqual(self.widget.size(), (100,150),
246 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Benjamin Peterson52baa292009-03-24 00:56:30 +0000248If the :meth:`~TestCase.setUp` method raises an exception while the test is
249running, the framework will consider the test to have suffered an error, and the
250:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Benjamin Peterson52baa292009-03-24 00:56:30 +0000252Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
253after the :meth:`~TestCase.runTest` method has been run::
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 def tearDown(self):
262 self.widget.dispose()
263 self.widget = None
264
Benjamin Peterson52baa292009-03-24 00:56:30 +0000265If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
266be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268Such a working environment for the testing code is called a :dfn:`fixture`.
269
270Often, many small test cases will use the same fixture. In this case, we would
271end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
272classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000273discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
274mechanism::
275
276 import unittest
277
278 class WidgetTestCase(unittest.TestCase):
279 def setUp(self):
280 self.widget = Widget('The widget')
281
282 def tearDown(self):
283 self.widget.dispose()
284 self.widget = None
285
Ezio Melottic08cae92010-02-28 03:48:50 +0000286 def test_default_size(self):
Ezio Melottid5031802010-02-04 20:29:01 +0000287 self.assertEqual(self.widget.size(), (50,50),
288 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000289
Ezio Melottic08cae92010-02-28 03:48:50 +0000290 def test_resize(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000291 self.widget.resize(100,150)
Ezio Melottid5031802010-02-04 20:29:01 +0000292 self.assertEqual(self.widget.size(), (100,150),
293 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000294
Benjamin Peterson52baa292009-03-24 00:56:30 +0000295Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
296provided two different test methods. Class instances will now each run one of
Ezio Melottic08cae92010-02-28 03:48:50 +0000297the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
Benjamin Peterson52baa292009-03-24 00:56:30 +0000298separately for each instance. When creating an instance we must specify the
299test method it is to run. We do this by passing the method name in the
300constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000301
Ezio Melottic08cae92010-02-28 03:48:50 +0000302 defaultSizeTestCase = WidgetTestCase('test_default_size')
303 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305Test case instances are grouped together according to the features they test.
306:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
307represented by :mod:`unittest`'s :class:`TestSuite` class::
308
309 widgetTestSuite = unittest.TestSuite()
Ezio Melottic08cae92010-02-28 03:48:50 +0000310 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
311 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000312
313For the ease of running tests, as we will see later, it is a good idea to
314provide in each test module a callable object that returns a pre-built test
315suite::
316
317 def suite():
318 suite = unittest.TestSuite()
Ezio Melottic08cae92010-02-28 03:48:50 +0000319 suite.addTest(WidgetTestCase('test_default_size'))
320 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000321 return suite
322
323or even::
324
325 def suite():
Ezio Melottic08cae92010-02-28 03:48:50 +0000326 tests = ['test_default_size', 'test_resize']
Georg Brandl116aa622007-08-15 14:28:22 +0000327
328 return unittest.TestSuite(map(WidgetTestCase, tests))
329
330Since it is a common pattern to create a :class:`TestCase` subclass with many
331similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
332class that can be used to automate the process of creating a test suite and
333populating it with individual tests. For example, ::
334
335 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
336
Ezio Melottic08cae92010-02-28 03:48:50 +0000337will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
338``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl116aa622007-08-15 14:28:22 +0000339name prefix to identify test methods automatically.
340
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000341Note that the order in which the various test cases will be run is
342determined by sorting the test function names with respect to the
343built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000344
345Often it is desirable to group suites of test cases together, so as to run tests
346for the whole system at once. This is easy, since :class:`TestSuite` instances
347can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
348added to a :class:`TestSuite`::
349
350 suite1 = module1.TheTestSuite()
351 suite2 = module2.TheTestSuite()
352 alltests = unittest.TestSuite([suite1, suite2])
353
354You can place the definitions of test cases and test suites in the same modules
355as the code they are to test (such as :file:`widget.py`), but there are several
356advantages to placing the test code in a separate module, such as
357:file:`test_widget.py`:
358
359* The test module can be run standalone from the command line.
360
361* The test code can more easily be separated from shipped code.
362
363* There is less temptation to change test code to fit the code it tests without
364 a good reason.
365
366* Test code should be modified much less frequently than the code it tests.
367
368* Tested code can be refactored more easily.
369
370* Tests for modules written in C must be in separate modules anyway, so why not
371 be consistent?
372
373* If the testing strategy changes, there is no need to change the source code.
374
375
376.. _legacy-unit-tests:
377
378Re-using old test code
379----------------------
380
381Some users will find that they have existing test code that they would like to
382run from :mod:`unittest`, without converting every old test function to a
383:class:`TestCase` subclass.
384
385For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
386This subclass of :class:`TestCase` can be used to wrap an existing test
387function. Set-up and tear-down functions can also be provided.
388
389Given the following test function::
390
391 def testSomething():
392 something = makeSomething()
393 assert something.name is not None
394 # ...
395
396one can create an equivalent test case instance as follows::
397
398 testcase = unittest.FunctionTestCase(testSomething)
399
400If there are additional set-up and tear-down methods that should be called as
401part of the test case's operation, they can also be provided like so::
402
403 testcase = unittest.FunctionTestCase(testSomething,
404 setUp=makeSomethingDB,
405 tearDown=deleteSomethingDB)
406
407To make migrating existing test suites easier, :mod:`unittest` supports tests
408raising :exc:`AssertionError` to indicate test failure. However, it is
409recommended that you use the explicit :meth:`TestCase.fail\*` and
410:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
411may treat :exc:`AssertionError` differently.
412
413.. note::
414
415 Even though :class:`FunctionTestCase` can be used to quickly convert an existing
416 test base over to a :mod:`unittest`\ -based system, this approach is not
417 recommended. Taking the time to set up proper :class:`TestCase` subclasses will
418 make future test refactorings infinitely easier.
419
Benjamin Peterson52baa292009-03-24 00:56:30 +0000420In some cases, the existing tests may have been written using the :mod:`doctest`
421module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
422automatically build :class:`unittest.TestSuite` instances from the existing
423:mod:`doctest`\ -based tests.
424
Georg Brandl116aa622007-08-15 14:28:22 +0000425
Benjamin Peterson5254c042009-03-23 22:25:03 +0000426.. _unittest-skipping:
427
428Skipping tests and expected failures
429------------------------------------
430
431Unittest supports skipping individual test methods and even whole classes of
432tests. In addition, it supports marking a test as a "expected failure," a test
433that is broken and will fail, but shouldn't be counted as a failure on a
434:class:`TestResult`.
435
436Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
437or one of its conditional variants.
438
439Basic skipping looks like this: ::
440
441 class MyTestCase(unittest.TestCase):
442
443 @unittest.skip("demonstrating skipping")
444 def test_nothing(self):
445 self.fail("shouldn't happen")
446
Benjamin Petersonded31c42009-03-30 15:04:16 +0000447 @unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version")
448 def test_format(self):
449 # Tests that work for only a certain version of the library.
450 pass
451
452 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
453 def test_windows_support(self):
454 # windows specific testing code
455 pass
456
Benjamin Peterson5254c042009-03-23 22:25:03 +0000457This is the output of running the example above in verbose mode: ::
458
Benjamin Petersonded31c42009-03-30 15:04:16 +0000459 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000460 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000461 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000462
463 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000464 Ran 3 tests in 0.005s
465
466 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000467
468Classes can be skipped just like methods: ::
469
470 @skip("showing class skipping")
471 class MySkippedTestCase(unittest.TestCase):
472 def test_not_run(self):
473 pass
474
Benjamin Peterson52baa292009-03-24 00:56:30 +0000475:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
476that needs to be set up is not available.
477
Benjamin Peterson5254c042009-03-23 22:25:03 +0000478Expected failures use the :func:`expectedFailure` decorator. ::
479
480 class ExpectedFailureTestCase(unittest.TestCase):
481 @unittest.expectedFailure
482 def test_fail(self):
483 self.assertEqual(1, 0, "broken")
484
485It's easy to roll your own skipping decorators by making a decorator that calls
486:func:`skip` on the test when it wants it to be skipped. This decorator skips
487the test unless the passed object has a certain attribute: ::
488
489 def skipUnlessHasattr(obj, attr):
490 if hasattr(obj, attr):
491 return lambda func: func
492 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
493
494The following decorators implement test skipping and expected failures:
495
496.. function:: skip(reason)
497
498 Unconditionally skip the decorated test. *reason* should describe why the
499 test is being skipped.
500
501.. function:: skipIf(condition, reason)
502
503 Skip the decorated test if *condition* is true.
504
505.. function:: skipUnless(condition, reason)
506
Georg Brandl4b054662010-10-06 08:56:53 +0000507 Skip the decorated test unless *condition* is true.
Benjamin Peterson5254c042009-03-23 22:25:03 +0000508
509.. function:: expectedFailure
510
511 Mark the test as an expected failure. If the test fails when run, the test
512 is not counted as a failure.
513
514
Georg Brandl116aa622007-08-15 14:28:22 +0000515.. _unittest-contents:
516
517Classes and functions
518---------------------
519
Benjamin Peterson52baa292009-03-24 00:56:30 +0000520This section describes in depth the API of :mod:`unittest`.
521
522
523.. _testcase-objects:
524
525Test cases
526~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000527
Georg Brandlb044b2a2009-09-16 16:05:59 +0000528.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000529
530 Instances of the :class:`TestCase` class represent the smallest testable units
531 in the :mod:`unittest` universe. This class is intended to be used as a base
532 class, with specific tests being implemented by concrete subclasses. This class
533 implements the interface needed by the test runner to allow it to drive the
534 test, and methods that the test code can use to check for and report various
535 kinds of failure.
536
537 Each instance of :class:`TestCase` will run a single test method: the method
538 named *methodName*. If you remember, we had an earlier example that went
539 something like this::
540
541 def suite():
542 suite = unittest.TestSuite()
Ezio Melottic08cae92010-02-28 03:48:50 +0000543 suite.addTest(WidgetTestCase('test_default_size'))
544 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl116aa622007-08-15 14:28:22 +0000545 return suite
546
547 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
548 single test.
549
Benjamin Peterson52baa292009-03-24 00:56:30 +0000550 *methodName* defaults to :meth:`runTest`.
551
552 :class:`TestCase` instances provide three groups of methods: one group used
553 to run the test, another used by the test implementation to check conditions
554 and report failures, and some inquiry methods allowing information about the
555 test itself to be gathered.
556
557 Methods in the first group (running the test) are:
558
559
560 .. method:: setUp()
561
562 Method called to prepare the test fixture. This is called immediately
563 before calling the test method; any exception raised by this method will
564 be considered an error rather than a test failure. The default
565 implementation does nothing.
566
567
568 .. method:: tearDown()
569
570 Method called immediately after the test method has been called and the
571 result recorded. This is called even if the test method raised an
572 exception, so the implementation in subclasses may need to be particularly
573 careful about checking internal state. Any exception raised by this
574 method will be considered an error rather than a test failure. This
575 method will only be called if the :meth:`setUp` succeeds, regardless of
576 the outcome of the test method. The default implementation does nothing.
577
578
Georg Brandlb044b2a2009-09-16 16:05:59 +0000579 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000580
581 Run the test, collecting the result into the test result object passed as
582 *result*. If *result* is omitted or :const:`None`, a temporary result
Georg Brandlbcc484e2009-08-13 11:51:54 +0000583 object is created (by calling the :meth:`defaultTestResult` method) and
584 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000585
586 The same effect may be had by simply calling the :class:`TestCase`
587 instance.
588
589
Benjamin Petersone549ead2009-03-28 21:42:05 +0000590 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000591
Stefan Krah671b0162010-05-19 16:11:36 +0000592 Calling this during a test method or :meth:`setUp` skips the current
Benjamin Peterson52baa292009-03-24 00:56:30 +0000593 test. See :ref:`unittest-skipping` for more information.
594
Ezio Melotti8d5c16a2010-04-20 09:36:13 +0000595 .. versionadded:: 3.1
596
Benjamin Peterson52baa292009-03-24 00:56:30 +0000597
598 .. method:: debug()
599
600 Run the test without collecting the result. This allows exceptions raised
601 by the test to be propagated to the caller, and can be used to support
602 running tests under a debugger.
603
604 The test code can use any of the following methods to check for and report
605 failures.
606
607
Georg Brandlb044b2a2009-09-16 16:05:59 +0000608 .. method:: assertTrue(expr, msg=None)
609 assert_(expr, msg=None)
610 failUnless(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000611
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000612 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson52baa292009-03-24 00:56:30 +0000613 will be *msg* if given, otherwise it will be :const:`None`.
614
Raymond Hettinger35a88362009-04-09 00:08:24 +0000615 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000616 :meth:`failUnless`.
617
Benjamin Peterson52baa292009-03-24 00:56:30 +0000618
Georg Brandlb044b2a2009-09-16 16:05:59 +0000619 .. method:: assertEqual(first, second, msg=None)
620 failUnlessEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000621
622 Test that *first* and *second* are equal. If the values do not compare
623 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000624 :const:`None`. Note that using :meth:`assertEqual` improves upon
625 doing the comparison as the first parameter to :meth:`assertTrue`: the
626 default value for *msg* include representations of both *first* and
627 *second*.
628
629 In addition, if *first* and *second* are the exact same type and one of
630 list, tuple, dict, set, or frozenset or any type that a subclass
631 registers :meth:`addTypeEqualityFunc` the type specific equality function
632 will be called in order to generate a more useful default error message.
633
Raymond Hettinger35a88362009-04-09 00:08:24 +0000634 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000635 Added the automatic calling of type specific equality function.
636
Raymond Hettinger35a88362009-04-09 00:08:24 +0000637 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000638 :meth:`failUnlessEqual`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000639
640
Georg Brandlb044b2a2009-09-16 16:05:59 +0000641 .. method:: assertNotEqual(first, second, msg=None)
642 failIfEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000643
644 Test that *first* and *second* are not equal. If the values do compare
645 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000646 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
647 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson52baa292009-03-24 00:56:30 +0000648 default value for *msg* can be computed to include representations of both
649 *first* and *second*.
650
Raymond Hettinger35a88362009-04-09 00:08:24 +0000651 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000652 :meth:`failIfEqual`.
653
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000654
Georg Brandlb044b2a2009-09-16 16:05:59 +0000655 .. method:: assertAlmostEqual(first, second, *, places=7, msg=None)
656 failUnlessAlmostEqual(first, second, *, places=7, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000657
658 Test that *first* and *second* are approximately equal by computing the
659 difference, rounding to the given number of decimal *places* (default 7),
660 and comparing to zero.
661
662 Note that comparing a given number of decimal places is not the same as
663 comparing a given number of significant digits. If the values do not
664 compare equal, the test will fail with the explanation given by *msg*, or
665 :const:`None`.
666
Raymond Hettinger35a88362009-04-09 00:08:24 +0000667 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000668 :meth:`failUnlessAlmostEqual`.
669
Benjamin Peterson52baa292009-03-24 00:56:30 +0000670
Georg Brandlb044b2a2009-09-16 16:05:59 +0000671 .. method:: assertNotAlmostEqual(first, second, *, places=7, msg=None)
672 failIfAlmostEqual(first, second, *, places=7, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000673
674 Test that *first* and *second* are not approximately equal by computing
675 the difference, rounding to the given number of decimal *places* (default
676 7), and comparing to zero.
677
678 Note that comparing a given number of decimal places is not the same as
679 comparing a given number of significant digits. If the values do not
680 compare equal, the test will fail with the explanation given by *msg*, or
681 :const:`None`.
682
Raymond Hettinger35a88362009-04-09 00:08:24 +0000683 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000684 :meth:`failIfAlmostEqual`.
685
686
687 .. method:: assertGreater(first, second, msg=None)
688 assertGreaterEqual(first, second, msg=None)
689 assertLess(first, second, msg=None)
690 assertLessEqual(first, second, msg=None)
691
692 Test that *first* is respectively >, >=, < or <= than *second* depending
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000693 on the method name. If not, the test will fail with an explanation
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000694 or with the explanation given by *msg*::
695
696 >>> self.assertGreaterEqual(3, 4)
697 AssertionError: "3" unexpectedly not greater than or equal to "4"
698
Raymond Hettinger35a88362009-04-09 00:08:24 +0000699 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000700
701
702 .. method:: assertMultiLineEqual(self, first, second, msg=None)
703
704 Test that the multiline string *first* is equal to the string *second*.
705 When not equal a diff of the two strings highlighting the differences
706 will be included in the error message.
707
708 If specified *msg* will be used as the error message on failure.
709
Raymond Hettinger35a88362009-04-09 00:08:24 +0000710 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000711
712
Georg Brandlb044b2a2009-09-16 16:05:59 +0000713 .. method:: assertRegexpMatches(text, regexp, msg=None):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000714
715 Verifies that a *regexp* search matches *text*. Fails with an error
716 message including the pattern and the *text*. *regexp* may be
717 a regular expression object or a string containing a regular expression
718 suitable for use by :func:`re.search`.
719
Raymond Hettinger35a88362009-04-09 00:08:24 +0000720 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000721
722
723 .. method:: assertIn(first, second, msg=None)
724 assertNotIn(first, second, msg=None)
725
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000726 Tests that *first* is or is not in *second* with an explanatory error
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000727 message as appropriate.
728
729 If specified *msg* will be used as the error message on failure.
730
Raymond Hettinger35a88362009-04-09 00:08:24 +0000731 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000732
733
Gregory P. Smith48a5ec42010-02-28 22:01:02 +0000734 .. method:: assertSameElements(actual, expected, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000735
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000736 Test that sequence *expected* contains the same elements as *actual*,
737 regardless of their order. When they don't, an error message listing
738 the differences between the sequences will be generated.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000739
Gregory P. Smith48a5ec42010-02-28 22:01:02 +0000740 Duplicate elements are ignored when comparing *actual* and *expected*.
741 It is the equivalent of ``assertEqual(set(expected), set(actual))``
742 but it works with sequences of unhashable objects as well.
743
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000744 If specified *msg* will be used as the error message on failure.
745
Raymond Hettinger35a88362009-04-09 00:08:24 +0000746 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000747
748
749 .. method:: assertSetEqual(set1, set2, msg=None)
750
751 Tests that two sets are equal. If not, an error message is constructed
752 that lists the differences between the sets.
753
754 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
755 method.
756
757 If specified *msg* will be used as the error message on failure.
758
Raymond Hettinger35a88362009-04-09 00:08:24 +0000759 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000760
761
762 .. method:: assertDictEqual(expected, actual, msg=None)
763
764 Test that two dictionaries are equal. If not, an error message is
765 constructed that shows the differences in the dictionaries.
766
767 If specified *msg* will be used as the error message on failure.
768
Raymond Hettinger35a88362009-04-09 00:08:24 +0000769 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000770
771
772 .. method:: assertDictContainsSubset(expected, actual, msg=None)
773
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000774 Tests whether the key/value pairs in dictionary *actual* are a
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000775 superset of those in *expected*. If not, an error message listing
776 the missing keys and mismatched values is generated.
777
778 If specified *msg* will be used as the error message on failure.
779
Raymond Hettinger35a88362009-04-09 00:08:24 +0000780 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000781
782
783 .. method:: assertListEqual(list1, list2, msg=None)
784 assertTupleEqual(tuple1, tuple2, msg=None)
785
786 Tests that two lists or tuples are equal. If not an error message is
787 constructed that shows only the differences between the two. An error
788 is also raised if either of the parameters are of the wrong type.
789
790 If specified *msg* will be used as the error message on failure.
791
Raymond Hettinger35a88362009-04-09 00:08:24 +0000792 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000793
794
795 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
796
797 Tests that two sequences are equal. If a *seq_type* is supplied, both
798 *seq1* and *seq2* must be instances of *seq_type* or a failure will
799 be raised. If the sequences are different an error message is
800 constructed that shows the difference between the two.
801
802 If specified *msg* will be used as the error message on failure.
803
804 This method is used to implement :meth:`assertListEqual` and
805 :meth:`assertTupleEqual`.
806
Raymond Hettinger35a88362009-04-09 00:08:24 +0000807 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000808
Benjamin Peterson52baa292009-03-24 00:56:30 +0000809
Georg Brandlb044b2a2009-09-16 16:05:59 +0000810 .. method:: assertRaises(exception, callable, *args, **kwds)
811 failUnlessRaises(exception, callable, *args, **kwds)
812 assertRaises(exception)
813 failUnlessRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000814
815 Test that an exception is raised when *callable* is called with any
816 positional or keyword arguments that are also passed to
817 :meth:`assertRaises`. The test passes if *exception* is raised, is an
818 error if another exception is raised, or fails if no exception is raised.
819 To catch any of a group of exceptions, a tuple containing the exception
820 classes may be passed as *exception*.
821
Georg Brandlb044b2a2009-09-16 16:05:59 +0000822 If only the *exception* argument is given, returns a context manager so
823 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000824
Ezio Melotti0f365732010-02-08 22:07:38 +0000825 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000826 do_something()
827
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000828 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000829 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000830
Raymond Hettinger35a88362009-04-09 00:08:24 +0000831 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000832 :meth:`failUnlessRaises`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000833
Benjamin Peterson52baa292009-03-24 00:56:30 +0000834
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000835 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
836
837 Like :meth:`assertRaises` but also tests that *regexp* matches
838 on the string representation of the raised exception. *regexp* may be
839 a regular expression object or a string containing a regular expression
840 suitable for use by :func:`re.search`. Examples::
841
842 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
843 int, 'XYZ')
844
845 or::
846
847 with self.assertRaisesRegexp(ValueError, 'literal'):
848 int('XYZ')
849
Raymond Hettinger35a88362009-04-09 00:08:24 +0000850 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000851
852
Georg Brandlb044b2a2009-09-16 16:05:59 +0000853 .. method:: assertIsNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000854
855 This signals a test failure if *expr* is not None.
856
Raymond Hettinger35a88362009-04-09 00:08:24 +0000857 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000858
859
Georg Brandlb044b2a2009-09-16 16:05:59 +0000860 .. method:: assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000861
862 The inverse of the :meth:`assertIsNone` method.
863 This signals a test failure if *expr* is None.
864
Raymond Hettinger35a88362009-04-09 00:08:24 +0000865 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000866
867
Georg Brandlb044b2a2009-09-16 16:05:59 +0000868 .. method:: assertIs(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000869
870 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
871 object.
872
Georg Brandl705d9d52009-05-05 09:29:50 +0000873 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000874
875
Georg Brandlb044b2a2009-09-16 16:05:59 +0000876 .. method:: assertIsNot(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000877
878 The inverse of the :meth:`assertIs` method.
879 This signals a test failure if *expr1* and *expr2* evaluate to the same
880 object.
881
Georg Brandl705d9d52009-05-05 09:29:50 +0000882 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000883
884
Georg Brandlb044b2a2009-09-16 16:05:59 +0000885 .. method:: assertFalse(expr, msg=None)
886 failIf(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000887
888 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000889 This signals a test failure if *expr* is true, with *msg* or :const:`None`
890 for the error message.
891
Raymond Hettinger35a88362009-04-09 00:08:24 +0000892 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000893 :meth:`failIf`.
894
Benjamin Peterson52baa292009-03-24 00:56:30 +0000895
Georg Brandlb044b2a2009-09-16 16:05:59 +0000896 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000897
898 Signals a test failure unconditionally, with *msg* or :const:`None` for
899 the error message.
900
901
902 .. attribute:: failureException
903
904 This class attribute gives the exception raised by the test method. If a
905 test framework needs to use a specialized exception, possibly to carry
906 additional information, it must subclass this exception in order to "play
907 fair" with the framework. The initial value of this attribute is
908 :exc:`AssertionError`.
909
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000910
911 .. attribute:: longMessage
912
913 If set to True then any explicit failure message you pass in to the
914 assert methods will be appended to the end of the normal failure message.
915 The normal messages contain useful information about the objects involved,
916 for example the message from assertEqual shows you the repr of the two
917 unequal objects. Setting this attribute to True allows you to have a
918 custom error message in addition to the normal one.
919
920 This attribute defaults to False, meaning that a custom message passed
921 to an assert method will silence the normal message.
922
923 The class setting can be overridden in individual tests by assigning an
924 instance attribute to True or False before calling the assert methods.
925
Raymond Hettinger35a88362009-04-09 00:08:24 +0000926 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000927
928
Benjamin Peterson52baa292009-03-24 00:56:30 +0000929 Testing frameworks can use the following methods to collect information on
930 the test:
931
932
933 .. method:: countTestCases()
934
935 Return the number of tests represented by this test object. For
936 :class:`TestCase` instances, this will always be ``1``.
937
938
939 .. method:: defaultTestResult()
940
941 Return an instance of the test result class that should be used for this
942 test case class (if no other result instance is provided to the
943 :meth:`run` method).
944
945 For :class:`TestCase` instances, this will always be an instance of
946 :class:`TestResult`; subclasses of :class:`TestCase` should override this
947 as necessary.
948
949
950 .. method:: id()
951
952 Return a string identifying the specific test case. This is usually the
953 full name of the test method, including the module and class name.
954
955
956 .. method:: shortDescription()
957
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000958 Returns a description of the test, or :const:`None` if no description
959 has been provided. The default implementation of this method
960 returns the first line of the test method's docstring, if available,
961 along with the method name.
962
Raymond Hettinger35a88362009-04-09 00:08:24 +0000963 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000964 In earlier versions this only returned the first line of the test
965 method's docstring, if available or the :const:`None`. That led to
966 undesirable behavior of not printing the test name when someone was
967 thoughtful enough to write a docstring.
968
969
970 .. method:: addTypeEqualityFunc(typeobj, function)
971
972 Registers a type specific :meth:`assertEqual` equality checking
973 function to be called by :meth:`assertEqual` when both objects it has
974 been asked to compare are exactly *typeobj* (not subclasses).
975 *function* must take two positional arguments and a third msg=None
976 keyword argument just as :meth:`assertEqual` does. It must raise
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000977 ``self.failureException`` when inequality between the first two
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000978 parameters is detected.
979
980 One good use of custom equality checking functions for a type
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000981 is to raise ``self.failureException`` with an error message useful
982 for debugging the problem by explaining the inequalities in detail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000983
Raymond Hettinger35a88362009-04-09 00:08:24 +0000984 .. versionadded:: 3.1
Georg Brandl116aa622007-08-15 14:28:22 +0000985
986
Georg Brandlb044b2a2009-09-16 16:05:59 +0000987 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000988
989 Add a function to be called after :meth:`tearDown` to cleanup resources
990 used during the test. Functions will be called in reverse order to the
991 order they are added (LIFO). They are called with any arguments and
992 keyword arguments passed into :meth:`addCleanup` when they are
993 added.
994
995 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
996 then any cleanup functions added will still be called.
997
Ezio Melotti8da105e2010-03-21 07:31:49 +0000998 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000999
1000
1001 .. method:: doCleanups()
1002
Barry Warsaw14e0a432010-04-12 14:55:03 +00001003 This method is called unconditionally after :meth:`tearDown`, or
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001004 after :meth:`setUp` if :meth:`setUp` raises an exception.
1005
1006 It is responsible for calling all the cleanup functions added by
1007 :meth:`addCleanup`. If you need cleanup functions to be called
1008 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1009 yourself.
1010
1011 :meth:`doCleanups` pops methods off the stack of cleanup
1012 functions one at a time, so it can be called at any time.
1013
Ezio Melotti8da105e2010-03-21 07:31:49 +00001014 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001015
1016
Georg Brandlb044b2a2009-09-16 16:05:59 +00001017.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001018
1019 This class implements the portion of the :class:`TestCase` interface which
1020 allows the test runner to drive the test, but does not provide the methods which
1021 test code can use to check and report errors. This is used to create test cases
1022 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
1023 -based test framework.
1024
1025
Benjamin Peterson52baa292009-03-24 00:56:30 +00001026.. _testsuite-objects:
1027
Benjamin Peterson52baa292009-03-24 00:56:30 +00001028Grouping tests
1029~~~~~~~~~~~~~~
1030
Georg Brandlb044b2a2009-09-16 16:05:59 +00001031.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001032
1033 This class represents an aggregation of individual tests cases and test suites.
1034 The class presents the interface needed by the test runner to allow it to be run
1035 as any other test case. Running a :class:`TestSuite` instance is the same as
1036 iterating over the suite, running each test individually.
1037
1038 If *tests* is given, it must be an iterable of individual test cases or other
1039 test suites that will be used to build the suite initially. Additional methods
1040 are provided to add test cases and suites to the collection later on.
1041
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001042 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1043 they do not actually implement a test. Instead, they are used to aggregate
1044 tests into groups of tests that should be run together. Some additional
1045 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001046
1047
1048 .. method:: TestSuite.addTest(test)
1049
1050 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1051
1052
1053 .. method:: TestSuite.addTests(tests)
1054
1055 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1056 instances to this test suite.
1057
1058 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
1059 element.
1060
1061 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1062
1063
1064 .. method:: run(result)
1065
1066 Run the tests associated with this suite, collecting the result into the
1067 test result object passed as *result*. Note that unlike
1068 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1069 be passed in.
1070
1071
1072 .. method:: debug()
1073
1074 Run the tests associated with this suite without collecting the
1075 result. This allows exceptions raised by the test to be propagated to the
1076 caller and can be used to support running tests under a debugger.
1077
1078
1079 .. method:: countTestCases()
1080
1081 Return the number of tests represented by this test object, including all
1082 individual tests and sub-suites.
1083
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001084
1085 .. method:: __iter__()
1086
1087 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1088 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1089 that this method maybe called several times on a single suite
1090 (for example when counting tests or comparing for equality)
1091 so the tests returned must be the same for repeated iterations.
1092
Ezio Melotti8da105e2010-03-21 07:31:49 +00001093 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001094 In earlier versions the :class:`TestSuite` accessed tests directly rather
1095 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1096 for providing tests.
1097
Benjamin Peterson52baa292009-03-24 00:56:30 +00001098 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1099 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1100
1101
Benjamin Peterson52baa292009-03-24 00:56:30 +00001102Loading and running tests
1103~~~~~~~~~~~~~~~~~~~~~~~~~
1104
Georg Brandl116aa622007-08-15 14:28:22 +00001105.. class:: TestLoader()
1106
Benjamin Peterson52baa292009-03-24 00:56:30 +00001107 The :class:`TestLoader` class is used to create test suites from classes and
1108 modules. Normally, there is no need to create an instance of this class; the
1109 :mod:`unittest` module provides an instance that can be shared as
1110 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1111 customization of some configurable properties.
1112
1113 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001114
1115
Benjamin Peterson52baa292009-03-24 00:56:30 +00001116 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001117
Benjamin Peterson52baa292009-03-24 00:56:30 +00001118 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1119 :class:`testCaseClass`.
1120
1121
1122 .. method:: loadTestsFromModule(module)
1123
1124 Return a suite of all tests cases contained in the given module. This
1125 method searches *module* for classes derived from :class:`TestCase` and
1126 creates an instance of the class for each test method defined for the
1127 class.
1128
Georg Brandle720c0a2009-04-27 16:20:50 +00001129 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001130
1131 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1132 convenient in sharing fixtures and helper functions, defining test
1133 methods on base classes that are not intended to be instantiated
1134 directly does not play well with this method. Doing so, however, can
1135 be useful when the fixtures are different and defined in subclasses.
1136
1137
Georg Brandlb044b2a2009-09-16 16:05:59 +00001138 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001139
1140 Return a suite of all tests cases given a string specifier.
1141
1142 The specifier *name* is a "dotted name" that may resolve either to a
1143 module, a test case class, a test method within a test case class, a
1144 :class:`TestSuite` instance, or a callable object which returns a
1145 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1146 applied in the order listed here; that is, a method on a possible test
1147 case class will be picked up as "a test method within a test case class",
1148 rather than "a callable object".
1149
1150 For example, if you have a module :mod:`SampleTests` containing a
1151 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1152 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1153 specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
1154 suite which will run all three test methods. Using the specifier
1155 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
1156 which will run only the :meth:`test_two` test method. The specifier can refer
1157 to modules and packages which have not been imported; they will be imported as a
1158 side-effect.
1159
1160 The method optionally resolves *name* relative to the given *module*.
1161
1162
Georg Brandlb044b2a2009-09-16 16:05:59 +00001163 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001164
1165 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1166 than a single name. The return value is a test suite which supports all
1167 the tests defined for each name.
1168
1169
1170 .. method:: getTestCaseNames(testCaseClass)
1171
1172 Return a sorted sequence of method names found within *testCaseClass*;
1173 this should be a subclass of :class:`TestCase`.
1174
1175 The following attributes of a :class:`TestLoader` can be configured either by
1176 subclassing or assignment on an instance:
1177
1178
1179 .. attribute:: testMethodPrefix
1180
1181 String giving the prefix of method names which will be interpreted as test
1182 methods. The default value is ``'test'``.
1183
1184 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1185 methods.
1186
1187
1188 .. attribute:: sortTestMethodsUsing
1189
1190 Function to be used to compare method names when sorting them in
1191 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1192
1193
1194 .. attribute:: suiteClass
1195
1196 Callable object that constructs a test suite from a list of tests. No
1197 methods on the resulting object are needed. The default value is the
1198 :class:`TestSuite` class.
1199
1200 This affects all the :meth:`loadTestsFrom\*` methods.
1201
1202
Benjamin Peterson52baa292009-03-24 00:56:30 +00001203.. class:: TestResult
1204
1205 This class is used to compile information about which tests have succeeded
1206 and which have failed.
1207
1208 A :class:`TestResult` object stores the results of a set of tests. The
1209 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1210 properly recorded; test authors do not need to worry about recording the
1211 outcome of tests.
1212
1213 Testing frameworks built on top of :mod:`unittest` may want access to the
1214 :class:`TestResult` object generated by running a set of tests for reporting
1215 purposes; a :class:`TestResult` instance is returned by the
1216 :meth:`TestRunner.run` method for this purpose.
1217
1218 :class:`TestResult` instances have the following attributes that will be of
1219 interest when inspecting the results of running a set of tests:
1220
1221
1222 .. attribute:: errors
1223
1224 A list containing 2-tuples of :class:`TestCase` instances and strings
1225 holding formatted tracebacks. Each tuple represents a test which raised an
1226 unexpected exception.
1227
Benjamin Peterson52baa292009-03-24 00:56:30 +00001228 .. attribute:: failures
1229
1230 A list containing 2-tuples of :class:`TestCase` instances and strings
1231 holding formatted tracebacks. Each tuple represents a test where a failure
1232 was explicitly signalled using the :meth:`TestCase.fail\*` or
1233 :meth:`TestCase.assert\*` methods.
1234
Benjamin Peterson52baa292009-03-24 00:56:30 +00001235 .. attribute:: skipped
1236
1237 A list containing 2-tuples of :class:`TestCase` instances and strings
1238 holding the reason for skipping the test.
1239
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001240 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001241
1242 .. attribute:: expectedFailures
1243
Georg Brandl4b054662010-10-06 08:56:53 +00001244 A list containing 2-tuples of :class:`TestCase` instances and strings
1245 holding formatted tracebacks. Each tuple represents an expected failure
Benjamin Peterson52baa292009-03-24 00:56:30 +00001246 of the test case.
1247
1248 .. attribute:: unexpectedSuccesses
1249
1250 A list containing :class:`TestCase` instances that were marked as expected
1251 failures, but succeeded.
1252
1253 .. attribute:: shouldStop
1254
1255 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1256
1257
1258 .. attribute:: testsRun
1259
1260 The total number of tests run so far.
1261
1262
1263 .. method:: wasSuccessful()
1264
1265 Return :const:`True` if all tests run so far have passed, otherwise returns
1266 :const:`False`.
1267
1268
1269 .. method:: stop()
1270
1271 This method can be called to signal that the set of tests being run should
1272 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1273 :class:`TestRunner` objects should respect this flag and return without
1274 running any additional tests.
1275
1276 For example, this feature is used by the :class:`TextTestRunner` class to
1277 stop the test framework when the user signals an interrupt from the
1278 keyboard. Interactive tools which provide :class:`TestRunner`
1279 implementations can use this in a similar manner.
1280
1281 The following methods of the :class:`TestResult` class are used to maintain
1282 the internal data structures, and may be extended in subclasses to support
1283 additional reporting requirements. This is particularly useful in building
1284 tools which support interactive reporting while tests are being run.
1285
1286
1287 .. method:: startTest(test)
1288
1289 Called when the test case *test* is about to be run.
1290
1291 The default implementation simply increments the instance's :attr:`testsRun`
1292 counter.
1293
1294
1295 .. method:: stopTest(test)
1296
1297 Called after the test case *test* has been executed, regardless of the
1298 outcome.
1299
1300 The default implementation does nothing.
1301
1302
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001303 .. method:: startTestRun(test)
1304
1305 Called once before any tests are executed.
1306
Ezio Melotti8da105e2010-03-21 07:31:49 +00001307 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001308
1309
1310 .. method:: stopTestRun(test)
1311
1312 Called once before any tests are executed.
1313
Ezio Melotti8da105e2010-03-21 07:31:49 +00001314 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001315
1316
Benjamin Peterson52baa292009-03-24 00:56:30 +00001317 .. method:: addError(test, err)
1318
1319 Called when the test case *test* raises an unexpected exception *err* is a
1320 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1321 traceback)``.
1322
1323 The default implementation appends a tuple ``(test, formatted_err)`` to
1324 the instance's :attr:`errors` attribute, where *formatted_err* is a
1325 formatted traceback derived from *err*.
1326
1327
1328 .. method:: addFailure(test, err)
1329
1330 Called when the test case *test* signals a failure. *err* is a tuple of the form
1331 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1332
1333 The default implementation appends a tuple ``(test, formatted_err)`` to
1334 the instance's :attr:`failures` attribute, where *formatted_err* is a
1335 formatted traceback derived from *err*.
1336
1337
1338 .. method:: addSuccess(test)
1339
1340 Called when the test case *test* succeeds.
1341
1342 The default implementation does nothing.
1343
1344
1345 .. method:: addSkip(test, reason)
1346
1347 Called when the test case *test* is skipped. *reason* is the reason the
1348 test gave for skipping.
1349
1350 The default implementation appends a tuple ``(test, reason)`` to the
1351 instance's :attr:`skipped` attribute.
1352
1353
1354 .. method:: addExpectedFailure(test, err)
1355
1356 Called when the test case *test* fails, but was marked with the
1357 :func:`expectedFailure` decorator.
1358
1359 The default implementation appends a tuple ``(test, formatted_err)`` to
1360 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1361 is a formatted traceback derived from *err*.
1362
1363
1364 .. method:: addUnexpectedSuccess(test)
1365
1366 Called when the test case *test* was marked with the
1367 :func:`expectedFailure` decorator, but succeeded.
1368
1369 The default implementation appends the test to the instance's
1370 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001371
1372
1373.. data:: defaultTestLoader
1374
1375 Instance of the :class:`TestLoader` class intended to be shared. If no
1376 customization of the :class:`TestLoader` is needed, this instance can be used
1377 instead of repeatedly creating new instances.
1378
1379
Georg Brandlb044b2a2009-09-16 16:05:59 +00001380.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001381
1382 A basic test runner implementation which prints results on standard error. It
1383 has a few configurable parameters, but is essentially very simple. Graphical
1384 applications which run test suites should provide alternate implementations.
1385
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001386 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001387
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001388 This method returns the instance of ``TestResult`` used by :meth:`run`.
1389 It is not intended to be called directly, but can be overridden in
1390 subclasses to provide a custom ``TestResult``.
1391
1392
Georg Brandlb044b2a2009-09-16 16:05:59 +00001393.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=TextTestRunner, testLoader=unittest.defaultTestLoader, exit=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001394
1395 A command-line program that runs a set of tests; this is primarily for making
1396 test modules conveniently executable. The simplest use for this function is to
1397 include the following line at the end of a test script::
1398
1399 if __name__ == '__main__':
1400 unittest.main()
1401
1402 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001403 created instance of it. By default ``main`` calls :func:`sys.exit` with
1404 an exit code indicating success or failure of the tests run.
1405
1406 ``main`` supports being used from the interactive interpreter by passing in the
1407 argument ``exit=False``. This displays the result on standard output without
1408 calling :func:`sys.exit`::
1409
1410 >>> from unittest import main
1411 >>> main(module='test_module', exit=False)
1412
1413 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1414 This stores the result of the tests run as the ``result`` attribute.
1415
Georg Brandlc62efa82010-07-11 10:41:07 +00001416 .. versionchanged:: 3.1
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001417 The ``exit`` parameter was added.