blob: aed03951912ce5f4a1c8ff0ea6b6a3c207aeb77c [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`unittest` --- Unit testing framework
2==========================================
3
4.. module:: unittest
5 :synopsis: Unit testing framework for Python.
6.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
7.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9.. sectionauthor:: Raymond Hettinger <python@rcn.com>
10
11
12.. versionadded:: 2.1
Benjamin Peterson692428e2009-03-23 21:50:21 +000013
Benjamin Peterson99721e02009-03-23 23:10:14 +000014.. versionchanged:: 2.7
15 Added test :ref:`skipping and expected failures <unittest-skipping>`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000016
17The Python unit testing framework, sometimes referred to as "PyUnit," is a
18Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
19turn, a Java version of Kent's Smalltalk testing framework. Each is the de
20facto standard unit testing framework for its respective language.
21
22:mod:`unittest` supports test automation, sharing of setup and shutdown code for
23tests, aggregation of tests into collections, and independence of the tests from
24the reporting framework. The :mod:`unittest` module provides classes that make
25it easy to support these qualities for a set of tests.
26
27To achieve this, :mod:`unittest` supports some important concepts:
28
29test fixture
30 A :dfn:`test fixture` represents the preparation needed to perform one or more
31 tests, and any associate cleanup actions. This may involve, for example,
32 creating temporary or proxy databases, directories, or starting a server
33 process.
34
35test case
36 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
37 response to a particular set of inputs. :mod:`unittest` provides a base class,
38 :class:`TestCase`, which may be used to create new test cases.
39
40test suite
41 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
42 used to aggregate tests that should be executed together.
43
44test runner
45 A :dfn:`test runner` is a component which orchestrates the execution of tests
46 and provides the outcome to the user. The runner may use a graphical interface,
47 a textual interface, or return a special value to indicate the results of
48 executing the tests.
49
50The test case and test fixture concepts are supported through the
51:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
52used when creating new tests, and the latter can be used when integrating
53existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson99721e02009-03-23 23:10:14 +000054fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
55:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
56and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
57can be passed to the constructor for these purposes. When the test is run, the
58fixture initialization is run first; if it succeeds, the cleanup method is run
59after the test has been executed, regardless of the outcome of the test. Each
60instance of the :class:`TestCase` will only be used to run a single test method,
61so a new fixture is created for each test.
Georg Brandl8ec7f652007-08-15 14:28:01 +000062
63Test suites are implemented by the :class:`TestSuite` class. This class allows
64individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson176a56c2009-05-25 00:48:58 +000065all tests added directly to the suite and in "child" test suites are run.
Georg Brandl8ec7f652007-08-15 14:28:01 +000066
Benjamin Peterson99721e02009-03-23 23:10:14 +000067A test runner is an object that provides a single method,
68:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
69object as a parameter, and returns a result object. The class
70:class:`TestResult` is provided for use as the result object. :mod:`unittest`
71provides the :class:`TextTestRunner` as an example test runner which reports
72test results on the standard error stream by default. Alternate runners can be
73implemented for other environments (such as graphical environments) without any
74need to derive from a specific class.
Georg Brandl8ec7f652007-08-15 14:28:01 +000075
76
77.. seealso::
78
79 Module :mod:`doctest`
80 Another test-support module with a very different flavor.
81
Georg Brandl2fcd1732009-05-30 10:45:40 +000082 `Simple Smalltalk Testing: With Patterns
83 <http://www.XProgramming.com/testfram.htm>`_
84 Kent Beck's original paper on testing frameworks using the pattern shared
85 by :mod:`unittest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000086
Georg Brandl2fcd1732009-05-30 10:45:40 +000087 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test
88 <http://pytest.org>`_
89 Third-party unittest frameworks with a lighter-weight syntax for writing
90 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger21b617b2009-03-24 00:17:11 +000091
Georg Brandl2fcd1732009-05-30 10:45:40 +000092 `python-mock <http://python-mock.sourceforge.net/>`_ and
93 `minimock <http://blog.ianbicking.org/minimock.html>`_
94 Tools for creating mock test objects (objects simulating external
95 resources).
Georg Brandl8ec7f652007-08-15 14:28:01 +000096
Michael Foordb4a81c82009-05-29 20:33:46 +000097
Michael Foordb4a81c82009-05-29 20:33:46 +000098
Michael Foord5d31e052009-05-11 17:59:43 +000099
Georg Brandl8ec7f652007-08-15 14:28:01 +0000100.. _unittest-minimal-example:
101
102Basic example
103-------------
104
105The :mod:`unittest` module provides a rich set of tools for constructing and
106running tests. This section demonstrates that a small subset of the tools
107suffice to meet the needs of most users.
108
109Here is a short script to test three functions from the :mod:`random` module::
110
111 import random
112 import unittest
113
114 class TestSequenceFunctions(unittest.TestCase):
115
116 def setUp(self):
117 self.seq = range(10)
118
Benjamin Peterson99721e02009-03-23 23:10:14 +0000119 def test_shuffle(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000120 # make sure the shuffled sequence does not lose any elements
121 random.shuffle(self.seq)
122 self.seq.sort()
123 self.assertEqual(self.seq, range(10))
124
Benjamin Peterson99721e02009-03-23 23:10:14 +0000125 def test_choice(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000126 element = random.choice(self.seq)
127 self.assert_(element in self.seq)
128
Benjamin Peterson99721e02009-03-23 23:10:14 +0000129 def test_sample(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000130 self.assertRaises(ValueError, random.sample, self.seq, 20)
131 for element in random.sample(self.seq, 5):
132 self.assert_(element in self.seq)
133
134 if __name__ == '__main__':
135 unittest.main()
136
Benjamin Peterson99721e02009-03-23 23:10:14 +0000137A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl8ec7f652007-08-15 14:28:01 +0000138individual tests are defined with methods whose names start with the letters
139``test``. This naming convention informs the test runner about which methods
140represent tests.
141
Benjamin Peterson99721e02009-03-23 23:10:14 +0000142The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
143expected result; :meth:`~TestCase.assert_` to verify a condition; or
144:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
145These methods are used instead of the :keyword:`assert` statement so the test
146runner can accumulate all test results and produce a report.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000147
Benjamin Peterson99721e02009-03-23 23:10:14 +0000148When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
149method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
150defined, the test runner will invoke that method after each test. In the
151example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
152test.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000153
154The final block shows a simple way to run the tests. :func:`unittest.main`
155provides a command line interface to the test script. When run from the command
156line, the above script produces an output that looks like this::
157
158 ...
159 ----------------------------------------------------------------------
160 Ran 3 tests in 0.000s
161
162 OK
163
164Instead of :func:`unittest.main`, there are other ways to run the tests with a
165finer level of control, less terse output, and no requirement to be run from the
166command line. For example, the last two lines may be replaced with::
167
168 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
169 unittest.TextTestRunner(verbosity=2).run(suite)
170
171Running the revised script from the interpreter or another script produces the
172following output::
173
174 testchoice (__main__.TestSequenceFunctions) ... ok
175 testsample (__main__.TestSequenceFunctions) ... ok
176 testshuffle (__main__.TestSequenceFunctions) ... ok
177
178 ----------------------------------------------------------------------
179 Ran 3 tests in 0.110s
180
181 OK
182
183The above examples show the most commonly used :mod:`unittest` features which
184are sufficient to meet many everyday testing needs. The remainder of the
185documentation explores the full feature set from first principles.
186
Raymond Hettingerb09f1982009-05-29 21:20:41 +0000187
188.. _unittest-command-line-interface:
189
190Command Line Interface
191----------------------
192
193The unittest module can be used from the command line to run tests from
194modules, classes or even individual test methods::
195
196 python -m unittest test_module1 test_module2
197 python -m unittest test_module.TestClass
198 python -m unittest test_module.TestClass.test_method
199
200You can pass in a list with any combination of module names, and fully
201qualified class or method names.
202
203You can run tests with more detail (higher verbosity) by passing in the -v flag::
204
205 python-m unittest -v test_module
206
207For a list of all the command line options::
208
209 python -m unittest -h
210
211.. versionchanged:: 2.7
212 In earlier versions it was only possible to run individual test methods and
213 not modules or classes.
214
215The command line can also be used for test discovery, for running all of the
216tests in a project or just a subset.
217
218
219.. _unittest-test-discovery:
220
221Test Discovery
222--------------
223
224.. versionadded:: 2.7
225
226Unittest supports simple test discovery. For a project's tests to be
227compatible with test discovery they must all be importable from the top level
228directory of the project (in other words, they must all be in Python packages).
229
230Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
231used from the command line. The basic command line usage is::
232
233 cd project_directory
234 python -m unittest discover
235
236The ``discover`` sub-command has the following options:
237
238 -v, --verbose Verbose output
239 -s directory Directory to start discovery ('.' default)
240 -p pattern Pattern to match test files ('test*.py' default)
241 -t directory Top level directory of project (default to
242 start directory)
243
244The -s, -p, & -t options can be passsed in as positional arguments. The
245following two command lines are equivalent::
246
247 python -m unittest -s project_directory -p '*_test.py'
248 python -m unittest project_directory '*_test.py'
249
250Test modules and packages can customize test loading and discovery by through
251the `load_tests protocol`_.
252
253
Georg Brandl8ec7f652007-08-15 14:28:01 +0000254.. _organizing-tests:
255
256Organizing test code
257--------------------
258
259The basic building blocks of unit testing are :dfn:`test cases` --- single
260scenarios that must be set up and checked for correctness. In :mod:`unittest`,
261test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
262class. To make your own test cases you must write subclasses of
263:class:`TestCase`, or use :class:`FunctionTestCase`.
264
265An instance of a :class:`TestCase`\ -derived class is an object that can
266completely run a single test method, together with optional set-up and tidy-up
267code.
268
269The testing code of a :class:`TestCase` instance should be entirely self
270contained, such that it can be run either in isolation or in arbitrary
271combination with any number of other test cases.
272
Benjamin Peterson99721e02009-03-23 23:10:14 +0000273The simplest :class:`TestCase` subclass will simply override the
274:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000275
276 import unittest
277
278 class DefaultWidgetSizeTestCase(unittest.TestCase):
279 def runTest(self):
280 widget = Widget('The widget')
281 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
282
Gregory P. Smith28399852009-03-31 16:54:10 +0000283Note that in order to test something, we use the one of the :meth:`assert\*`
Georg Brandl2fcd1732009-05-30 10:45:40 +0000284methods provided by the :class:`TestCase` base class. If the test fails, an
285exception will be raised, and :mod:`unittest` will identify the test case as a
286:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
287helps you identify where the problem is: :dfn:`failures` are caused by incorrect
288results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
289code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000290
291The way to run a test case will be described later. For now, note that to
292construct an instance of such a test case, we call its constructor without
293arguments::
294
295 testCase = DefaultWidgetSizeTestCase()
296
297Now, such test cases can be numerous, and their set-up can be repetitive. In
298the above case, constructing a :class:`Widget` in each of 100 Widget test case
299subclasses would mean unsightly duplication.
300
301Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson99721e02009-03-23 23:10:14 +0000302:meth:`~TestCase.setUp`, which the testing framework will automatically call for
303us when we run the test::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000304
305 import unittest
306
307 class SimpleWidgetTestCase(unittest.TestCase):
308 def setUp(self):
309 self.widget = Widget('The widget')
310
311 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
312 def runTest(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000313 self.assertTrue(self.widget.size() == (50,50),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000314 'incorrect default size')
315
316 class WidgetResizeTestCase(SimpleWidgetTestCase):
317 def runTest(self):
318 self.widget.resize(100,150)
Gregory P. Smith28399852009-03-31 16:54:10 +0000319 self.assertTrue(self.widget.size() == (100,150),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000320 'wrong size after resize')
321
Benjamin Peterson99721e02009-03-23 23:10:14 +0000322If the :meth:`~TestCase.setUp` method raises an exception while the test is
323running, the framework will consider the test to have suffered an error, and the
324:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000325
Benjamin Peterson99721e02009-03-23 23:10:14 +0000326Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
327after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000328
329 import unittest
330
331 class SimpleWidgetTestCase(unittest.TestCase):
332 def setUp(self):
333 self.widget = Widget('The widget')
334
335 def tearDown(self):
336 self.widget.dispose()
337 self.widget = None
338
Benjamin Peterson99721e02009-03-23 23:10:14 +0000339If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
340be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341
342Such a working environment for the testing code is called a :dfn:`fixture`.
343
344Often, many small test cases will use the same fixture. In this case, we would
345end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
346classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000347discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
348mechanism::
349
350 import unittest
351
352 class WidgetTestCase(unittest.TestCase):
353 def setUp(self):
354 self.widget = Widget('The widget')
355
356 def tearDown(self):
357 self.widget.dispose()
358 self.widget = None
359
360 def testDefaultSize(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000361 self.assertTrue(self.widget.size() == (50,50),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000362 'incorrect default size')
363
364 def testResize(self):
365 self.widget.resize(100,150)
Gregory P. Smith28399852009-03-31 16:54:10 +0000366 self.assertTrue(self.widget.size() == (100,150),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000367 'wrong size after resize')
368
Benjamin Peterson99721e02009-03-23 23:10:14 +0000369Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
370provided two different test methods. Class instances will now each run one of
371the :meth:`test\*` methods, with ``self.widget`` created and destroyed
372separately for each instance. When creating an instance we must specify the
373test method it is to run. We do this by passing the method name in the
374constructor::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000375
376 defaultSizeTestCase = WidgetTestCase('testDefaultSize')
377 resizeTestCase = WidgetTestCase('testResize')
378
379Test case instances are grouped together according to the features they test.
380:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
381represented by :mod:`unittest`'s :class:`TestSuite` class::
382
383 widgetTestSuite = unittest.TestSuite()
384 widgetTestSuite.addTest(WidgetTestCase('testDefaultSize'))
385 widgetTestSuite.addTest(WidgetTestCase('testResize'))
386
387For the ease of running tests, as we will see later, it is a good idea to
388provide in each test module a callable object that returns a pre-built test
389suite::
390
391 def suite():
392 suite = unittest.TestSuite()
393 suite.addTest(WidgetTestCase('testDefaultSize'))
394 suite.addTest(WidgetTestCase('testResize'))
395 return suite
396
397or even::
398
399 def suite():
400 tests = ['testDefaultSize', 'testResize']
401
402 return unittest.TestSuite(map(WidgetTestCase, tests))
403
404Since it is a common pattern to create a :class:`TestCase` subclass with many
405similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
406class that can be used to automate the process of creating a test suite and
407populating it with individual tests. For example, ::
408
409 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
410
411will create a test suite that will run ``WidgetTestCase.testDefaultSize()`` and
412``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method
413name prefix to identify test methods automatically.
414
415Note that the order in which the various test cases will be run is determined by
416sorting the test function names with the built-in :func:`cmp` function.
417
418Often it is desirable to group suites of test cases together, so as to run tests
419for the whole system at once. This is easy, since :class:`TestSuite` instances
420can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
421added to a :class:`TestSuite`::
422
423 suite1 = module1.TheTestSuite()
424 suite2 = module2.TheTestSuite()
425 alltests = unittest.TestSuite([suite1, suite2])
426
427You can place the definitions of test cases and test suites in the same modules
428as the code they are to test (such as :file:`widget.py`), but there are several
429advantages to placing the test code in a separate module, such as
430:file:`test_widget.py`:
431
432* The test module can be run standalone from the command line.
433
434* The test code can more easily be separated from shipped code.
435
436* There is less temptation to change test code to fit the code it tests without
437 a good reason.
438
439* Test code should be modified much less frequently than the code it tests.
440
441* Tested code can be refactored more easily.
442
443* Tests for modules written in C must be in separate modules anyway, so why not
444 be consistent?
445
446* If the testing strategy changes, there is no need to change the source code.
447
448
449.. _legacy-unit-tests:
450
451Re-using old test code
452----------------------
453
454Some users will find that they have existing test code that they would like to
455run from :mod:`unittest`, without converting every old test function to a
456:class:`TestCase` subclass.
457
458For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
459This subclass of :class:`TestCase` can be used to wrap an existing test
460function. Set-up and tear-down functions can also be provided.
461
462Given the following test function::
463
464 def testSomething():
465 something = makeSomething()
466 assert something.name is not None
467 # ...
468
469one can create an equivalent test case instance as follows::
470
471 testcase = unittest.FunctionTestCase(testSomething)
472
473If there are additional set-up and tear-down methods that should be called as
474part of the test case's operation, they can also be provided like so::
475
476 testcase = unittest.FunctionTestCase(testSomething,
477 setUp=makeSomethingDB,
478 tearDown=deleteSomethingDB)
479
480To make migrating existing test suites easier, :mod:`unittest` supports tests
481raising :exc:`AssertionError` to indicate test failure. However, it is
482recommended that you use the explicit :meth:`TestCase.fail\*` and
483:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
484may treat :exc:`AssertionError` differently.
485
486.. note::
487
Georg Brandl2fcd1732009-05-30 10:45:40 +0000488 Even though :class:`FunctionTestCase` can be used to quickly convert an
489 existing test base over to a :mod:`unittest`\ -based system, this approach is
490 not recommended. Taking the time to set up proper :class:`TestCase`
491 subclasses will make future test refactorings infinitely easier.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000492
Benjamin Peterson99721e02009-03-23 23:10:14 +0000493In some cases, the existing tests may have been written using the :mod:`doctest`
494module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
495automatically build :class:`unittest.TestSuite` instances from the existing
496:mod:`doctest`\ -based tests.
497
Georg Brandl8ec7f652007-08-15 14:28:01 +0000498
Benjamin Peterson692428e2009-03-23 21:50:21 +0000499.. _unittest-skipping:
500
501Skipping tests and expected failures
502------------------------------------
503
504Unittest supports skipping individual test methods and even whole classes of
505tests. In addition, it supports marking a test as a "expected failure," a test
506that is broken and will fail, but shouldn't be counted as a failure on a
507:class:`TestResult`.
508
509Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
510or one of its conditional variants.
511
512Basic skipping looks like this: ::
513
514 class MyTestCase(unittest.TestCase):
515
516 @unittest.skip("demonstrating skipping")
517 def test_nothing(self):
518 self.fail("shouldn't happen")
519
Georg Brandl2fcd1732009-05-30 10:45:40 +0000520 @unittest.skipIf(mylib.__version__ < (1, 3),
521 "not supported in this library version")
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000522 def test_format(self):
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000523 # Tests that work for only a certain version of the library.
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000524 pass
525
526 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
527 def test_windows_support(self):
528 # windows specific testing code
529 pass
530
Benjamin Peterson692428e2009-03-23 21:50:21 +0000531This is the output of running the example above in verbose mode: ::
532
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000533 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000534 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000535 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000536
537 ----------------------------------------------------------------------
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000538 Ran 3 tests in 0.005s
539
540 OK (skipped=3)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000541
542Classes can be skipped just like methods: ::
543
544 @skip("showing class skipping")
545 class MySkippedTestCase(unittest.TestCase):
546 def test_not_run(self):
547 pass
548
Benjamin Peterson31b78062009-03-23 23:13:36 +0000549:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
550that needs to be set up is not available.
551
Benjamin Peterson692428e2009-03-23 21:50:21 +0000552Expected failures use the :func:`expectedFailure` decorator. ::
553
554 class ExpectedFailureTestCase(unittest.TestCase):
555 @unittest.expectedFailure
556 def test_fail(self):
557 self.assertEqual(1, 0, "broken")
558
559It's easy to roll your own skipping decorators by making a decorator that calls
560:func:`skip` on the test when it wants it to be skipped. This decorator skips
561the test unless the passed object has a certain attribute: ::
562
563 def skipUnlessHasattr(obj, attr):
564 if hasattr(obj, attr):
565 return lambda func: func
566 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
567
568The following decorators implement test skipping and expected failures:
569
570.. function:: skip(reason)
571
572 Unconditionally skip the decorated test. *reason* should describe why the
573 test is being skipped.
574
575.. function:: skipIf(condition, reason)
576
577 Skip the decorated test if *condition* is true.
578
579.. function:: skipUnless(condition, reason)
580
581 Skip the decoratored test unless *condition* is true.
582
583.. function:: expectedFailure
584
585 Mark the test as an expected failure. If the test fails when run, the test
586 is not counted as a failure.
587
588
Georg Brandl8ec7f652007-08-15 14:28:01 +0000589.. _unittest-contents:
590
591Classes and functions
592---------------------
593
Benjamin Peterson99721e02009-03-23 23:10:14 +0000594This section describes in depth the API of :mod:`unittest`.
595
596
597.. _testcase-objects:
598
599Test cases
600~~~~~~~~~~
Georg Brandl8ec7f652007-08-15 14:28:01 +0000601
602.. class:: TestCase([methodName])
603
604 Instances of the :class:`TestCase` class represent the smallest testable units
605 in the :mod:`unittest` universe. This class is intended to be used as a base
606 class, with specific tests being implemented by concrete subclasses. This class
607 implements the interface needed by the test runner to allow it to drive the
608 test, and methods that the test code can use to check for and report various
609 kinds of failure.
610
611 Each instance of :class:`TestCase` will run a single test method: the method
612 named *methodName*. If you remember, we had an earlier example that went
613 something like this::
614
615 def suite():
616 suite = unittest.TestSuite()
617 suite.addTest(WidgetTestCase('testDefaultSize'))
618 suite.addTest(WidgetTestCase('testResize'))
619 return suite
620
621 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
622 single test.
623
Benjamin Peterson99721e02009-03-23 23:10:14 +0000624 *methodName* defaults to :meth:`runTest`.
625
626 :class:`TestCase` instances provide three groups of methods: one group used
627 to run the test, another used by the test implementation to check conditions
628 and report failures, and some inquiry methods allowing information about the
629 test itself to be gathered.
630
631 Methods in the first group (running the test) are:
632
633
634 .. method:: setUp()
635
636 Method called to prepare the test fixture. This is called immediately
637 before calling the test method; any exception raised by this method will
638 be considered an error rather than a test failure. The default
639 implementation does nothing.
640
641
642 .. method:: tearDown()
643
644 Method called immediately after the test method has been called and the
645 result recorded. This is called even if the test method raised an
646 exception, so the implementation in subclasses may need to be particularly
647 careful about checking internal state. Any exception raised by this
648 method will be considered an error rather than a test failure. This
649 method will only be called if the :meth:`setUp` succeeds, regardless of
650 the outcome of the test method. The default implementation does nothing.
651
652
653 .. method:: run([result])
654
655 Run the test, collecting the result into the test result object passed as
656 *result*. If *result* is omitted or :const:`None`, a temporary result
657 object is created (by calling the :meth:`defaultTestCase` method) and
658 used; this result object is not returned to :meth:`run`'s caller.
659
660 The same effect may be had by simply calling the :class:`TestCase`
661 instance.
662
663
Benjamin Peterson47d97382009-03-26 20:05:50 +0000664 .. method:: skipTest(reason)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000665
Benjamin Peterson31b78062009-03-23 23:13:36 +0000666 Calling this during the a test method or :meth:`setUp` skips the current
667 test. See :ref:`unittest-skipping` for more information.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000668
669
670 .. method:: debug()
671
672 Run the test without collecting the result. This allows exceptions raised
673 by the test to be propagated to the caller, and can be used to support
674 running tests under a debugger.
675
676 The test code can use any of the following methods to check for and report
677 failures.
678
679
Gregory P. Smith28399852009-03-31 16:54:10 +0000680 .. method:: assertTrue(expr[, msg])
681 assert_(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000682 failUnless(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000683
Georg Brandl64034bb2009-04-25 14:51:31 +0000684 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson99721e02009-03-23 23:10:14 +0000685 will be *msg* if given, otherwise it will be :const:`None`.
686
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000687 .. deprecated:: 2.7
688 :meth:`failUnless`.
689
Benjamin Peterson99721e02009-03-23 23:10:14 +0000690
691 .. method:: assertEqual(first, second[, msg])
692 failUnlessEqual(first, second[, msg])
693
694 Test that *first* and *second* are equal. If the values do not compare
695 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000696 :const:`None`. Note that using :meth:`assertEqual` improves upon
697 doing the comparison as the first parameter to :meth:`assertTrue`: the
698 default value for *msg* include representations of both *first* and
699 *second*.
700
701 In addition, if *first* and *second* are the exact same type and one of
702 list, tuple, dict, set, or frozenset or any type that a subclass
703 registers :meth:`addTypeEqualityFunc` the type specific equality function
704 will be called in order to generate a more useful default error message.
705
706 .. versionchanged:: 2.7
707 Added the automatic calling of type specific equality function.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000708
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000709 .. deprecated:: 2.7
710 :meth:`failUnlessEqual`.
711
Benjamin Peterson99721e02009-03-23 23:10:14 +0000712
713 .. method:: assertNotEqual(first, second[, msg])
714 failIfEqual(first, second[, msg])
715
716 Test that *first* and *second* are not equal. If the values do compare
717 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000718 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
719 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson99721e02009-03-23 23:10:14 +0000720 default value for *msg* can be computed to include representations of both
721 *first* and *second*.
722
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000723 .. deprecated:: 2.7
724 :meth:`failIfEqual`.
725
Benjamin Peterson99721e02009-03-23 23:10:14 +0000726
727 .. method:: assertAlmostEqual(first, second[, places[, msg]])
728 failUnlessAlmostEqual(first, second[, places[, msg]])
729
730 Test that *first* and *second* are approximately equal by computing the
731 difference, rounding to the given number of decimal *places* (default 7),
732 and comparing to zero.
733
734 Note that comparing a given number of decimal places is not the same as
735 comparing a given number of significant digits. If the values do not
736 compare equal, the test will fail with the explanation given by *msg*, or
737 :const:`None`.
738
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000739 .. deprecated:: 2.7
740 :meth:`failUnlessAlmostEqual`.
741
Benjamin Peterson99721e02009-03-23 23:10:14 +0000742
743 .. method:: assertNotAlmostEqual(first, second[, places[, msg]])
744 failIfAlmostEqual(first, second[, places[, msg]])
745
746 Test that *first* and *second* are not approximately equal by computing
747 the difference, rounding to the given number of decimal *places* (default
748 7), and comparing to zero.
749
750 Note that comparing a given number of decimal places is not the same as
751 comparing a given number of significant digits. If the values do not
752 compare equal, the test will fail with the explanation given by *msg*, or
753 :const:`None`.
754
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000755 .. deprecated:: 2.7
756 :meth:`failIfAlmostEqual`.
757
Benjamin Peterson99721e02009-03-23 23:10:14 +0000758
Gregory P. Smith28399852009-03-31 16:54:10 +0000759 .. method:: assertGreater(first, second, msg=None)
760 assertGreaterEqual(first, second, msg=None)
761 assertLess(first, second, msg=None)
762 assertLessEqual(first, second, msg=None)
763
764 Test that *first* is respectively >, >=, < or <= than *second* depending
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000765 on the method name. If not, the test will fail with an explanation
Gregory P. Smith28399852009-03-31 16:54:10 +0000766 or with the explanation given by *msg*::
767
768 >>> self.assertGreaterEqual(3, 4)
769 AssertionError: "3" unexpectedly not greater than or equal to "4"
770
771 .. versionadded:: 2.7
772
773
774 .. method:: assertMultiLineEqual(self, first, second, msg=None)
775
776 Test that the multiline string *first* is equal to the string *second*.
777 When not equal a diff of the two strings highlighting the differences
778 will be included in the error message.
779
780 If specified *msg* will be used as the error message on failure.
781
782 .. versionadded:: 2.7
783
784
785 .. method:: assertRegexpMatches(text, regexp[, msg=None]):
786
787 Verifies that a *regexp* search matches *text*. Fails with an error
788 message including the pattern and the *text*. *regexp* may be
789 a regular expression object or a string containing a regular expression
790 suitable for use by :func:`re.search`.
791
792 .. versionadded:: 2.7
793
794
795 .. method:: assertIn(first, second, msg=None)
796 assertNotIn(first, second, msg=None)
797
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000798 Tests that *first* is or is not in *second* with an explanatory error
Gregory P. Smith28399852009-03-31 16:54:10 +0000799 message as appropriate.
800
801 If specified *msg* will be used as the error message on failure.
802
803 .. versionadded:: 2.7
804
805
806 .. method:: assertSameElements(expected, actual, msg=None)
807
808 Test that sequence *expected* contains the same elements as *actual*.
809 When they don't an error message listing the differences between the
810 sequences will be generated.
811
812 If specified *msg* will be used as the error message on failure.
813
814 .. versionadded:: 2.7
815
816
817 .. method:: assertSetEqual(set1, set2, msg=None)
818
819 Tests that two sets are equal. If not, an error message is constructed
820 that lists the differences between the sets.
821
822 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
823 method.
824
825 If specified *msg* will be used as the error message on failure.
826
827 .. versionadded:: 2.7
828
829
830 .. method:: assertDictEqual(expected, actual, msg=None)
831
832 Test that two dictionaries are equal. If not, an error message is
833 constructed that shows the differences in the dictionaries.
834
835 If specified *msg* will be used as the error message on failure.
836
837 .. versionadded:: 2.7
838
839
840 .. method:: assertDictContainsSubset(expected, actual, msg=None)
841
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000842 Tests whether the key/value pairs in dictionary *actual* are a
Gregory P. Smith28399852009-03-31 16:54:10 +0000843 superset of those in *expected*. If not, an error message listing
844 the missing keys and mismatched values is generated.
845
846 If specified *msg* will be used as the error message on failure.
847
848 .. versionadded:: 2.7
849
850
851 .. method:: assertListEqual(list1, list2, msg=None)
852 assertTupleEqual(tuple1, tuple2, msg=None)
853
854 Tests that two lists or tuples are equal. If not an error message is
855 constructed that shows only the differences between the two. An error
856 is also raised if either of the parameters are of the wrong type.
857
858 If specified *msg* will be used as the error message on failure.
859
860 .. versionadded:: 2.7
861
862
863 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
864
865 Tests that two sequences are equal. If a *seq_type* is supplied, both
866 *seq1* and *seq2* must be instances of *seq_type* or a failure will
867 be raised. If the sequences are different an error message is
868 constructed that shows the difference between the two.
869
870 If specified *msg* will be used as the error message on failure.
871
872 This method is used to implement :meth:`assertListEqual` and
873 :meth:`assertTupleEqual`.
874
875 .. versionadded:: 2.7
876
877
Benjamin Peterson99721e02009-03-23 23:10:14 +0000878 .. method:: assertRaises(exception[, callable, ...])
879 failUnlessRaises(exception[, callable, ...])
880
881 Test that an exception is raised when *callable* is called with any
882 positional or keyword arguments that are also passed to
883 :meth:`assertRaises`. The test passes if *exception* is raised, is an
884 error if another exception is raised, or fails if no exception is raised.
885 To catch any of a group of exceptions, a tuple containing the exception
886 classes may be passed as *exception*.
887
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000888 If *callable* is omitted or None, returns a context manager so that the
889 code under test can be written inline rather than as a function::
890
891 with self.failUnlessRaises(some_error_class):
892 do_something()
893
Benjamin Peterson99721e02009-03-23 23:10:14 +0000894 .. versionchanged:: 2.7
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000895 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000896
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000897 .. deprecated:: 2.7
898 :meth:`failUnlessRaises`.
899
Benjamin Peterson99721e02009-03-23 23:10:14 +0000900
Gregory P. Smith28399852009-03-31 16:54:10 +0000901 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000902
Gregory P. Smith28399852009-03-31 16:54:10 +0000903 Like :meth:`assertRaises` but also tests that *regexp* matches
904 on the string representation of the raised exception. *regexp* may be
905 a regular expression object or a string containing a regular expression
906 suitable for use by :func:`re.search`. Examples::
907
908 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
909 int, 'XYZ')
910
911 or::
912
913 with self.assertRaisesRegexp(ValueError, 'literal'):
914 int('XYZ')
915
916 .. versionadded:: 2.7
917
918
919 .. method:: assertIsNone(expr[, msg])
920
921 This signals a test failure if *expr* is not None.
922
923 .. versionadded:: 2.7
924
925
926 .. method:: assertIsNotNone(expr[, msg])
927
928 The inverse of the :meth:`assertIsNone` method.
929 This signals a test failure if *expr* is None.
930
931 .. versionadded:: 2.7
932
933
Michael Foordf2dfef12009-04-05 19:19:28 +0000934 .. method:: assertIs(expr1, expr2[, msg])
935
936 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
937 object.
938
939 .. versionadded:: 2.7
940
941
942 .. method:: assertIsNot(expr1, expr2[, msg])
943
944 The inverse of the :meth:`assertIs` method.
945 This signals a test failure if *expr1* and *expr2* evaluate to the same
946 object.
947
948 .. versionadded:: 2.7
949
950
Gregory P. Smith28399852009-03-31 16:54:10 +0000951 .. method:: assertFalse(expr[, msg])
952 failIf(expr[, msg])
953
954 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000955 This signals a test failure if *expr* is true, with *msg* or :const:`None`
956 for the error message.
957
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000958 .. deprecated:: 2.7
959 :meth:`failIf`.
960
Benjamin Peterson99721e02009-03-23 23:10:14 +0000961
962 .. method:: fail([msg])
963
964 Signals a test failure unconditionally, with *msg* or :const:`None` for
965 the error message.
966
967
968 .. attribute:: failureException
969
970 This class attribute gives the exception raised by the test method. If a
971 test framework needs to use a specialized exception, possibly to carry
972 additional information, it must subclass this exception in order to "play
973 fair" with the framework. The initial value of this attribute is
974 :exc:`AssertionError`.
975
Michael Foord345b2fe2009-04-02 03:20:38 +0000976
977 .. attribute:: longMessage
978
979 If set to True then any explicit failure message you pass in to the
980 assert methods will be appended to the end of the normal failure message.
981 The normal messages contain useful information about the objects involved,
982 for example the message from assertEqual shows you the repr of the two
983 unequal objects. Setting this attribute to True allows you to have a
984 custom error message in addition to the normal one.
985
986 This attribute defaults to False, meaning that a custom message passed
987 to an assert method will silence the normal message.
988
989 The class setting can be overridden in individual tests by assigning an
990 instance attribute to True or False before calling the assert methods.
991
992 .. versionadded:: 2.7
993
994
Benjamin Peterson99721e02009-03-23 23:10:14 +0000995 Testing frameworks can use the following methods to collect information on
996 the test:
997
998
999 .. method:: countTestCases()
1000
1001 Return the number of tests represented by this test object. For
1002 :class:`TestCase` instances, this will always be ``1``.
1003
1004
1005 .. method:: defaultTestResult()
1006
1007 Return an instance of the test result class that should be used for this
1008 test case class (if no other result instance is provided to the
1009 :meth:`run` method).
1010
1011 For :class:`TestCase` instances, this will always be an instance of
1012 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1013 as necessary.
1014
1015
1016 .. method:: id()
1017
1018 Return a string identifying the specific test case. This is usually the
1019 full name of the test method, including the module and class name.
1020
1021
1022 .. method:: shortDescription()
1023
Gregory P. Smith28399852009-03-31 16:54:10 +00001024 Returns a description of the test, or :const:`None` if no description
1025 has been provided. The default implementation of this method
1026 returns the first line of the test method's docstring, if available,
1027 along with the method name.
1028
1029 .. versionchanged:: 2.7
Gregory P. Smith28399852009-03-31 16:54:10 +00001030 In earlier versions this only returned the first line of the test
1031 method's docstring, if available or the :const:`None`. That led to
1032 undesirable behavior of not printing the test name when someone was
1033 thoughtful enough to write a docstring.
1034
1035
1036 .. method:: addTypeEqualityFunc(typeobj, function)
1037
1038 Registers a type specific :meth:`assertEqual` equality checking
1039 function to be called by :meth:`assertEqual` when both objects it has
1040 been asked to compare are exactly *typeobj* (not subclasses).
1041 *function* must take two positional arguments and a third msg=None
1042 keyword argument just as :meth:`assertEqual` does. It must raise
Andrew M. Kuchling59631852009-04-09 11:23:36 +00001043 ``self.failureException`` when inequality between the first two
Gregory P. Smith28399852009-03-31 16:54:10 +00001044 parameters is detected.
1045
1046 One good use of custom equality checking functions for a type
Andrew M. Kuchling59631852009-04-09 11:23:36 +00001047 is to raise ``self.failureException`` with an error message useful
1048 for debugging the problem by explaining the inequalities in detail.
Gregory P. Smith28399852009-03-31 16:54:10 +00001049
1050 .. versionadded:: 2.7
Georg Brandl8ec7f652007-08-15 14:28:01 +00001051
1052
Michael Foorde2fb98f2009-05-02 20:15:05 +00001053 .. method:: addCleanup(function[, *args[, **kwargs]])
1054
1055 Add a function to be called after :meth:`tearDown` to cleanup resources
1056 used during the test. Functions will be called in reverse order to the
1057 order they are added (LIFO). They are called with any arguments and
1058 keyword arguments passed into :meth:`addCleanup` when they are
1059 added.
1060
1061 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1062 then any cleanup functions added will still be called.
1063
1064 .. versionadded:: 2.7
1065
1066
1067 .. method:: doCleanups()
1068
1069 This method is called uncoditionally after :meth:`tearDown`, or
1070 after :meth:`setUp` if :meth:`setUp` raises an exception.
1071
1072 It is responsible for calling all the cleanup functions added by
1073 :meth:`addCleanup`. If you need cleanup functions to be called
1074 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1075 yourself.
1076
1077 :meth:`doCleanups` pops methods off the stack of cleanup
1078 functions one at a time, so it can be called at any time.
1079
1080 .. versionadded:: 2.7
1081
1082
Georg Brandl8ec7f652007-08-15 14:28:01 +00001083.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
1084
1085 This class implements the portion of the :class:`TestCase` interface which
Georg Brandl2fcd1732009-05-30 10:45:40 +00001086 allows the test runner to drive the test, but does not provide the methods
1087 which test code can use to check and report errors. This is used to create
1088 test cases using legacy test code, allowing it to be integrated into a
1089 :mod:`unittest`-based test framework.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001090
1091
Benjamin Peterson99721e02009-03-23 23:10:14 +00001092.. _testsuite-objects:
1093
1094Grouping tests
1095~~~~~~~~~~~~~~
1096
Georg Brandl8ec7f652007-08-15 14:28:01 +00001097.. class:: TestSuite([tests])
1098
1099 This class represents an aggregation of individual tests cases and test suites.
1100 The class presents the interface needed by the test runner to allow it to be run
1101 as any other test case. Running a :class:`TestSuite` instance is the same as
1102 iterating over the suite, running each test individually.
1103
1104 If *tests* is given, it must be an iterable of individual test cases or other
1105 test suites that will be used to build the suite initially. Additional methods
1106 are provided to add test cases and suites to the collection later on.
1107
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001108 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1109 they do not actually implement a test. Instead, they are used to aggregate
1110 tests into groups of tests that should be run together. Some additional
1111 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson99721e02009-03-23 23:10:14 +00001112
1113
1114 .. method:: TestSuite.addTest(test)
1115
1116 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1117
1118
1119 .. method:: TestSuite.addTests(tests)
1120
1121 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1122 instances to this test suite.
1123
Georg Brandl2fcd1732009-05-30 10:45:40 +00001124 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1125 each element.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001126
1127 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1128
1129
1130 .. method:: run(result)
1131
1132 Run the tests associated with this suite, collecting the result into the
1133 test result object passed as *result*. Note that unlike
1134 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1135 be passed in.
1136
1137
1138 .. method:: debug()
1139
1140 Run the tests associated with this suite without collecting the
1141 result. This allows exceptions raised by the test to be propagated to the
1142 caller and can be used to support running tests under a debugger.
1143
1144
1145 .. method:: countTestCases()
1146
1147 Return the number of tests represented by this test object, including all
1148 individual tests and sub-suites.
1149
Georg Brandl9bc66822009-04-27 17:04:23 +00001150
1151 .. method:: __iter__()
1152
1153 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1154 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1155 that this method maybe called several times on a single suite
1156 (for example when counting tests or comparing for equality)
1157 so the tests returned must be the same for repeated iterations.
1158
1159 .. versionchanged:: 2.7
1160 In earlier versions the :class:`TestSuite` accessed tests directly rather
1161 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1162 for providing tests.
1163
Benjamin Peterson99721e02009-03-23 23:10:14 +00001164 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1165 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1166
1167
Benjamin Peterson99721e02009-03-23 23:10:14 +00001168Loading and running tests
1169~~~~~~~~~~~~~~~~~~~~~~~~~
1170
Georg Brandl8ec7f652007-08-15 14:28:01 +00001171.. class:: TestLoader()
1172
Benjamin Peterson99721e02009-03-23 23:10:14 +00001173 The :class:`TestLoader` class is used to create test suites from classes and
1174 modules. Normally, there is no need to create an instance of this class; the
1175 :mod:`unittest` module provides an instance that can be shared as
1176 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1177 customization of some configurable properties.
1178
1179 :class:`TestLoader` objects have the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001180
1181
Benjamin Peterson99721e02009-03-23 23:10:14 +00001182 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001183
Benjamin Peterson99721e02009-03-23 23:10:14 +00001184 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1185 :class:`testCaseClass`.
1186
1187
1188 .. method:: loadTestsFromModule(module)
1189
1190 Return a suite of all tests cases contained in the given module. This
1191 method searches *module* for classes derived from :class:`TestCase` and
1192 creates an instance of the class for each test method defined for the
1193 class.
1194
Georg Brandl16a57f62009-04-27 15:29:09 +00001195 .. note::
Benjamin Peterson99721e02009-03-23 23:10:14 +00001196
1197 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1198 convenient in sharing fixtures and helper functions, defining test
1199 methods on base classes that are not intended to be instantiated
1200 directly does not play well with this method. Doing so, however, can
1201 be useful when the fixtures are different and defined in subclasses.
1202
Michael Foordb4a81c82009-05-29 20:33:46 +00001203 If a module provides a ``load_tests`` function it will be called to
1204 load the tests. This allows modules to customize test loading.
1205 This is the `load_tests protocol`_.
1206
1207 .. versionchanged:: 2.7
1208 Support for ``load_tests`` added.
1209
Benjamin Peterson99721e02009-03-23 23:10:14 +00001210
1211 .. method:: loadTestsFromName(name[, module])
1212
1213 Return a suite of all tests cases given a string specifier.
1214
1215 The specifier *name* is a "dotted name" that may resolve either to a
1216 module, a test case class, a test method within a test case class, a
1217 :class:`TestSuite` instance, or a callable object which returns a
1218 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1219 applied in the order listed here; that is, a method on a possible test
1220 case class will be picked up as "a test method within a test case class",
1221 rather than "a callable object".
1222
1223 For example, if you have a module :mod:`SampleTests` containing a
Georg Brandl2fcd1732009-05-30 10:45:40 +00001224 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1225 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1226 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1227 return a suite which will run all three test methods. Using the specifier
1228 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1229 suite which will run only the :meth:`test_two` test method. The specifier
1230 can refer to modules and packages which have not been imported; they will
1231 be imported as a side-effect.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001232
1233 The method optionally resolves *name* relative to the given *module*.
1234
1235
1236 .. method:: loadTestsFromNames(names[, module])
1237
1238 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1239 than a single name. The return value is a test suite which supports all
1240 the tests defined for each name.
1241
1242
1243 .. method:: getTestCaseNames(testCaseClass)
1244
1245 Return a sorted sequence of method names found within *testCaseClass*;
1246 this should be a subclass of :class:`TestCase`.
1247
Michael Foordb4a81c82009-05-29 20:33:46 +00001248
1249 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1250
1251 Find and return all test modules from the specified start directory,
1252 recursing into subdirectories to find them. Only test files that match
1253 *pattern* will be loaded. (Using shell style pattern matching.)
1254
1255 All test modules must be importable from the top level of the project. If
1256 the start directory is not the top level directory then the top level
1257 directory must be specified separately.
1258
1259 If a test package name (directory with :file:`__init__.py`) matches the
1260 pattern then the package will be checked for a ``load_tests``
1261 function. If this exists then it will be called with *loader*, *tests*,
1262 *pattern*.
1263
1264 If load_tests exists then discovery does *not* recurse into the package,
1265 ``load_tests`` is responsible for loading all tests in the package.
1266
1267 The pattern is deliberately not stored as a loader attribute so that
1268 packages can continue discovery themselves. *top_level_dir* is stored so
1269 ``load_tests`` does not need to pass this argument in to
1270 ``loader.discover()``.
1271
1272
Benjamin Peterson99721e02009-03-23 23:10:14 +00001273 The following attributes of a :class:`TestLoader` can be configured either by
1274 subclassing or assignment on an instance:
1275
1276
1277 .. attribute:: testMethodPrefix
1278
1279 String giving the prefix of method names which will be interpreted as test
1280 methods. The default value is ``'test'``.
1281
1282 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1283 methods.
1284
1285
1286 .. attribute:: sortTestMethodsUsing
1287
1288 Function to be used to compare method names when sorting them in
1289 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
1290 default value is the built-in :func:`cmp` function; the attribute can also
1291 be set to :const:`None` to disable the sort.
1292
1293
1294 .. attribute:: suiteClass
1295
1296 Callable object that constructs a test suite from a list of tests. No
1297 methods on the resulting object are needed. The default value is the
1298 :class:`TestSuite` class.
1299
1300 This affects all the :meth:`loadTestsFrom\*` methods.
1301
1302
Benjamin Peterson99721e02009-03-23 23:10:14 +00001303.. class:: TestResult
1304
1305 This class is used to compile information about which tests have succeeded
1306 and which have failed.
1307
1308 A :class:`TestResult` object stores the results of a set of tests. The
1309 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1310 properly recorded; test authors do not need to worry about recording the
1311 outcome of tests.
1312
1313 Testing frameworks built on top of :mod:`unittest` may want access to the
1314 :class:`TestResult` object generated by running a set of tests for reporting
1315 purposes; a :class:`TestResult` instance is returned by the
1316 :meth:`TestRunner.run` method for this purpose.
1317
1318 :class:`TestResult` instances have the following attributes that will be of
1319 interest when inspecting the results of running a set of tests:
1320
1321
1322 .. attribute:: errors
1323
1324 A list containing 2-tuples of :class:`TestCase` instances and strings
1325 holding formatted tracebacks. Each tuple represents a test which raised an
1326 unexpected exception.
1327
1328 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001329 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1330
1331
1332 .. attribute:: failures
1333
1334 A list containing 2-tuples of :class:`TestCase` instances and strings
1335 holding formatted tracebacks. Each tuple represents a test where a failure
1336 was explicitly signalled using the :meth:`TestCase.fail\*` or
1337 :meth:`TestCase.assert\*` methods.
1338
1339 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001340 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1341
1342 .. attribute:: skipped
1343
1344 A list containing 2-tuples of :class:`TestCase` instances and strings
1345 holding the reason for skipping the test.
1346
1347 .. versionadded:: 2.7
1348
1349 .. attribute:: expectedFailures
1350
1351 A list contaning 2-tuples of :class:`TestCase` instances and strings
1352 holding formatted tracebacks. Each tuple represents a expected failures
1353 of the test case.
1354
1355 .. attribute:: unexpectedSuccesses
1356
1357 A list containing :class:`TestCase` instances that were marked as expected
1358 failures, but succeeded.
1359
1360 .. attribute:: shouldStop
1361
1362 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1363
1364
1365 .. attribute:: testsRun
1366
1367 The total number of tests run so far.
1368
1369
1370 .. method:: wasSuccessful()
1371
1372 Return :const:`True` if all tests run so far have passed, otherwise returns
1373 :const:`False`.
1374
1375
1376 .. method:: stop()
1377
1378 This method can be called to signal that the set of tests being run should
1379 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1380 :class:`TestRunner` objects should respect this flag and return without
1381 running any additional tests.
1382
1383 For example, this feature is used by the :class:`TextTestRunner` class to
1384 stop the test framework when the user signals an interrupt from the
1385 keyboard. Interactive tools which provide :class:`TestRunner`
1386 implementations can use this in a similar manner.
1387
1388 The following methods of the :class:`TestResult` class are used to maintain
1389 the internal data structures, and may be extended in subclasses to support
1390 additional reporting requirements. This is particularly useful in building
1391 tools which support interactive reporting while tests are being run.
1392
1393
1394 .. method:: startTest(test)
1395
1396 Called when the test case *test* is about to be run.
1397
1398 The default implementation simply increments the instance's :attr:`testsRun`
1399 counter.
1400
1401
1402 .. method:: stopTest(test)
1403
1404 Called after the test case *test* has been executed, regardless of the
1405 outcome.
1406
1407 The default implementation does nothing.
1408
1409
Michael Foord07ef4872009-05-02 22:43:34 +00001410 .. method:: startTestRun(test)
1411
1412 Called once before any tests are executed.
1413
1414 .. versionadded:: 2.7
1415
1416
1417 .. method:: stopTestRun(test)
1418
1419 Called once before any tests are executed.
1420
1421 .. versionadded:: 2.7
1422
1423
Benjamin Peterson99721e02009-03-23 23:10:14 +00001424 .. method:: addError(test, err)
1425
1426 Called when the test case *test* raises an unexpected exception *err* is a
1427 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1428 traceback)``.
1429
1430 The default implementation appends a tuple ``(test, formatted_err)`` to
1431 the instance's :attr:`errors` attribute, where *formatted_err* is a
1432 formatted traceback derived from *err*.
1433
1434
1435 .. method:: addFailure(test, err)
1436
Michael Foordb4a81c82009-05-29 20:33:46 +00001437 Called when the test case *test* signals a failure. *err* is a tuple of
1438 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001439
1440 The default implementation appends a tuple ``(test, formatted_err)`` to
1441 the instance's :attr:`failures` attribute, where *formatted_err* is a
1442 formatted traceback derived from *err*.
1443
1444
1445 .. method:: addSuccess(test)
1446
1447 Called when the test case *test* succeeds.
1448
1449 The default implementation does nothing.
1450
1451
1452 .. method:: addSkip(test, reason)
1453
1454 Called when the test case *test* is skipped. *reason* is the reason the
1455 test gave for skipping.
1456
1457 The default implementation appends a tuple ``(test, reason)`` to the
1458 instance's :attr:`skipped` attribute.
1459
1460
1461 .. method:: addExpectedFailure(test, err)
1462
1463 Called when the test case *test* fails, but was marked with the
1464 :func:`expectedFailure` decorator.
1465
1466 The default implementation appends a tuple ``(test, formatted_err)`` to
1467 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1468 is a formatted traceback derived from *err*.
1469
1470
1471 .. method:: addUnexpectedSuccess(test)
1472
1473 Called when the test case *test* was marked with the
1474 :func:`expectedFailure` decorator, but succeeded.
1475
1476 The default implementation appends the test to the instance's
1477 :attr:`unexpectedSuccesses` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001478
1479
1480.. data:: defaultTestLoader
1481
1482 Instance of the :class:`TestLoader` class intended to be shared. If no
1483 customization of the :class:`TestLoader` is needed, this instance can be used
1484 instead of repeatedly creating new instances.
1485
1486
1487.. class:: TextTestRunner([stream[, descriptions[, verbosity]]])
1488
1489 A basic test runner implementation which prints results on standard error. It
1490 has a few configurable parameters, but is essentially very simple. Graphical
1491 applications which run test suites should provide alternate implementations.
1492
Georg Brandl9bc66822009-04-27 17:04:23 +00001493 .. method:: _makeResult()
1494
1495 This method returns the instance of ``TestResult`` used by :meth:`run`.
1496 It is not intended to be called directly, but can be overridden in
1497 subclasses to provide a custom ``TestResult``.
1498
Georg Brandl8ec7f652007-08-15 14:28:01 +00001499
Michael Foord5d31e052009-05-11 17:59:43 +00001500.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit, [verbosity]]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001501
1502 A command-line program that runs a set of tests; this is primarily for making
1503 test modules conveniently executable. The simplest use for this function is to
1504 include the following line at the end of a test script::
1505
1506 if __name__ == '__main__':
1507 unittest.main()
1508
Michael Foord5d31e052009-05-11 17:59:43 +00001509 You can run tests with more detailed information by passing in the verbosity
1510 argument::
1511
1512 if __name__ == '__main__':
1513 unittest.main(verbosity=2)
1514
Georg Brandl8ec7f652007-08-15 14:28:01 +00001515 The *testRunner* argument can either be a test runner class or an already
Michael Foord829f6b82009-05-02 11:43:06 +00001516 created instance of it. By default ``main`` calls :func:`sys.exit` with
1517 an exit code indicating success or failure of the tests run.
1518
1519 ``main`` supports being used from the interactive interpreter by passing in the
1520 argument ``exit=False``. This displays the result on standard output without
1521 calling :func:`sys.exit`::
1522
1523 >>> from unittest import main
1524 >>> main(module='test_module', exit=False)
1525
1526 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1527 This stores the result of the tests run as the ``result`` attribute.
1528
1529 .. versionchanged:: 2.7
Michael Foord5d31e052009-05-11 17:59:43 +00001530 The ``exit`` and ``verbosity`` parameters were added.
Michael Foordb4a81c82009-05-29 20:33:46 +00001531
1532
1533load_tests Protocol
1534###################
1535
1536Modules or packages can customize how tests are loaded from them during normal
1537test runs or test discovery by implementing a function called ``load_tests``.
1538
1539If a test module defines ``load_tests`` it will be called by
1540:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1541
1542 load_tests(loader, standard_tests, None)
1543
1544It should return a :class:`TestSuite`.
1545
1546*loader* is the instance of :class:`TestLoader` doing the loading.
1547*standard_tests* are the tests that would be loaded by default from the
1548module. It is common for test modules to only want to add or remove tests
1549from the standard set of tests.
1550The third argument is used when loading packages as part of test discovery.
1551
1552A typical ``load_tests`` function that loads tests from a specific set of
1553:class:`TestCase` classes may look like::
1554
1555 test_cases = (TestCase1, TestCase2, TestCase3)
1556
1557 def load_tests(loader, tests, pattern):
1558 suite = TestSuite()
1559 for test_class in test_cases:
1560 tests = loader.loadTestsFromTestCase(test_class)
1561 suite.addTests(tests)
1562 return suite
1563
1564If discovery is started, either from the command line or by calling
1565:meth:`TestLoader.discover`, with a pattern that matches a package
1566name then the package :file:`__init__.py` will be checked for ``load_tests``.
1567
1568.. note::
1569
1570 The default pattern is 'test*.py'. This matches all python files
1571 that start with 'test' but *won't* match any test directories.
1572
1573 A pattern like 'test*' will match test packages as well as
1574 modules.
1575
1576If the package :file:`__init__.py` defines ``load_tests`` then it will be
1577called and discovery not continued into the package. ``load_tests``
1578is called with the following arguments::
1579
1580 load_tests(loader, standard_tests, pattern)
1581
1582This should return a :class:`TestSuite` representing all the tests
1583from the package. (``standard_tests`` will only contain tests
1584collected from :file:`__init__.py`.)
1585
1586Because the pattern is passed into ``load_tests`` the package is free to
1587continue (and potentially modify) test discovery. A 'do nothing'
1588``load_tests`` function for a test package would look like::
1589
1590 def load_tests(loader, standard_tests, pattern):
1591 # top level directory cached on loader instance
1592 this_dir = os.path.dirname(__file__)
1593 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1594 standard_tests.addTests(package_tests)
1595 return standard_tests