blob: 3f7680b5a532a92eed74ade3aa4e8fcd095de21e [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>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000081 Kent Beck's original paper on testing frameworks using the pattern shared
82 by :mod:`unittest`.
Georg Brandl116aa622007-08-15 14:28:22 +000083
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000084 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000085 Third-party unittest frameworks with a lighter-weight syntax for writing
86 tests. For example, ``assert func(10) == 42``.
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000087
88 `python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
Benjamin Petersond2397752009-06-27 23:45:02 +000089 Tools for creating mock test objects (objects simulating external
90 resources).
91
92
93.. _unittest-command-line-interface:
94
95Command Line Interface
96----------------------
97
98The unittest module can be used from the command line to run tests from
99modules, classes or even individual test methods::
100
101 python -m unittest test_module1 test_module2
102 python -m unittest test_module.TestClass
103 python -m unittest test_module.TestClass.test_method
104
105You can pass in a list with any combination of module names, and fully
106qualified class or method names.
107
108You can run tests with more detail (higher verbosity) by passing in the -v flag::
109
Ezio Melotti176d6c42010-01-27 20:58:07 +0000110 python -m unittest -v test_module
Benjamin Petersond2397752009-06-27 23:45:02 +0000111
112For a list of all the command line options::
113
114 python -m unittest -h
115
Georg Brandl853947a2010-01-31 18:53:23 +0000116.. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +0000117 In earlier versions it was only possible to run individual test methods and
118 not modules or classes.
119
120The command line can also be used for test discovery, for running all of the
121tests in a project or just a subset.
122
123
124.. _unittest-test-discovery:
125
126Test Discovery
127--------------
128
Georg Brandl853947a2010-01-31 18:53:23 +0000129.. versionadded:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +0000130
131unittest supports simple test discovery. For a project's tests to be
132compatible with test discovery they must all be importable from the top level
133directory of the project; i.e. they must all be in Python packages.
134
135Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
136used from the command line. The basic command line usage is::
137
138 cd project_directory
139 python -m unittest discover
140
141The ``discover`` sub-command has the following options:
142
143 -v, --verbose Verbose output
144 -s directory Directory to start discovery ('.' default)
145 -p pattern Pattern to match test files ('test*.py' default)
146 -t directory Top level directory of project (default to
147 start directory)
148
149The -s, -p, & -t options can be passsed in as positional arguments. The
150following two command lines are equivalent::
151
Ezio Melotti176d6c42010-01-27 20:58:07 +0000152 python -m unittest discover -s project_directory -p '*_test.py'
153 python -m unittest discover project_directory '*_test.py'
Benjamin Petersond2397752009-06-27 23:45:02 +0000154
155Test modules and packages can customize test loading and discovery by through
156the `load_tests protocol`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158.. _unittest-minimal-example:
159
160Basic example
161-------------
162
163The :mod:`unittest` module provides a rich set of tools for constructing and
164running tests. This section demonstrates that a small subset of the tools
165suffice to meet the needs of most users.
166
167Here is a short script to test three functions from the :mod:`random` module::
168
169 import random
170 import unittest
171
172 class TestSequenceFunctions(unittest.TestCase):
173
174 def setUp(self):
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000175 self.seq = list(range(10))
Georg Brandl116aa622007-08-15 14:28:22 +0000176
Benjamin Peterson52baa292009-03-24 00:56:30 +0000177 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000178 # make sure the shuffled sequence does not lose any elements
179 random.shuffle(self.seq)
180 self.seq.sort()
Benjamin Petersonbe0e1772009-07-25 01:02:01 +0000181 self.assertEqual(self.seq, list(range(10)))
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Benjamin Peterson52baa292009-03-24 00:56:30 +0000183 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000184 element = random.choice(self.seq)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000185 self.assertIn(element, self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000186
Benjamin Peterson52baa292009-03-24 00:56:30 +0000187 def test_sample(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000188 self.assertRaises(ValueError, random.sample, self.seq, 20)
189 for element in random.sample(self.seq, 5):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000190 self.assertIn(element, self.seq)
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192 if __name__ == '__main__':
193 unittest.main()
194
Benjamin Peterson52baa292009-03-24 00:56:30 +0000195A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000196individual tests are defined with methods whose names start with the letters
197``test``. This naming convention informs the test runner about which methods
198represent tests.
199
Benjamin Peterson52baa292009-03-24 00:56:30 +0000200The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
201expected result; :meth:`~TestCase.assert_` to verify a condition; or
202:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
203These methods are used instead of the :keyword:`assert` statement so the test
204runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Benjamin Peterson52baa292009-03-24 00:56:30 +0000206When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
207method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
208defined, the test runner will invoke that method after each test. In the
209example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
210test.
Georg Brandl116aa622007-08-15 14:28:22 +0000211
212The final block shows a simple way to run the tests. :func:`unittest.main`
213provides a command line interface to the test script. When run from the command
214line, the above script produces an output that looks like this::
215
216 ...
217 ----------------------------------------------------------------------
218 Ran 3 tests in 0.000s
219
220 OK
221
222Instead of :func:`unittest.main`, there are other ways to run the tests with a
223finer level of control, less terse output, and no requirement to be run from the
224command line. For example, the last two lines may be replaced with::
225
226 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
227 unittest.TextTestRunner(verbosity=2).run(suite)
228
229Running the revised script from the interpreter or another script produces the
230following output::
231
232 testchoice (__main__.TestSequenceFunctions) ... ok
233 testsample (__main__.TestSequenceFunctions) ... ok
234 testshuffle (__main__.TestSequenceFunctions) ... ok
235
236 ----------------------------------------------------------------------
237 Ran 3 tests in 0.110s
238
239 OK
240
241The above examples show the most commonly used :mod:`unittest` features which
242are sufficient to meet many everyday testing needs. The remainder of the
243documentation explores the full feature set from first principles.
244
Georg Brandl116aa622007-08-15 14:28:22 +0000245.. _organizing-tests:
246
247Organizing test code
248--------------------
249
250The basic building blocks of unit testing are :dfn:`test cases` --- single
251scenarios that must be set up and checked for correctness. In :mod:`unittest`,
252test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
253class. To make your own test cases you must write subclasses of
254:class:`TestCase`, or use :class:`FunctionTestCase`.
255
256An instance of a :class:`TestCase`\ -derived class is an object that can
257completely run a single test method, together with optional set-up and tidy-up
258code.
259
260The testing code of a :class:`TestCase` instance should be entirely self
261contained, such that it can be run either in isolation or in arbitrary
262combination with any number of other test cases.
263
Benjamin Peterson52baa292009-03-24 00:56:30 +0000264The simplest :class:`TestCase` subclass will simply override the
265:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267 import unittest
268
269 class DefaultWidgetSizeTestCase(unittest.TestCase):
270 def runTest(self):
271 widget = Widget('The widget')
272 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
273
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000274Note that in order to test something, we use the one of the :meth:`assert\*`
Benjamin Petersond2397752009-06-27 23:45:02 +0000275methods provided by the :class:`TestCase` base class. If the test fails, an
276exception will be raised, and :mod:`unittest` will identify the test case as a
277:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
278helps you identify where the problem is: :dfn:`failures` are caused by incorrect
279results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
280code - e.g., a :exc:`TypeError` caused by an incorrect function call.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282The way to run a test case will be described later. For now, note that to
283construct an instance of such a test case, we call its constructor without
284arguments::
285
286 testCase = DefaultWidgetSizeTestCase()
287
288Now, such test cases can be numerous, and their set-up can be repetitive. In
289the above case, constructing a :class:`Widget` in each of 100 Widget test case
290subclasses would mean unsightly duplication.
291
292Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000293:meth:`~TestCase.setUp`, which the testing framework will automatically call for
294us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296 import unittest
297
298 class SimpleWidgetTestCase(unittest.TestCase):
299 def setUp(self):
300 self.widget = Widget('The widget')
301
302 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
303 def runTest(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000304 self.assertEqual(self.widget.size(), (50,50),
305 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000306
307 class WidgetResizeTestCase(SimpleWidgetTestCase):
308 def runTest(self):
309 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000310 self.assertEqual(self.widget.size(), (100,150),
311 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Benjamin Peterson52baa292009-03-24 00:56:30 +0000313If the :meth:`~TestCase.setUp` method raises an exception while the test is
314running, the framework will consider the test to have suffered an error, and the
315:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000316
Benjamin Peterson52baa292009-03-24 00:56:30 +0000317Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
318after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000319
320 import unittest
321
322 class SimpleWidgetTestCase(unittest.TestCase):
323 def setUp(self):
324 self.widget = Widget('The widget')
325
326 def tearDown(self):
327 self.widget.dispose()
328 self.widget = None
329
Benjamin Peterson52baa292009-03-24 00:56:30 +0000330If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
331be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000332
333Such a working environment for the testing code is called a :dfn:`fixture`.
334
335Often, many small test cases will use the same fixture. In this case, we would
336end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
337classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000338discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
339mechanism::
340
341 import unittest
342
343 class WidgetTestCase(unittest.TestCase):
344 def setUp(self):
345 self.widget = Widget('The widget')
346
347 def tearDown(self):
348 self.widget.dispose()
349 self.widget = None
350
351 def testDefaultSize(self):
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000352 self.assertEqual(self.widget.size(), (50,50),
353 'incorrect default size')
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355 def testResize(self):
356 self.widget.resize(100,150)
Ezio Melotti2d6c39b2010-02-04 20:27:41 +0000357 self.assertEqual(self.widget.size(), (100,150),
358 'wrong size after resize')
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Benjamin Peterson52baa292009-03-24 00:56:30 +0000360Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
361provided two different test methods. Class instances will now each run one of
362the :meth:`test\*` methods, with ``self.widget`` created and destroyed
363separately for each instance. When creating an instance we must specify the
364test method it is to run. We do this by passing the method name in the
365constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367 defaultSizeTestCase = WidgetTestCase('testDefaultSize')
368 resizeTestCase = WidgetTestCase('testResize')
369
370Test case instances are grouped together according to the features they test.
371:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
372represented by :mod:`unittest`'s :class:`TestSuite` class::
373
374 widgetTestSuite = unittest.TestSuite()
375 widgetTestSuite.addTest(WidgetTestCase('testDefaultSize'))
376 widgetTestSuite.addTest(WidgetTestCase('testResize'))
377
378For the ease of running tests, as we will see later, it is a good idea to
379provide in each test module a callable object that returns a pre-built test
380suite::
381
382 def suite():
383 suite = unittest.TestSuite()
384 suite.addTest(WidgetTestCase('testDefaultSize'))
385 suite.addTest(WidgetTestCase('testResize'))
386 return suite
387
388or even::
389
390 def suite():
391 tests = ['testDefaultSize', 'testResize']
392
393 return unittest.TestSuite(map(WidgetTestCase, tests))
394
395Since it is a common pattern to create a :class:`TestCase` subclass with many
396similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
397class that can be used to automate the process of creating a test suite and
398populating it with individual tests. For example, ::
399
400 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
401
402will create a test suite that will run ``WidgetTestCase.testDefaultSize()`` and
403``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method
404name prefix to identify test methods automatically.
405
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000406Note that the order in which the various test cases will be run is
407determined by sorting the test function names with respect to the
408built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410Often it is desirable to group suites of test cases together, so as to run tests
411for the whole system at once. This is easy, since :class:`TestSuite` instances
412can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
413added to a :class:`TestSuite`::
414
415 suite1 = module1.TheTestSuite()
416 suite2 = module2.TheTestSuite()
417 alltests = unittest.TestSuite([suite1, suite2])
418
419You can place the definitions of test cases and test suites in the same modules
420as the code they are to test (such as :file:`widget.py`), but there are several
421advantages to placing the test code in a separate module, such as
422:file:`test_widget.py`:
423
424* The test module can be run standalone from the command line.
425
426* The test code can more easily be separated from shipped code.
427
428* There is less temptation to change test code to fit the code it tests without
429 a good reason.
430
431* Test code should be modified much less frequently than the code it tests.
432
433* Tested code can be refactored more easily.
434
435* Tests for modules written in C must be in separate modules anyway, so why not
436 be consistent?
437
438* If the testing strategy changes, there is no need to change the source code.
439
440
441.. _legacy-unit-tests:
442
443Re-using old test code
444----------------------
445
446Some users will find that they have existing test code that they would like to
447run from :mod:`unittest`, without converting every old test function to a
448:class:`TestCase` subclass.
449
450For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
451This subclass of :class:`TestCase` can be used to wrap an existing test
452function. Set-up and tear-down functions can also be provided.
453
454Given the following test function::
455
456 def testSomething():
457 something = makeSomething()
458 assert something.name is not None
459 # ...
460
461one can create an equivalent test case instance as follows::
462
463 testcase = unittest.FunctionTestCase(testSomething)
464
465If there are additional set-up and tear-down methods that should be called as
466part of the test case's operation, they can also be provided like so::
467
468 testcase = unittest.FunctionTestCase(testSomething,
469 setUp=makeSomethingDB,
470 tearDown=deleteSomethingDB)
471
472To make migrating existing test suites easier, :mod:`unittest` supports tests
473raising :exc:`AssertionError` to indicate test failure. However, it is
474recommended that you use the explicit :meth:`TestCase.fail\*` and
475:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
476may treat :exc:`AssertionError` differently.
477
478.. note::
479
Benjamin Petersond2397752009-06-27 23:45:02 +0000480 Even though :class:`FunctionTestCase` can be used to quickly convert an
481 existing test base over to a :mod:`unittest`\ -based system, this approach is
482 not recommended. Taking the time to set up proper :class:`TestCase`
483 subclasses will make future test refactorings infinitely easier.
Georg Brandl116aa622007-08-15 14:28:22 +0000484
Benjamin Peterson52baa292009-03-24 00:56:30 +0000485In some cases, the existing tests may have been written using the :mod:`doctest`
486module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
487automatically build :class:`unittest.TestSuite` instances from the existing
488:mod:`doctest`\ -based tests.
489
Georg Brandl116aa622007-08-15 14:28:22 +0000490
Benjamin Peterson5254c042009-03-23 22:25:03 +0000491.. _unittest-skipping:
492
493Skipping tests and expected failures
494------------------------------------
495
496Unittest supports skipping individual test methods and even whole classes of
497tests. In addition, it supports marking a test as a "expected failure," a test
498that is broken and will fail, but shouldn't be counted as a failure on a
499:class:`TestResult`.
500
501Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
502or one of its conditional variants.
503
504Basic skipping looks like this: ::
505
506 class MyTestCase(unittest.TestCase):
507
508 @unittest.skip("demonstrating skipping")
509 def test_nothing(self):
510 self.fail("shouldn't happen")
511
Benjamin Petersond2397752009-06-27 23:45:02 +0000512 @unittest.skipIf(mylib.__version__ < (1, 3),
513 "not supported in this library version")
Benjamin Petersonded31c42009-03-30 15:04:16 +0000514 def test_format(self):
515 # Tests that work for only a certain version of the library.
516 pass
517
518 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
519 def test_windows_support(self):
520 # windows specific testing code
521 pass
522
Benjamin Peterson5254c042009-03-23 22:25:03 +0000523This is the output of running the example above in verbose mode: ::
524
Benjamin Petersonded31c42009-03-30 15:04:16 +0000525 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000526 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000527 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000528
529 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000530 Ran 3 tests in 0.005s
531
532 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000533
534Classes can be skipped just like methods: ::
535
536 @skip("showing class skipping")
537 class MySkippedTestCase(unittest.TestCase):
538 def test_not_run(self):
539 pass
540
Benjamin Peterson52baa292009-03-24 00:56:30 +0000541:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
542that needs to be set up is not available.
543
Benjamin Peterson5254c042009-03-23 22:25:03 +0000544Expected failures use the :func:`expectedFailure` decorator. ::
545
546 class ExpectedFailureTestCase(unittest.TestCase):
547 @unittest.expectedFailure
548 def test_fail(self):
549 self.assertEqual(1, 0, "broken")
550
551It's easy to roll your own skipping decorators by making a decorator that calls
552:func:`skip` on the test when it wants it to be skipped. This decorator skips
553the test unless the passed object has a certain attribute: ::
554
555 def skipUnlessHasattr(obj, attr):
556 if hasattr(obj, attr):
557 return lambda func: func
558 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
559
560The following decorators implement test skipping and expected failures:
561
562.. function:: skip(reason)
563
564 Unconditionally skip the decorated test. *reason* should describe why the
565 test is being skipped.
566
567.. function:: skipIf(condition, reason)
568
569 Skip the decorated test if *condition* is true.
570
571.. function:: skipUnless(condition, reason)
572
573 Skip the decoratored test unless *condition* is true.
574
575.. function:: expectedFailure
576
577 Mark the test as an expected failure. If the test fails when run, the test
578 is not counted as a failure.
579
580
Georg Brandl116aa622007-08-15 14:28:22 +0000581.. _unittest-contents:
582
583Classes and functions
584---------------------
585
Benjamin Peterson52baa292009-03-24 00:56:30 +0000586This section describes in depth the API of :mod:`unittest`.
587
588
589.. _testcase-objects:
590
591Test cases
592~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000593
Georg Brandl7f01a132009-09-16 15:58:14 +0000594.. class:: TestCase(methodName='runTest')
Georg Brandl116aa622007-08-15 14:28:22 +0000595
596 Instances of the :class:`TestCase` class represent the smallest testable units
597 in the :mod:`unittest` universe. This class is intended to be used as a base
598 class, with specific tests being implemented by concrete subclasses. This class
599 implements the interface needed by the test runner to allow it to drive the
600 test, and methods that the test code can use to check for and report various
601 kinds of failure.
602
603 Each instance of :class:`TestCase` will run a single test method: the method
604 named *methodName*. If you remember, we had an earlier example that went
605 something like this::
606
607 def suite():
608 suite = unittest.TestSuite()
609 suite.addTest(WidgetTestCase('testDefaultSize'))
610 suite.addTest(WidgetTestCase('testResize'))
611 return suite
612
613 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
614 single test.
615
Benjamin Peterson52baa292009-03-24 00:56:30 +0000616 *methodName* defaults to :meth:`runTest`.
617
618 :class:`TestCase` instances provide three groups of methods: one group used
619 to run the test, another used by the test implementation to check conditions
620 and report failures, and some inquiry methods allowing information about the
621 test itself to be gathered.
622
623 Methods in the first group (running the test) are:
624
625
626 .. method:: setUp()
627
628 Method called to prepare the test fixture. This is called immediately
629 before calling the test method; any exception raised by this method will
630 be considered an error rather than a test failure. The default
631 implementation does nothing.
632
633
634 .. method:: tearDown()
635
636 Method called immediately after the test method has been called and the
637 result recorded. This is called even if the test method raised an
638 exception, so the implementation in subclasses may need to be particularly
639 careful about checking internal state. Any exception raised by this
640 method will be considered an error rather than a test failure. This
641 method will only be called if the :meth:`setUp` succeeds, regardless of
642 the outcome of the test method. The default implementation does nothing.
643
644
Georg Brandl7f01a132009-09-16 15:58:14 +0000645 .. method:: run(result=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000646
647 Run the test, collecting the result into the test result object passed as
648 *result*. If *result* is omitted or :const:`None`, a temporary result
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000649 object is created (by calling the :meth:`defaultTestResult` method) and
650 used. The result object is not returned to :meth:`run`'s caller.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000651
652 The same effect may be had by simply calling the :class:`TestCase`
653 instance.
654
655
Benjamin Petersone549ead2009-03-28 21:42:05 +0000656 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000657
658 Calling this during the a test method or :meth:`setUp` skips the current
659 test. See :ref:`unittest-skipping` for more information.
660
661
662 .. method:: debug()
663
664 Run the test without collecting the result. This allows exceptions raised
665 by the test to be propagated to the caller, and can be used to support
666 running tests under a debugger.
667
668 The test code can use any of the following methods to check for and report
669 failures.
670
671
Georg Brandl7f01a132009-09-16 15:58:14 +0000672 .. method:: assertTrue(expr, msg=None)
673 assert_(expr, msg=None)
674 failUnless(expr, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000675
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000676 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson52baa292009-03-24 00:56:30 +0000677 will be *msg* if given, otherwise it will be :const:`None`.
678
Raymond Hettinger35a88362009-04-09 00:08:24 +0000679 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000680 :meth:`failUnless`.
681
Benjamin Peterson52baa292009-03-24 00:56:30 +0000682
Georg Brandl7f01a132009-09-16 15:58:14 +0000683 .. method:: assertEqual(first, second, msg=None)
684 failUnlessEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000685
686 Test that *first* and *second* are equal. If the values do not compare
687 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000688 :const:`None`. Note that using :meth:`assertEqual` improves upon
689 doing the comparison as the first parameter to :meth:`assertTrue`: the
690 default value for *msg* include representations of both *first* and
691 *second*.
692
693 In addition, if *first* and *second* are the exact same type and one of
694 list, tuple, dict, set, or frozenset or any type that a subclass
695 registers :meth:`addTypeEqualityFunc` the type specific equality function
696 will be called in order to generate a more useful default error message.
697
Raymond Hettinger35a88362009-04-09 00:08:24 +0000698 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000699 Added the automatic calling of type specific equality function.
700
Raymond Hettinger35a88362009-04-09 00:08:24 +0000701 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000702 :meth:`failUnlessEqual`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000703
704
Georg Brandl7f01a132009-09-16 15:58:14 +0000705 .. method:: assertNotEqual(first, second, msg=None)
706 failIfEqual(first, second, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000707
708 Test that *first* and *second* are not equal. If the values do compare
709 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000710 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
711 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson52baa292009-03-24 00:56:30 +0000712 default value for *msg* can be computed to include representations of both
713 *first* and *second*.
714
Raymond Hettinger35a88362009-04-09 00:08:24 +0000715 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000716 :meth:`failIfEqual`.
717
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000718
Georg Brandl7f01a132009-09-16 15:58:14 +0000719 .. method:: assertAlmostEqual(first, second, *, places=7, msg=None)
720 failUnlessAlmostEqual(first, second, *, places=7, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000721
722 Test that *first* and *second* are approximately equal by computing the
723 difference, rounding to the given number of decimal *places* (default 7),
724 and comparing to zero.
725
726 Note that comparing a given number of decimal places is not the same as
727 comparing a given number of significant digits. If the values do not
728 compare equal, the test will fail with the explanation given by *msg*, or
729 :const:`None`.
730
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000731 .. versionchanged:: 3.2
732 Objects that compare equal are automatically almost equal.
733
Raymond Hettinger35a88362009-04-09 00:08:24 +0000734 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000735 :meth:`failUnlessAlmostEqual`.
736
Benjamin Peterson52baa292009-03-24 00:56:30 +0000737
Georg Brandl7f01a132009-09-16 15:58:14 +0000738 .. method:: assertNotAlmostEqual(first, second, *, places=7, msg=None)
739 failIfAlmostEqual(first, second, *, places=7, msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000740
741 Test that *first* and *second* are not approximately equal by computing
742 the difference, rounding to the given number of decimal *places* (default
743 7), and comparing to zero.
744
745 Note that comparing a given number of decimal places is not the same as
746 comparing a given number of significant digits. If the values do not
747 compare equal, the test will fail with the explanation given by *msg*, or
748 :const:`None`.
749
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000750 .. versionchanged:: 3.2
751 Objects that compare equal automatically fail.
752
Raymond Hettinger35a88362009-04-09 00:08:24 +0000753 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000754 :meth:`failIfAlmostEqual`.
755
756
757 .. method:: assertGreater(first, second, msg=None)
758 assertGreaterEqual(first, second, msg=None)
759 assertLess(first, second, msg=None)
760 assertLessEqual(first, second, msg=None)
761
762 Test that *first* is respectively >, >=, < or <= than *second* depending
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000763 on the method name. If not, the test will fail with an explanation
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000764 or with the explanation given by *msg*::
765
766 >>> self.assertGreaterEqual(3, 4)
767 AssertionError: "3" unexpectedly not greater than or equal to "4"
768
Raymond Hettinger35a88362009-04-09 00:08:24 +0000769 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000770
771
772 .. method:: assertMultiLineEqual(self, first, second, msg=None)
773
774 Test that the multiline string *first* is equal to the string *second*.
775 When not equal a diff of the two strings highlighting the differences
776 will be included in the error message.
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
Ezio Melotti732b6822010-01-16 19:40:06 +0000783 .. method:: assertRegexpMatches(text, regexp, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000784
785 Verifies that a *regexp* search matches *text*. Fails with an error
786 message including the pattern and the *text*. *regexp* may be
787 a regular expression object or a string containing a regular expression
788 suitable for use by :func:`re.search`.
789
Raymond Hettinger35a88362009-04-09 00:08:24 +0000790 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000791
792
793 .. method:: assertIn(first, second, msg=None)
794 assertNotIn(first, second, msg=None)
795
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000796 Tests that *first* is or is not in *second* with an explanatory error
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000797 message as appropriate.
798
799 If specified *msg* will be used as the error message on failure.
800
Raymond Hettinger35a88362009-04-09 00:08:24 +0000801 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000802
803
Michael Foorde9abbee2010-02-05 20:54:27 +0000804 .. method:: assertSameElements(actual, expected, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000805
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000806 Test that sequence *expected* contains the same elements as *actual*,
807 regardless of their order. When they don't, an error message listing
808 the differences between the sequences will be generated.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000809
Michael Foorde9abbee2010-02-05 20:54:27 +0000810 Duplicate elements are ignored when comparing *actual* and *expected*.
811 It is the equivalent of ``assertEqual(set(expected), set(actual))``
812 but it works with sequences of unhashable objects as well.
813
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000814 If specified *msg* will be used as the error message on failure.
815
Raymond Hettinger35a88362009-04-09 00:08:24 +0000816 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000817
818
819 .. method:: assertSetEqual(set1, set2, msg=None)
820
821 Tests that two sets are equal. If not, an error message is constructed
822 that lists the differences between the sets.
823
824 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
825 method.
826
827 If specified *msg* will be used as the error message on failure.
828
Raymond Hettinger35a88362009-04-09 00:08:24 +0000829 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000830
831
832 .. method:: assertDictEqual(expected, actual, msg=None)
833
834 Test that two dictionaries are equal. If not, an error message is
835 constructed that shows the differences in the dictionaries.
836
837 If specified *msg* will be used as the error message on failure.
838
Raymond Hettinger35a88362009-04-09 00:08:24 +0000839 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000840
841
842 .. method:: assertDictContainsSubset(expected, actual, msg=None)
843
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000844 Tests whether the key/value pairs in dictionary *actual* are a
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000845 superset of those in *expected*. If not, an error message listing
846 the missing keys and mismatched values is generated.
847
848 If specified *msg* will be used as the error message on failure.
849
Raymond Hettinger35a88362009-04-09 00:08:24 +0000850 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000851
852
853 .. method:: assertListEqual(list1, list2, msg=None)
854 assertTupleEqual(tuple1, tuple2, msg=None)
855
856 Tests that two lists or tuples are equal. If not an error message is
857 constructed that shows only the differences between the two. An error
858 is also raised if either of the parameters are of the wrong type.
859
860 If specified *msg* will be used as the error message on failure.
861
Raymond Hettinger35a88362009-04-09 00:08:24 +0000862 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000863
864
865 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
866
867 Tests that two sequences are equal. If a *seq_type* is supplied, both
868 *seq1* and *seq2* must be instances of *seq_type* or a failure will
869 be raised. If the sequences are different an error message is
870 constructed that shows the difference between the two.
871
872 If specified *msg* will be used as the error message on failure.
873
874 This method is used to implement :meth:`assertListEqual` and
875 :meth:`assertTupleEqual`.
876
Raymond Hettinger35a88362009-04-09 00:08:24 +0000877 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000878
Benjamin Peterson52baa292009-03-24 00:56:30 +0000879
Georg Brandl7f01a132009-09-16 15:58:14 +0000880 .. method:: assertRaises(exception, callable, *args, **kwds)
881 failUnlessRaises(exception, callable, *args, **kwds)
882 assertRaises(exception)
883 failUnlessRaises(exception)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000884
885 Test that an exception is raised when *callable* is called with any
886 positional or keyword arguments that are also passed to
887 :meth:`assertRaises`. The test passes if *exception* is raised, is an
888 error if another exception is raised, or fails if no exception is raised.
889 To catch any of a group of exceptions, a tuple containing the exception
890 classes may be passed as *exception*.
891
Georg Brandl7f01a132009-09-16 15:58:14 +0000892 If only the *exception* argument is given, returns a context manager so
893 that the code under test can be written inline rather than as a function::
Benjamin Petersonded31c42009-03-30 15:04:16 +0000894
Michael Foord41531f22010-02-05 21:13:40 +0000895 with self.assertRaises(SomeException):
Benjamin Petersonded31c42009-03-30 15:04:16 +0000896 do_something()
897
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000898 The context manager will store the caught exception object in its
899 :attr:`exc_value` attribute. This can be useful if the intention
Michael Foord41531f22010-02-05 21:13:40 +0000900 is to perform additional checks on the exception raised::
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000901
Michael Foord41531f22010-02-05 21:13:40 +0000902 with self.assertRaises(SomeException) as cm:
903 do_something()
904
905 the_exception = cm.exc_value
906 self.assertEquals(the_exception.error_code, 3)
907
908 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000909 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000910
Raymond Hettinger35a88362009-04-09 00:08:24 +0000911 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000912 :meth:`failUnlessRaises`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000913
Kristján Valur Jónsson88d1bc42009-11-13 16:15:57 +0000914 .. versionchanged:: 3.2
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +0000915 Added the :attr:`exc_value` attribute.
916
Benjamin Peterson52baa292009-03-24 00:56:30 +0000917
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000918 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
919
920 Like :meth:`assertRaises` but also tests that *regexp* matches
921 on the string representation of the raised exception. *regexp* may be
922 a regular expression object or a string containing a regular expression
923 suitable for use by :func:`re.search`. Examples::
924
925 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
926 int, 'XYZ')
927
928 or::
929
930 with self.assertRaisesRegexp(ValueError, 'literal'):
931 int('XYZ')
932
Raymond Hettinger35a88362009-04-09 00:08:24 +0000933 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000934
935
Georg Brandl7f01a132009-09-16 15:58:14 +0000936 .. method:: assertIsNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000937
938 This signals a test failure if *expr* is not None.
939
Raymond Hettinger35a88362009-04-09 00:08:24 +0000940 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000941
942
Georg Brandl7f01a132009-09-16 15:58:14 +0000943 .. method:: assertIsNotNone(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000944
945 The inverse of the :meth:`assertIsNone` method.
946 This signals a test failure if *expr* is None.
947
Raymond Hettinger35a88362009-04-09 00:08:24 +0000948 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000949
950
Georg Brandl7f01a132009-09-16 15:58:14 +0000951 .. method:: assertIs(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000952
953 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
954 object.
955
Georg Brandl705d9d52009-05-05 09:29:50 +0000956 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000957
958
Georg Brandl7f01a132009-09-16 15:58:14 +0000959 .. method:: assertIsNot(expr1, expr2, msg=None)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000960
961 The inverse of the :meth:`assertIs` method.
962 This signals a test failure if *expr1* and *expr2* evaluate to the same
963 object.
964
Georg Brandl705d9d52009-05-05 09:29:50 +0000965 .. versionadded:: 3.1
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000966
967
Benjamin Peterson6e8c7572009-10-04 20:19:21 +0000968 .. method:: assertIsInstance(obj, cls[, msg])
969
970 This signals a test failure if *obj* is not an instance of *cls* (which
971 can be a class or a tuple of classes, as supported by :func:`isinstance`).
972
973 .. versionadded:: 3.2
974
975
976 .. method:: assertNotIsInstance(obj, cls[, msg])
977
978 The inverse of the :meth:`assertIsInstance` method. This signals a test
979 failure if *obj* is an instance of *cls*.
980
981 .. versionadded:: 3.2
982
983
Georg Brandl7f01a132009-09-16 15:58:14 +0000984 .. method:: assertFalse(expr, msg=None)
985 failIf(expr, msg=None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000986
987 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000988 This signals a test failure if *expr* is true, with *msg* or :const:`None`
989 for the error message.
990
Raymond Hettinger35a88362009-04-09 00:08:24 +0000991 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000992 :meth:`failIf`.
993
Benjamin Peterson52baa292009-03-24 00:56:30 +0000994
Georg Brandl7f01a132009-09-16 15:58:14 +0000995 .. method:: fail(msg=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000996
997 Signals a test failure unconditionally, with *msg* or :const:`None` for
998 the error message.
999
1000
1001 .. attribute:: failureException
1002
1003 This class attribute gives the exception raised by the test method. If a
1004 test framework needs to use a specialized exception, possibly to carry
1005 additional information, it must subclass this exception in order to "play
1006 fair" with the framework. The initial value of this attribute is
1007 :exc:`AssertionError`.
1008
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001009
1010 .. attribute:: longMessage
1011
1012 If set to True then any explicit failure message you pass in to the
1013 assert methods will be appended to the end of the normal failure message.
1014 The normal messages contain useful information about the objects involved,
1015 for example the message from assertEqual shows you the repr of the two
1016 unequal objects. Setting this attribute to True allows you to have a
1017 custom error message in addition to the normal one.
1018
1019 This attribute defaults to False, meaning that a custom message passed
1020 to an assert method will silence the normal message.
1021
1022 The class setting can be overridden in individual tests by assigning an
1023 instance attribute to True or False before calling the assert methods.
1024
Raymond Hettinger35a88362009-04-09 00:08:24 +00001025 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001026
1027
Benjamin Peterson52baa292009-03-24 00:56:30 +00001028 Testing frameworks can use the following methods to collect information on
1029 the test:
1030
1031
1032 .. method:: countTestCases()
1033
1034 Return the number of tests represented by this test object. For
1035 :class:`TestCase` instances, this will always be ``1``.
1036
1037
1038 .. method:: defaultTestResult()
1039
1040 Return an instance of the test result class that should be used for this
1041 test case class (if no other result instance is provided to the
1042 :meth:`run` method).
1043
1044 For :class:`TestCase` instances, this will always be an instance of
1045 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1046 as necessary.
1047
1048
1049 .. method:: id()
1050
1051 Return a string identifying the specific test case. This is usually the
1052 full name of the test method, including the module and class name.
1053
1054
1055 .. method:: shortDescription()
1056
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001057 Returns a description of the test, or :const:`None` if no description
1058 has been provided. The default implementation of this method
1059 returns the first line of the test method's docstring, if available,
1060 along with the method name.
1061
Raymond Hettinger35a88362009-04-09 00:08:24 +00001062 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001063 In earlier versions this only returned the first line of the test
1064 method's docstring, if available or the :const:`None`. That led to
1065 undesirable behavior of not printing the test name when someone was
1066 thoughtful enough to write a docstring.
1067
1068
1069 .. method:: addTypeEqualityFunc(typeobj, function)
1070
1071 Registers a type specific :meth:`assertEqual` equality checking
1072 function to be called by :meth:`assertEqual` when both objects it has
1073 been asked to compare are exactly *typeobj* (not subclasses).
1074 *function* must take two positional arguments and a third msg=None
1075 keyword argument just as :meth:`assertEqual` does. It must raise
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001076 ``self.failureException`` when inequality between the first two
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001077 parameters is detected.
1078
1079 One good use of custom equality checking functions for a type
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001080 is to raise ``self.failureException`` with an error message useful
1081 for debugging the problem by explaining the inequalities in detail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001082
Raymond Hettinger35a88362009-04-09 00:08:24 +00001083 .. versionadded:: 3.1
Georg Brandl116aa622007-08-15 14:28:22 +00001084
1085
Georg Brandl7f01a132009-09-16 15:58:14 +00001086 .. method:: addCleanup(function, *args, **kwargs)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001087
1088 Add a function to be called after :meth:`tearDown` to cleanup resources
1089 used during the test. Functions will be called in reverse order to the
1090 order they are added (LIFO). They are called with any arguments and
1091 keyword arguments passed into :meth:`addCleanup` when they are
1092 added.
1093
1094 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1095 then any cleanup functions added will still be called.
1096
Georg Brandl853947a2010-01-31 18:53:23 +00001097 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001098
1099
1100 .. method:: doCleanups()
1101
1102 This method is called uncoditionally after :meth:`tearDown`, or
1103 after :meth:`setUp` if :meth:`setUp` raises an exception.
1104
1105 It is responsible for calling all the cleanup functions added by
1106 :meth:`addCleanup`. If you need cleanup functions to be called
1107 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1108 yourself.
1109
1110 :meth:`doCleanups` pops methods off the stack of cleanup
1111 functions one at a time, so it can be called at any time.
1112
Georg Brandl853947a2010-01-31 18:53:23 +00001113 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001114
1115
Georg Brandl7f01a132009-09-16 15:58:14 +00001116.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001117
1118 This class implements the portion of the :class:`TestCase` interface which
Benjamin Petersond2397752009-06-27 23:45:02 +00001119 allows the test runner to drive the test, but does not provide the methods
1120 which test code can use to check and report errors. This is used to create
1121 test cases using legacy test code, allowing it to be integrated into a
1122 :mod:`unittest`-based test framework.
Georg Brandl116aa622007-08-15 14:28:22 +00001123
1124
Benjamin Peterson52baa292009-03-24 00:56:30 +00001125.. _testsuite-objects:
1126
Benjamin Peterson52baa292009-03-24 00:56:30 +00001127Grouping tests
1128~~~~~~~~~~~~~~
1129
Georg Brandl7f01a132009-09-16 15:58:14 +00001130.. class:: TestSuite(tests=())
Georg Brandl116aa622007-08-15 14:28:22 +00001131
1132 This class represents an aggregation of individual tests cases and test suites.
1133 The class presents the interface needed by the test runner to allow it to be run
1134 as any other test case. Running a :class:`TestSuite` instance is the same as
1135 iterating over the suite, running each test individually.
1136
1137 If *tests* is given, it must be an iterable of individual test cases or other
1138 test suites that will be used to build the suite initially. Additional methods
1139 are provided to add test cases and suites to the collection later on.
1140
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001141 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1142 they do not actually implement a test. Instead, they are used to aggregate
1143 tests into groups of tests that should be run together. Some additional
1144 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001145
1146
1147 .. method:: TestSuite.addTest(test)
1148
1149 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1150
1151
1152 .. method:: TestSuite.addTests(tests)
1153
1154 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1155 instances to this test suite.
1156
Benjamin Petersond2397752009-06-27 23:45:02 +00001157 This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1158 each element.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001159
1160 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1161
1162
1163 .. method:: run(result)
1164
1165 Run the tests associated with this suite, collecting the result into the
1166 test result object passed as *result*. Note that unlike
1167 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1168 be passed in.
1169
1170
1171 .. method:: debug()
1172
1173 Run the tests associated with this suite without collecting the
1174 result. This allows exceptions raised by the test to be propagated to the
1175 caller and can be used to support running tests under a debugger.
1176
1177
1178 .. method:: countTestCases()
1179
1180 Return the number of tests represented by this test object, including all
1181 individual tests and sub-suites.
1182
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001183
1184 .. method:: __iter__()
1185
1186 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1187 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1188 that this method maybe called several times on a single suite
1189 (for example when counting tests or comparing for equality)
1190 so the tests returned must be the same for repeated iterations.
1191
Georg Brandl853947a2010-01-31 18:53:23 +00001192 .. versionchanged:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001193 In earlier versions the :class:`TestSuite` accessed tests directly rather
1194 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1195 for providing tests.
1196
Benjamin Peterson52baa292009-03-24 00:56:30 +00001197 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1198 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1199
1200
Benjamin Peterson52baa292009-03-24 00:56:30 +00001201Loading and running tests
1202~~~~~~~~~~~~~~~~~~~~~~~~~
1203
Georg Brandl116aa622007-08-15 14:28:22 +00001204.. class:: TestLoader()
1205
Benjamin Peterson52baa292009-03-24 00:56:30 +00001206 The :class:`TestLoader` class is used to create test suites from classes and
1207 modules. Normally, there is no need to create an instance of this class; the
1208 :mod:`unittest` module provides an instance that can be shared as
1209 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1210 customization of some configurable properties.
1211
1212 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001213
1214
Benjamin Peterson52baa292009-03-24 00:56:30 +00001215 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001216
Benjamin Peterson52baa292009-03-24 00:56:30 +00001217 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1218 :class:`testCaseClass`.
1219
1220
1221 .. method:: loadTestsFromModule(module)
1222
1223 Return a suite of all tests cases contained in the given module. This
1224 method searches *module* for classes derived from :class:`TestCase` and
1225 creates an instance of the class for each test method defined for the
1226 class.
1227
Georg Brandle720c0a2009-04-27 16:20:50 +00001228 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001229
1230 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1231 convenient in sharing fixtures and helper functions, defining test
1232 methods on base classes that are not intended to be instantiated
1233 directly does not play well with this method. Doing so, however, can
1234 be useful when the fixtures are different and defined in subclasses.
1235
Benjamin Petersond2397752009-06-27 23:45:02 +00001236 If a module provides a ``load_tests`` function it will be called to
1237 load the tests. This allows modules to customize test loading.
1238 This is the `load_tests protocol`_.
1239
Georg Brandl853947a2010-01-31 18:53:23 +00001240 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001241 Support for ``load_tests`` added.
1242
Benjamin Peterson52baa292009-03-24 00:56:30 +00001243
Georg Brandl7f01a132009-09-16 15:58:14 +00001244 .. method:: loadTestsFromName(name, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001245
1246 Return a suite of all tests cases given a string specifier.
1247
1248 The specifier *name* is a "dotted name" that may resolve either to a
1249 module, a test case class, a test method within a test case class, a
1250 :class:`TestSuite` instance, or a callable object which returns a
1251 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1252 applied in the order listed here; that is, a method on a possible test
1253 case class will be picked up as "a test method within a test case class",
1254 rather than "a callable object".
1255
1256 For example, if you have a module :mod:`SampleTests` containing a
1257 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1258 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
Benjamin Petersond2397752009-06-27 23:45:02 +00001259 specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1260 return a suite which will run all three test methods. Using the specifier
1261 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1262 suite which will run only the :meth:`test_two` test method. The specifier
1263 can refer to modules and packages which have not been imported; they will
1264 be imported as a side-effect.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001265
1266 The method optionally resolves *name* relative to the given *module*.
1267
1268
Georg Brandl7f01a132009-09-16 15:58:14 +00001269 .. method:: loadTestsFromNames(names, module=None)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001270
1271 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1272 than a single name. The return value is a test suite which supports all
1273 the tests defined for each name.
1274
1275
1276 .. method:: getTestCaseNames(testCaseClass)
1277
1278 Return a sorted sequence of method names found within *testCaseClass*;
1279 this should be a subclass of :class:`TestCase`.
1280
Benjamin Petersond2397752009-06-27 23:45:02 +00001281
1282 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1283
1284 Find and return all test modules from the specified start directory,
1285 recursing into subdirectories to find them. Only test files that match
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001286 *pattern* will be loaded. (Using shell style pattern matching.) Only
1287 module names that are importable (i.e. are valid Python identifiers) will
1288 be loaded.
Benjamin Petersond2397752009-06-27 23:45:02 +00001289
1290 All test modules must be importable from the top level of the project. If
1291 the start directory is not the top level directory then the top level
1292 directory must be specified separately.
1293
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001294 If importing a module fails, for example due to a syntax error, then this
1295 will be recorded as a single error and discovery will continue.
1296
Benjamin Petersond2397752009-06-27 23:45:02 +00001297 If a test package name (directory with :file:`__init__.py`) matches the
1298 pattern then the package will be checked for a ``load_tests``
1299 function. If this exists then it will be called with *loader*, *tests*,
1300 *pattern*.
1301
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001302 If load_tests exists then discovery does *not* recurse into the package,
Benjamin Petersond2397752009-06-27 23:45:02 +00001303 ``load_tests`` is responsible for loading all tests in the package.
1304
1305 The pattern is deliberately not stored as a loader attribute so that
1306 packages can continue discovery themselves. *top_level_dir* is stored so
1307 ``load_tests`` does not need to pass this argument in to
1308 ``loader.discover()``.
1309
Georg Brandl853947a2010-01-31 18:53:23 +00001310 .. versionadded:: 3.2
1311
Benjamin Petersond2397752009-06-27 23:45:02 +00001312
Benjamin Peterson52baa292009-03-24 00:56:30 +00001313 The following attributes of a :class:`TestLoader` can be configured either by
1314 subclassing or assignment on an instance:
1315
1316
1317 .. attribute:: testMethodPrefix
1318
1319 String giving the prefix of method names which will be interpreted as test
1320 methods. The default value is ``'test'``.
1321
1322 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1323 methods.
1324
1325
1326 .. attribute:: sortTestMethodsUsing
1327
1328 Function to be used to compare method names when sorting them in
1329 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1330
1331
1332 .. attribute:: suiteClass
1333
1334 Callable object that constructs a test suite from a list of tests. No
1335 methods on the resulting object are needed. The default value is the
1336 :class:`TestSuite` class.
1337
1338 This affects all the :meth:`loadTestsFrom\*` methods.
1339
1340
Benjamin Peterson52baa292009-03-24 00:56:30 +00001341.. class:: TestResult
1342
1343 This class is used to compile information about which tests have succeeded
1344 and which have failed.
1345
1346 A :class:`TestResult` object stores the results of a set of tests. The
1347 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1348 properly recorded; test authors do not need to worry about recording the
1349 outcome of tests.
1350
1351 Testing frameworks built on top of :mod:`unittest` may want access to the
1352 :class:`TestResult` object generated by running a set of tests for reporting
1353 purposes; a :class:`TestResult` instance is returned by the
1354 :meth:`TestRunner.run` method for this purpose.
1355
1356 :class:`TestResult` instances have the following attributes that will be of
1357 interest when inspecting the results of running a set of tests:
1358
1359
1360 .. attribute:: errors
1361
1362 A list containing 2-tuples of :class:`TestCase` instances and strings
1363 holding formatted tracebacks. Each tuple represents a test which raised an
1364 unexpected exception.
1365
Benjamin Peterson52baa292009-03-24 00:56:30 +00001366 .. attribute:: failures
1367
1368 A list containing 2-tuples of :class:`TestCase` instances and strings
1369 holding formatted tracebacks. Each tuple represents a test where a failure
1370 was explicitly signalled using the :meth:`TestCase.fail\*` or
1371 :meth:`TestCase.assert\*` methods.
1372
Benjamin Peterson52baa292009-03-24 00:56:30 +00001373 .. attribute:: skipped
1374
1375 A list containing 2-tuples of :class:`TestCase` instances and strings
1376 holding the reason for skipping the test.
1377
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001378 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001379
1380 .. attribute:: expectedFailures
1381
1382 A list contaning 2-tuples of :class:`TestCase` instances and strings
1383 holding formatted tracebacks. Each tuple represents a expected failures
1384 of the test case.
1385
1386 .. attribute:: unexpectedSuccesses
1387
1388 A list containing :class:`TestCase` instances that were marked as expected
1389 failures, but succeeded.
1390
1391 .. attribute:: shouldStop
1392
1393 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1394
1395
1396 .. attribute:: testsRun
1397
1398 The total number of tests run so far.
1399
1400
1401 .. method:: wasSuccessful()
1402
1403 Return :const:`True` if all tests run so far have passed, otherwise returns
1404 :const:`False`.
1405
1406
1407 .. method:: stop()
1408
1409 This method can be called to signal that the set of tests being run should
1410 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1411 :class:`TestRunner` objects should respect this flag and return without
1412 running any additional tests.
1413
1414 For example, this feature is used by the :class:`TextTestRunner` class to
1415 stop the test framework when the user signals an interrupt from the
1416 keyboard. Interactive tools which provide :class:`TestRunner`
1417 implementations can use this in a similar manner.
1418
1419 The following methods of the :class:`TestResult` class are used to maintain
1420 the internal data structures, and may be extended in subclasses to support
1421 additional reporting requirements. This is particularly useful in building
1422 tools which support interactive reporting while tests are being run.
1423
1424
1425 .. method:: startTest(test)
1426
1427 Called when the test case *test* is about to be run.
1428
1429 The default implementation simply increments the instance's :attr:`testsRun`
1430 counter.
1431
1432
1433 .. method:: stopTest(test)
1434
1435 Called after the test case *test* has been executed, regardless of the
1436 outcome.
1437
1438 The default implementation does nothing.
1439
1440
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001441 .. method:: startTestRun(test)
1442
1443 Called once before any tests are executed.
1444
Georg Brandl853947a2010-01-31 18:53:23 +00001445 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001446
1447
1448 .. method:: stopTestRun(test)
1449
Ezio Melotti176d6c42010-01-27 20:58:07 +00001450 Called once after all tests are executed.
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001451
Georg Brandl853947a2010-01-31 18:53:23 +00001452 .. versionadded:: 3.2
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001453
1454
Benjamin Peterson52baa292009-03-24 00:56:30 +00001455 .. method:: addError(test, err)
1456
1457 Called when the test case *test* raises an unexpected exception *err* is a
1458 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1459 traceback)``.
1460
1461 The default implementation appends a tuple ``(test, formatted_err)`` to
1462 the instance's :attr:`errors` attribute, where *formatted_err* is a
1463 formatted traceback derived from *err*.
1464
1465
1466 .. method:: addFailure(test, err)
1467
Benjamin Petersond2397752009-06-27 23:45:02 +00001468 Called when the test case *test* signals a failure. *err* is a tuple of
1469 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson52baa292009-03-24 00:56:30 +00001470
1471 The default implementation appends a tuple ``(test, formatted_err)`` to
1472 the instance's :attr:`failures` attribute, where *formatted_err* is a
1473 formatted traceback derived from *err*.
1474
1475
1476 .. method:: addSuccess(test)
1477
1478 Called when the test case *test* succeeds.
1479
1480 The default implementation does nothing.
1481
1482
1483 .. method:: addSkip(test, reason)
1484
1485 Called when the test case *test* is skipped. *reason* is the reason the
1486 test gave for skipping.
1487
1488 The default implementation appends a tuple ``(test, reason)`` to the
1489 instance's :attr:`skipped` attribute.
1490
1491
1492 .. method:: addExpectedFailure(test, err)
1493
1494 Called when the test case *test* fails, but was marked with the
1495 :func:`expectedFailure` decorator.
1496
1497 The default implementation appends a tuple ``(test, formatted_err)`` to
1498 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1499 is a formatted traceback derived from *err*.
1500
1501
1502 .. method:: addUnexpectedSuccess(test)
1503
1504 Called when the test case *test* was marked with the
1505 :func:`expectedFailure` decorator, but succeeded.
1506
1507 The default implementation appends the test to the instance's
1508 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001509
1510
1511.. data:: defaultTestLoader
1512
1513 Instance of the :class:`TestLoader` class intended to be shared. If no
1514 customization of the :class:`TestLoader` is needed, this instance can be used
1515 instead of repeatedly creating new instances.
1516
1517
Georg Brandl7f01a132009-09-16 15:58:14 +00001518.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001519
1520 A basic test runner implementation which prints results on standard error. It
1521 has a few configurable parameters, but is essentially very simple. Graphical
1522 applications which run test suites should provide alternate implementations.
1523
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001524 .. method:: _makeResult()
Georg Brandl116aa622007-08-15 14:28:22 +00001525
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001526 This method returns the instance of ``TestResult`` used by :meth:`run`.
1527 It is not intended to be called directly, but can be overridden in
1528 subclasses to provide a custom ``TestResult``.
1529
1530
Georg Brandl7f01a132009-09-16 15:58:14 +00001531.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001532
1533 A command-line program that runs a set of tests; this is primarily for making
1534 test modules conveniently executable. The simplest use for this function is to
1535 include the following line at the end of a test script::
1536
1537 if __name__ == '__main__':
1538 unittest.main()
1539
Benjamin Petersond2397752009-06-27 23:45:02 +00001540 You can run tests with more detailed information by passing in the verbosity
1541 argument::
1542
1543 if __name__ == '__main__':
1544 unittest.main(verbosity=2)
1545
Georg Brandl116aa622007-08-15 14:28:22 +00001546 The *testRunner* argument can either be a test runner class or an already
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001547 created instance of it. By default ``main`` calls :func:`sys.exit` with
1548 an exit code indicating success or failure of the tests run.
1549
1550 ``main`` supports being used from the interactive interpreter by passing in the
1551 argument ``exit=False``. This displays the result on standard output without
1552 calling :func:`sys.exit`::
1553
1554 >>> from unittest import main
1555 >>> main(module='test_module', exit=False)
1556
1557 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1558 This stores the result of the tests run as the ``result`` attribute.
1559
Georg Brandl853947a2010-01-31 18:53:23 +00001560 .. versionchanged:: 3.2
Benjamin Petersond2397752009-06-27 23:45:02 +00001561 The ``exit`` and ``verbosity`` parameters were added.
1562
1563
1564load_tests Protocol
1565###################
1566
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001567
Georg Brandl853947a2010-01-31 18:53:23 +00001568.. versionadded:: 3.2
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001569
1570
Benjamin Petersond2397752009-06-27 23:45:02 +00001571Modules or packages can customize how tests are loaded from them during normal
1572test runs or test discovery by implementing a function called ``load_tests``.
1573
1574If a test module defines ``load_tests`` it will be called by
1575:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1576
1577 load_tests(loader, standard_tests, None)
1578
1579It should return a :class:`TestSuite`.
1580
1581*loader* is the instance of :class:`TestLoader` doing the loading.
1582*standard_tests* are the tests that would be loaded by default from the
1583module. It is common for test modules to only want to add or remove tests
1584from the standard set of tests.
1585The third argument is used when loading packages as part of test discovery.
1586
1587A typical ``load_tests`` function that loads tests from a specific set of
1588:class:`TestCase` classes may look like::
1589
1590 test_cases = (TestCase1, TestCase2, TestCase3)
1591
1592 def load_tests(loader, tests, pattern):
1593 suite = TestSuite()
1594 for test_class in test_cases:
1595 tests = loader.loadTestsFromTestCase(test_class)
1596 suite.addTests(tests)
1597 return suite
1598
1599If discovery is started, either from the command line or by calling
1600:meth:`TestLoader.discover`, with a pattern that matches a package
1601name then the package :file:`__init__.py` will be checked for ``load_tests``.
1602
1603.. note::
1604
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001605 The default pattern is 'test*.py'. This matches all Python files
Benjamin Petersond2397752009-06-27 23:45:02 +00001606 that start with 'test' but *won't* match any test directories.
1607
1608 A pattern like 'test*' will match test packages as well as
1609 modules.
1610
1611If the package :file:`__init__.py` defines ``load_tests`` then it will be
1612called and discovery not continued into the package. ``load_tests``
1613is called with the following arguments::
1614
1615 load_tests(loader, standard_tests, pattern)
1616
1617This should return a :class:`TestSuite` representing all the tests
1618from the package. (``standard_tests`` will only contain tests
1619collected from :file:`__init__.py`.)
1620
1621Because the pattern is passed into ``load_tests`` the package is free to
1622continue (and potentially modify) test discovery. A 'do nothing'
1623``load_tests`` function for a test package would look like::
1624
1625 def load_tests(loader, standard_tests, pattern):
1626 # top level directory cached on loader instance
1627 this_dir = os.path.dirname(__file__)
1628 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1629 standard_tests.addTests(package_tests)
1630 return standard_tests