blob: bc26f05e8aa4f757c900945f93a01dbbfb1d2b8a [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
82 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
83 Kent Beck's original paper on testing frameworks using the pattern shared by
84 :mod:`unittest`.
85
Raymond Hettinger21b617b2009-03-24 00:17:11 +000086 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
87 Third-party unittest frameworks with a lighter-weight syntax
88 for writing tests. For example, ``assert func(10) == 42``.
89
90 `python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
91 Tools for creating mock test objects (objects simulating external resources).
Georg Brandl8ec7f652007-08-15 14:28:01 +000092
Michael Foordb4a81c82009-05-29 20:33:46 +000093
94.. _unittest-command-line-interface:
95
Michael Foord5d31e052009-05-11 17:59:43 +000096Command Line Interface
97----------------------
98
99The unittest module can be used from the command line to run tests from
100modules, classes or even individual test methods::
101
102 python -m unittest test_module1 test_module2
103 python -m unittest test_module.TestClass
104 python -m unittest test_module.TestClass.test_method
105
Michael Foordb4a81c82009-05-29 20:33:46 +0000106You can pass in a list with any combination of module names, and fully
107qualified class or method names.
Michael Foord5d31e052009-05-11 17:59:43 +0000108
109You can run tests with more detail (higher verbosity) by passing in the -v flag::
110
111 python-m unittest -v test_module
112
113For a list of all the command line options::
114
115 python -m unittest -h
116
Michael Foordb4a81c82009-05-29 20:33:46 +0000117.. versionchanged:: 2.7
118 In earlier versions it was only possible to run individual test methods and
119 not modules or classes.
120
121The command line can also be used for test discovery, for running all of the
122tests in a project or just a subset.
123
124
125.. _unittest-test-discovery:
126
127Test Discovery
128--------------
129
130.. versionadded:: 2.7
131
132unittest supports simple test discovery. For a project's tests to be
133compatible with test discovery they must all be importable from the top level
134directory of the project; i.e. they must all be in Python packages.
135
136Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
137used from the command line. The basic command line usage is::
138
139 cd project_directory
140 python -m unittest discover
141
142The ``discover`` sub-command has the following options:
143
144 -v, --verbose Verbose output
145 -s directory Directory to start discovery ('.' default)
146 -p pattern Pattern to match test files ('test*.py' default)
147 -t directory Top level directory of project (default to
148 start directory)
149
150The -s, -p, & -t options can be passsed in as positional arguments. The
151following two command lines are equivalent::
152
153 python -m unittest -s project_directory -p '*_test.py'
154 python -m unittest project_directory '*_test.py'
155
156Test modules and packages can customize test loading and discovery by through
157the `load_tests protocol`_.
Michael Foord5d31e052009-05-11 17:59:43 +0000158
Georg Brandl8ec7f652007-08-15 14:28:01 +0000159.. _unittest-minimal-example:
160
161Basic example
162-------------
163
164The :mod:`unittest` module provides a rich set of tools for constructing and
165running tests. This section demonstrates that a small subset of the tools
166suffice to meet the needs of most users.
167
168Here is a short script to test three functions from the :mod:`random` module::
169
170 import random
171 import unittest
172
173 class TestSequenceFunctions(unittest.TestCase):
174
175 def setUp(self):
176 self.seq = range(10)
177
Benjamin Peterson99721e02009-03-23 23:10:14 +0000178 def test_shuffle(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179 # make sure the shuffled sequence does not lose any elements
180 random.shuffle(self.seq)
181 self.seq.sort()
182 self.assertEqual(self.seq, range(10))
183
Benjamin Peterson99721e02009-03-23 23:10:14 +0000184 def test_choice(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000185 element = random.choice(self.seq)
186 self.assert_(element in self.seq)
187
Benjamin Peterson99721e02009-03-23 23:10:14 +0000188 def test_sample(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000189 self.assertRaises(ValueError, random.sample, self.seq, 20)
190 for element in random.sample(self.seq, 5):
191 self.assert_(element in self.seq)
192
193 if __name__ == '__main__':
194 unittest.main()
195
Benjamin Peterson99721e02009-03-23 23:10:14 +0000196A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl8ec7f652007-08-15 14:28:01 +0000197individual tests are defined with methods whose names start with the letters
198``test``. This naming convention informs the test runner about which methods
199represent tests.
200
Benjamin Peterson99721e02009-03-23 23:10:14 +0000201The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
202expected result; :meth:`~TestCase.assert_` to verify a condition; or
203:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
204These methods are used instead of the :keyword:`assert` statement so the test
205runner can accumulate all test results and produce a report.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000206
Benjamin Peterson99721e02009-03-23 23:10:14 +0000207When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
208method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
209defined, the test runner will invoke that method after each test. In the
210example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
211test.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000212
213The final block shows a simple way to run the tests. :func:`unittest.main`
214provides a command line interface to the test script. When run from the command
215line, the above script produces an output that looks like this::
216
217 ...
218 ----------------------------------------------------------------------
219 Ran 3 tests in 0.000s
220
221 OK
222
223Instead of :func:`unittest.main`, there are other ways to run the tests with a
224finer level of control, less terse output, and no requirement to be run from the
225command line. For example, the last two lines may be replaced with::
226
227 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
228 unittest.TextTestRunner(verbosity=2).run(suite)
229
230Running the revised script from the interpreter or another script produces the
231following output::
232
233 testchoice (__main__.TestSequenceFunctions) ... ok
234 testsample (__main__.TestSequenceFunctions) ... ok
235 testshuffle (__main__.TestSequenceFunctions) ... ok
236
237 ----------------------------------------------------------------------
238 Ran 3 tests in 0.110s
239
240 OK
241
242The above examples show the most commonly used :mod:`unittest` features which
243are sufficient to meet many everyday testing needs. The remainder of the
244documentation explores the full feature set from first principles.
245
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246.. _organizing-tests:
247
248Organizing test code
249--------------------
250
251The basic building blocks of unit testing are :dfn:`test cases` --- single
252scenarios that must be set up and checked for correctness. In :mod:`unittest`,
253test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
254class. To make your own test cases you must write subclasses of
255:class:`TestCase`, or use :class:`FunctionTestCase`.
256
257An instance of a :class:`TestCase`\ -derived class is an object that can
258completely run a single test method, together with optional set-up and tidy-up
259code.
260
261The testing code of a :class:`TestCase` instance should be entirely self
262contained, such that it can be run either in isolation or in arbitrary
263combination with any number of other test cases.
264
Benjamin Peterson99721e02009-03-23 23:10:14 +0000265The simplest :class:`TestCase` subclass will simply override the
266:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000267
268 import unittest
269
270 class DefaultWidgetSizeTestCase(unittest.TestCase):
271 def runTest(self):
272 widget = Widget('The widget')
273 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
274
Gregory P. Smith28399852009-03-31 16:54:10 +0000275Note that in order to test something, we use the one of the :meth:`assert\*`
276methods provided by the :class:`TestCase` base class. If the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277test fails, an exception will be raised, and :mod:`unittest` will identify the
278test case as a :dfn:`failure`. Any other exceptions will be treated as
279:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
280caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
281caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
282function call.
283
284The way to run a test case will be described later. For now, note that to
285construct an instance of such a test case, we call its constructor without
286arguments::
287
288 testCase = DefaultWidgetSizeTestCase()
289
290Now, such test cases can be numerous, and their set-up can be repetitive. In
291the above case, constructing a :class:`Widget` in each of 100 Widget test case
292subclasses would mean unsightly duplication.
293
294Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson99721e02009-03-23 23:10:14 +0000295:meth:`~TestCase.setUp`, which the testing framework will automatically call for
296us when we run the test::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000297
298 import unittest
299
300 class SimpleWidgetTestCase(unittest.TestCase):
301 def setUp(self):
302 self.widget = Widget('The widget')
303
304 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
305 def runTest(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000306 self.assertTrue(self.widget.size() == (50,50),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307 'incorrect default size')
308
309 class WidgetResizeTestCase(SimpleWidgetTestCase):
310 def runTest(self):
311 self.widget.resize(100,150)
Gregory P. Smith28399852009-03-31 16:54:10 +0000312 self.assertTrue(self.widget.size() == (100,150),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000313 'wrong size after resize')
314
Benjamin Peterson99721e02009-03-23 23:10:14 +0000315If the :meth:`~TestCase.setUp` method raises an exception while the test is
316running, the framework will consider the test to have suffered an error, and the
317:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000318
Benjamin Peterson99721e02009-03-23 23:10:14 +0000319Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
320after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000321
322 import unittest
323
324 class SimpleWidgetTestCase(unittest.TestCase):
325 def setUp(self):
326 self.widget = Widget('The widget')
327
328 def tearDown(self):
329 self.widget.dispose()
330 self.widget = None
331
Benjamin Peterson99721e02009-03-23 23:10:14 +0000332If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
333be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000334
335Such a working environment for the testing code is called a :dfn:`fixture`.
336
337Often, many small test cases will use the same fixture. In this case, we would
338end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
339classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000340discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
341mechanism::
342
343 import unittest
344
345 class WidgetTestCase(unittest.TestCase):
346 def setUp(self):
347 self.widget = Widget('The widget')
348
349 def tearDown(self):
350 self.widget.dispose()
351 self.widget = None
352
353 def testDefaultSize(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000354 self.assertTrue(self.widget.size() == (50,50),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000355 'incorrect default size')
356
357 def testResize(self):
358 self.widget.resize(100,150)
Gregory P. Smith28399852009-03-31 16:54:10 +0000359 self.assertTrue(self.widget.size() == (100,150),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000360 'wrong size after resize')
361
Benjamin Peterson99721e02009-03-23 23:10:14 +0000362Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
363provided two different test methods. Class instances will now each run one of
364the :meth:`test\*` methods, with ``self.widget`` created and destroyed
365separately for each instance. When creating an instance we must specify the
366test method it is to run. We do this by passing the method name in the
367constructor::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000368
369 defaultSizeTestCase = WidgetTestCase('testDefaultSize')
370 resizeTestCase = WidgetTestCase('testResize')
371
372Test case instances are grouped together according to the features they test.
373:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
374represented by :mod:`unittest`'s :class:`TestSuite` class::
375
376 widgetTestSuite = unittest.TestSuite()
377 widgetTestSuite.addTest(WidgetTestCase('testDefaultSize'))
378 widgetTestSuite.addTest(WidgetTestCase('testResize'))
379
380For the ease of running tests, as we will see later, it is a good idea to
381provide in each test module a callable object that returns a pre-built test
382suite::
383
384 def suite():
385 suite = unittest.TestSuite()
386 suite.addTest(WidgetTestCase('testDefaultSize'))
387 suite.addTest(WidgetTestCase('testResize'))
388 return suite
389
390or even::
391
392 def suite():
393 tests = ['testDefaultSize', 'testResize']
394
395 return unittest.TestSuite(map(WidgetTestCase, tests))
396
397Since it is a common pattern to create a :class:`TestCase` subclass with many
398similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
399class that can be used to automate the process of creating a test suite and
400populating it with individual tests. For example, ::
401
402 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
403
404will create a test suite that will run ``WidgetTestCase.testDefaultSize()`` and
405``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method
406name prefix to identify test methods automatically.
407
408Note that the order in which the various test cases will be run is determined by
409sorting the test function names with the built-in :func:`cmp` function.
410
411Often it is desirable to group suites of test cases together, so as to run tests
412for the whole system at once. This is easy, since :class:`TestSuite` instances
413can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
414added to a :class:`TestSuite`::
415
416 suite1 = module1.TheTestSuite()
417 suite2 = module2.TheTestSuite()
418 alltests = unittest.TestSuite([suite1, suite2])
419
420You can place the definitions of test cases and test suites in the same modules
421as the code they are to test (such as :file:`widget.py`), but there are several
422advantages to placing the test code in a separate module, such as
423:file:`test_widget.py`:
424
425* The test module can be run standalone from the command line.
426
427* The test code can more easily be separated from shipped code.
428
429* There is less temptation to change test code to fit the code it tests without
430 a good reason.
431
432* Test code should be modified much less frequently than the code it tests.
433
434* Tested code can be refactored more easily.
435
436* Tests for modules written in C must be in separate modules anyway, so why not
437 be consistent?
438
439* If the testing strategy changes, there is no need to change the source code.
440
441
442.. _legacy-unit-tests:
443
444Re-using old test code
445----------------------
446
447Some users will find that they have existing test code that they would like to
448run from :mod:`unittest`, without converting every old test function to a
449:class:`TestCase` subclass.
450
451For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
452This subclass of :class:`TestCase` can be used to wrap an existing test
453function. Set-up and tear-down functions can also be provided.
454
455Given the following test function::
456
457 def testSomething():
458 something = makeSomething()
459 assert something.name is not None
460 # ...
461
462one can create an equivalent test case instance as follows::
463
464 testcase = unittest.FunctionTestCase(testSomething)
465
466If there are additional set-up and tear-down methods that should be called as
467part of the test case's operation, they can also be provided like so::
468
469 testcase = unittest.FunctionTestCase(testSomething,
470 setUp=makeSomethingDB,
471 tearDown=deleteSomethingDB)
472
473To make migrating existing test suites easier, :mod:`unittest` supports tests
474raising :exc:`AssertionError` to indicate test failure. However, it is
475recommended that you use the explicit :meth:`TestCase.fail\*` and
476:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
477may treat :exc:`AssertionError` differently.
478
479.. note::
480
481 Even though :class:`FunctionTestCase` can be used to quickly convert an existing
482 test base over to a :mod:`unittest`\ -based system, this approach is not
483 recommended. Taking the time to set up proper :class:`TestCase` subclasses will
484 make future test refactorings infinitely easier.
485
Benjamin Peterson99721e02009-03-23 23:10:14 +0000486In some cases, the existing tests may have been written using the :mod:`doctest`
487module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
488automatically build :class:`unittest.TestSuite` instances from the existing
489:mod:`doctest`\ -based tests.
490
Georg Brandl8ec7f652007-08-15 14:28:01 +0000491
Benjamin Peterson692428e2009-03-23 21:50:21 +0000492.. _unittest-skipping:
493
494Skipping tests and expected failures
495------------------------------------
496
497Unittest supports skipping individual test methods and even whole classes of
498tests. In addition, it supports marking a test as a "expected failure," a test
499that is broken and will fail, but shouldn't be counted as a failure on a
500:class:`TestResult`.
501
502Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
503or one of its conditional variants.
504
505Basic skipping looks like this: ::
506
507 class MyTestCase(unittest.TestCase):
508
509 @unittest.skip("demonstrating skipping")
510 def test_nothing(self):
511 self.fail("shouldn't happen")
512
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000513 @unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version")
514 def test_format(self):
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000515 # Tests that work for only a certain version of the library.
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000516 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 Peterson692428e2009-03-23 21:50:21 +0000523This is the output of running the example above in verbose mode: ::
524
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000525 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000526 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000527 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000528
529 ----------------------------------------------------------------------
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000530 Ran 3 tests in 0.005s
531
532 OK (skipped=3)
Benjamin Peterson692428e2009-03-23 21:50:21 +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 Peterson31b78062009-03-23 23:13:36 +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 Peterson692428e2009-03-23 21:50:21 +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 Brandl8ec7f652007-08-15 14:28:01 +0000581.. _unittest-contents:
582
583Classes and functions
584---------------------
585
Benjamin Peterson99721e02009-03-23 23:10:14 +0000586This section describes in depth the API of :mod:`unittest`.
587
588
589.. _testcase-objects:
590
591Test cases
592~~~~~~~~~~
Georg Brandl8ec7f652007-08-15 14:28:01 +0000593
594.. class:: TestCase([methodName])
595
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 Peterson99721e02009-03-23 23:10:14 +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
645 .. method:: run([result])
646
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
649 object is created (by calling the :meth:`defaultTestCase` method) and
650 used; this result object is not returned to :meth:`run`'s caller.
651
652 The same effect may be had by simply calling the :class:`TestCase`
653 instance.
654
655
Benjamin Peterson47d97382009-03-26 20:05:50 +0000656 .. method:: skipTest(reason)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000657
Benjamin Peterson31b78062009-03-23 23:13:36 +0000658 Calling this during the a test method or :meth:`setUp` skips the current
659 test. See :ref:`unittest-skipping` for more information.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000660
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
Gregory P. Smith28399852009-03-31 16:54:10 +0000672 .. method:: assertTrue(expr[, msg])
673 assert_(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000674 failUnless(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000675
Georg Brandl64034bb2009-04-25 14:51:31 +0000676 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson99721e02009-03-23 23:10:14 +0000677 will be *msg* if given, otherwise it will be :const:`None`.
678
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000679 .. deprecated:: 2.7
680 :meth:`failUnless`.
681
Benjamin Peterson99721e02009-03-23 23:10:14 +0000682
683 .. method:: assertEqual(first, second[, msg])
684 failUnlessEqual(first, second[, msg])
685
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
Gregory P. Smith28399852009-03-31 16:54:10 +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
698 .. versionchanged:: 2.7
699 Added the automatic calling of type specific equality function.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000700
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000701 .. deprecated:: 2.7
702 :meth:`failUnlessEqual`.
703
Benjamin Peterson99721e02009-03-23 23:10:14 +0000704
705 .. method:: assertNotEqual(first, second[, msg])
706 failIfEqual(first, second[, msg])
707
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
Gregory P. Smith28399852009-03-31 16:54:10 +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 Peterson99721e02009-03-23 23:10:14 +0000712 default value for *msg* can be computed to include representations of both
713 *first* and *second*.
714
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000715 .. deprecated:: 2.7
716 :meth:`failIfEqual`.
717
Benjamin Peterson99721e02009-03-23 23:10:14 +0000718
719 .. method:: assertAlmostEqual(first, second[, places[, msg]])
720 failUnlessAlmostEqual(first, second[, places[, msg]])
721
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
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000731 .. deprecated:: 2.7
732 :meth:`failUnlessAlmostEqual`.
733
Benjamin Peterson99721e02009-03-23 23:10:14 +0000734
735 .. method:: assertNotAlmostEqual(first, second[, places[, msg]])
736 failIfAlmostEqual(first, second[, places[, msg]])
737
738 Test that *first* and *second* are not approximately equal by computing
739 the difference, rounding to the given number of decimal *places* (default
740 7), and comparing to zero.
741
742 Note that comparing a given number of decimal places is not the same as
743 comparing a given number of significant digits. If the values do not
744 compare equal, the test will fail with the explanation given by *msg*, or
745 :const:`None`.
746
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000747 .. deprecated:: 2.7
748 :meth:`failIfAlmostEqual`.
749
Benjamin Peterson99721e02009-03-23 23:10:14 +0000750
Gregory P. Smith28399852009-03-31 16:54:10 +0000751 .. method:: assertGreater(first, second, msg=None)
752 assertGreaterEqual(first, second, msg=None)
753 assertLess(first, second, msg=None)
754 assertLessEqual(first, second, msg=None)
755
756 Test that *first* is respectively >, >=, < or <= than *second* depending
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000757 on the method name. If not, the test will fail with an explanation
Gregory P. Smith28399852009-03-31 16:54:10 +0000758 or with the explanation given by *msg*::
759
760 >>> self.assertGreaterEqual(3, 4)
761 AssertionError: "3" unexpectedly not greater than or equal to "4"
762
763 .. versionadded:: 2.7
764
765
766 .. method:: assertMultiLineEqual(self, first, second, msg=None)
767
768 Test that the multiline string *first* is equal to the string *second*.
769 When not equal a diff of the two strings highlighting the differences
770 will be included in the error message.
771
772 If specified *msg* will be used as the error message on failure.
773
774 .. versionadded:: 2.7
775
776
777 .. method:: assertRegexpMatches(text, regexp[, msg=None]):
778
779 Verifies that a *regexp* search matches *text*. Fails with an error
780 message including the pattern and the *text*. *regexp* may be
781 a regular expression object or a string containing a regular expression
782 suitable for use by :func:`re.search`.
783
784 .. versionadded:: 2.7
785
786
787 .. method:: assertIn(first, second, msg=None)
788 assertNotIn(first, second, msg=None)
789
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000790 Tests that *first* is or is not in *second* with an explanatory error
Gregory P. Smith28399852009-03-31 16:54:10 +0000791 message as appropriate.
792
793 If specified *msg* will be used as the error message on failure.
794
795 .. versionadded:: 2.7
796
797
798 .. method:: assertSameElements(expected, actual, msg=None)
799
800 Test that sequence *expected* contains the same elements as *actual*.
801 When they don't an error message listing the differences between the
802 sequences will be generated.
803
804 If specified *msg* will be used as the error message on failure.
805
806 .. versionadded:: 2.7
807
808
809 .. method:: assertSetEqual(set1, set2, msg=None)
810
811 Tests that two sets are equal. If not, an error message is constructed
812 that lists the differences between the sets.
813
814 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
815 method.
816
817 If specified *msg* will be used as the error message on failure.
818
819 .. versionadded:: 2.7
820
821
822 .. method:: assertDictEqual(expected, actual, msg=None)
823
824 Test that two dictionaries are equal. If not, an error message is
825 constructed that shows the differences in the dictionaries.
826
827 If specified *msg* will be used as the error message on failure.
828
829 .. versionadded:: 2.7
830
831
832 .. method:: assertDictContainsSubset(expected, actual, msg=None)
833
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000834 Tests whether the key/value pairs in dictionary *actual* are a
Gregory P. Smith28399852009-03-31 16:54:10 +0000835 superset of those in *expected*. If not, an error message listing
836 the missing keys and mismatched values is generated.
837
838 If specified *msg* will be used as the error message on failure.
839
840 .. versionadded:: 2.7
841
842
843 .. method:: assertListEqual(list1, list2, msg=None)
844 assertTupleEqual(tuple1, tuple2, msg=None)
845
846 Tests that two lists or tuples are equal. If not an error message is
847 constructed that shows only the differences between the two. An error
848 is also raised if either of the parameters are of the wrong type.
849
850 If specified *msg* will be used as the error message on failure.
851
852 .. versionadded:: 2.7
853
854
855 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
856
857 Tests that two sequences are equal. If a *seq_type* is supplied, both
858 *seq1* and *seq2* must be instances of *seq_type* or a failure will
859 be raised. If the sequences are different an error message is
860 constructed that shows the difference between the two.
861
862 If specified *msg* will be used as the error message on failure.
863
864 This method is used to implement :meth:`assertListEqual` and
865 :meth:`assertTupleEqual`.
866
867 .. versionadded:: 2.7
868
869
Benjamin Peterson99721e02009-03-23 23:10:14 +0000870 .. method:: assertRaises(exception[, callable, ...])
871 failUnlessRaises(exception[, callable, ...])
872
873 Test that an exception is raised when *callable* is called with any
874 positional or keyword arguments that are also passed to
875 :meth:`assertRaises`. The test passes if *exception* is raised, is an
876 error if another exception is raised, or fails if no exception is raised.
877 To catch any of a group of exceptions, a tuple containing the exception
878 classes may be passed as *exception*.
879
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000880 If *callable* is omitted or None, returns a context manager so that the
881 code under test can be written inline rather than as a function::
882
883 with self.failUnlessRaises(some_error_class):
884 do_something()
885
Benjamin Peterson99721e02009-03-23 23:10:14 +0000886 .. versionchanged:: 2.7
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000887 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000888
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000889 .. deprecated:: 2.7
890 :meth:`failUnlessRaises`.
891
Benjamin Peterson99721e02009-03-23 23:10:14 +0000892
Gregory P. Smith28399852009-03-31 16:54:10 +0000893 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000894
Gregory P. Smith28399852009-03-31 16:54:10 +0000895 Like :meth:`assertRaises` but also tests that *regexp* matches
896 on the string representation of the raised exception. *regexp* may be
897 a regular expression object or a string containing a regular expression
898 suitable for use by :func:`re.search`. Examples::
899
900 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
901 int, 'XYZ')
902
903 or::
904
905 with self.assertRaisesRegexp(ValueError, 'literal'):
906 int('XYZ')
907
908 .. versionadded:: 2.7
909
910
911 .. method:: assertIsNone(expr[, msg])
912
913 This signals a test failure if *expr* is not None.
914
915 .. versionadded:: 2.7
916
917
918 .. method:: assertIsNotNone(expr[, msg])
919
920 The inverse of the :meth:`assertIsNone` method.
921 This signals a test failure if *expr* is None.
922
923 .. versionadded:: 2.7
924
925
Michael Foordf2dfef12009-04-05 19:19:28 +0000926 .. method:: assertIs(expr1, expr2[, msg])
927
928 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
929 object.
930
931 .. versionadded:: 2.7
932
933
934 .. method:: assertIsNot(expr1, expr2[, msg])
935
936 The inverse of the :meth:`assertIs` method.
937 This signals a test failure if *expr1* and *expr2* evaluate to the same
938 object.
939
940 .. versionadded:: 2.7
941
942
Gregory P. Smith28399852009-03-31 16:54:10 +0000943 .. method:: assertFalse(expr[, msg])
944 failIf(expr[, msg])
945
946 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000947 This signals a test failure if *expr* is true, with *msg* or :const:`None`
948 for the error message.
949
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000950 .. deprecated:: 2.7
951 :meth:`failIf`.
952
Benjamin Peterson99721e02009-03-23 23:10:14 +0000953
954 .. method:: fail([msg])
955
956 Signals a test failure unconditionally, with *msg* or :const:`None` for
957 the error message.
958
959
960 .. attribute:: failureException
961
962 This class attribute gives the exception raised by the test method. If a
963 test framework needs to use a specialized exception, possibly to carry
964 additional information, it must subclass this exception in order to "play
965 fair" with the framework. The initial value of this attribute is
966 :exc:`AssertionError`.
967
Michael Foord345b2fe2009-04-02 03:20:38 +0000968
969 .. attribute:: longMessage
970
971 If set to True then any explicit failure message you pass in to the
972 assert methods will be appended to the end of the normal failure message.
973 The normal messages contain useful information about the objects involved,
974 for example the message from assertEqual shows you the repr of the two
975 unequal objects. Setting this attribute to True allows you to have a
976 custom error message in addition to the normal one.
977
978 This attribute defaults to False, meaning that a custom message passed
979 to an assert method will silence the normal message.
980
981 The class setting can be overridden in individual tests by assigning an
982 instance attribute to True or False before calling the assert methods.
983
984 .. versionadded:: 2.7
985
986
Benjamin Peterson99721e02009-03-23 23:10:14 +0000987 Testing frameworks can use the following methods to collect information on
988 the test:
989
990
991 .. method:: countTestCases()
992
993 Return the number of tests represented by this test object. For
994 :class:`TestCase` instances, this will always be ``1``.
995
996
997 .. method:: defaultTestResult()
998
999 Return an instance of the test result class that should be used for this
1000 test case class (if no other result instance is provided to the
1001 :meth:`run` method).
1002
1003 For :class:`TestCase` instances, this will always be an instance of
1004 :class:`TestResult`; subclasses of :class:`TestCase` should override this
1005 as necessary.
1006
1007
1008 .. method:: id()
1009
1010 Return a string identifying the specific test case. This is usually the
1011 full name of the test method, including the module and class name.
1012
1013
1014 .. method:: shortDescription()
1015
Gregory P. Smith28399852009-03-31 16:54:10 +00001016 Returns a description of the test, or :const:`None` if no description
1017 has been provided. The default implementation of this method
1018 returns the first line of the test method's docstring, if available,
1019 along with the method name.
1020
1021 .. versionchanged:: 2.7
Gregory P. Smith28399852009-03-31 16:54:10 +00001022 In earlier versions this only returned the first line of the test
1023 method's docstring, if available or the :const:`None`. That led to
1024 undesirable behavior of not printing the test name when someone was
1025 thoughtful enough to write a docstring.
1026
1027
1028 .. method:: addTypeEqualityFunc(typeobj, function)
1029
1030 Registers a type specific :meth:`assertEqual` equality checking
1031 function to be called by :meth:`assertEqual` when both objects it has
1032 been asked to compare are exactly *typeobj* (not subclasses).
1033 *function* must take two positional arguments and a third msg=None
1034 keyword argument just as :meth:`assertEqual` does. It must raise
Andrew M. Kuchling59631852009-04-09 11:23:36 +00001035 ``self.failureException`` when inequality between the first two
Gregory P. Smith28399852009-03-31 16:54:10 +00001036 parameters is detected.
1037
1038 One good use of custom equality checking functions for a type
Andrew M. Kuchling59631852009-04-09 11:23:36 +00001039 is to raise ``self.failureException`` with an error message useful
1040 for debugging the problem by explaining the inequalities in detail.
Gregory P. Smith28399852009-03-31 16:54:10 +00001041
1042 .. versionadded:: 2.7
Georg Brandl8ec7f652007-08-15 14:28:01 +00001043
1044
Michael Foorde2fb98f2009-05-02 20:15:05 +00001045 .. method:: addCleanup(function[, *args[, **kwargs]])
1046
1047 Add a function to be called after :meth:`tearDown` to cleanup resources
1048 used during the test. Functions will be called in reverse order to the
1049 order they are added (LIFO). They are called with any arguments and
1050 keyword arguments passed into :meth:`addCleanup` when they are
1051 added.
1052
1053 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1054 then any cleanup functions added will still be called.
1055
1056 .. versionadded:: 2.7
1057
1058
1059 .. method:: doCleanups()
1060
1061 This method is called uncoditionally after :meth:`tearDown`, or
1062 after :meth:`setUp` if :meth:`setUp` raises an exception.
1063
1064 It is responsible for calling all the cleanup functions added by
1065 :meth:`addCleanup`. If you need cleanup functions to be called
1066 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1067 yourself.
1068
1069 :meth:`doCleanups` pops methods off the stack of cleanup
1070 functions one at a time, so it can be called at any time.
1071
1072 .. versionadded:: 2.7
1073
1074
Georg Brandl8ec7f652007-08-15 14:28:01 +00001075.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
1076
1077 This class implements the portion of the :class:`TestCase` interface which
1078 allows the test runner to drive the test, but does not provide the methods which
1079 test code can use to check and report errors. This is used to create test cases
1080 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
1081 -based test framework.
1082
1083
Benjamin Peterson99721e02009-03-23 23:10:14 +00001084.. _testsuite-objects:
1085
1086Grouping tests
1087~~~~~~~~~~~~~~
1088
Georg Brandl8ec7f652007-08-15 14:28:01 +00001089.. class:: TestSuite([tests])
1090
1091 This class represents an aggregation of individual tests cases and test suites.
1092 The class presents the interface needed by the test runner to allow it to be run
1093 as any other test case. Running a :class:`TestSuite` instance is the same as
1094 iterating over the suite, running each test individually.
1095
1096 If *tests* is given, it must be an iterable of individual test cases or other
1097 test suites that will be used to build the suite initially. Additional methods
1098 are provided to add test cases and suites to the collection later on.
1099
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001100 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1101 they do not actually implement a test. Instead, they are used to aggregate
1102 tests into groups of tests that should be run together. Some additional
1103 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson99721e02009-03-23 23:10:14 +00001104
1105
1106 .. method:: TestSuite.addTest(test)
1107
1108 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1109
1110
1111 .. method:: TestSuite.addTests(tests)
1112
1113 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1114 instances to this test suite.
1115
1116 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
1117 element.
1118
1119 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1120
1121
1122 .. method:: run(result)
1123
1124 Run the tests associated with this suite, collecting the result into the
1125 test result object passed as *result*. Note that unlike
1126 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1127 be passed in.
1128
1129
1130 .. method:: debug()
1131
1132 Run the tests associated with this suite without collecting the
1133 result. This allows exceptions raised by the test to be propagated to the
1134 caller and can be used to support running tests under a debugger.
1135
1136
1137 .. method:: countTestCases()
1138
1139 Return the number of tests represented by this test object, including all
1140 individual tests and sub-suites.
1141
Georg Brandl9bc66822009-04-27 17:04:23 +00001142
1143 .. method:: __iter__()
1144
1145 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1146 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1147 that this method maybe called several times on a single suite
1148 (for example when counting tests or comparing for equality)
1149 so the tests returned must be the same for repeated iterations.
1150
1151 .. versionchanged:: 2.7
1152 In earlier versions the :class:`TestSuite` accessed tests directly rather
1153 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1154 for providing tests.
1155
Benjamin Peterson99721e02009-03-23 23:10:14 +00001156 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1157 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1158
1159
Benjamin Peterson99721e02009-03-23 23:10:14 +00001160Loading and running tests
1161~~~~~~~~~~~~~~~~~~~~~~~~~
1162
Georg Brandl8ec7f652007-08-15 14:28:01 +00001163.. class:: TestLoader()
1164
Benjamin Peterson99721e02009-03-23 23:10:14 +00001165 The :class:`TestLoader` class is used to create test suites from classes and
1166 modules. Normally, there is no need to create an instance of this class; the
1167 :mod:`unittest` module provides an instance that can be shared as
1168 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1169 customization of some configurable properties.
1170
1171 :class:`TestLoader` objects have the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001172
1173
Benjamin Peterson99721e02009-03-23 23:10:14 +00001174 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001175
Benjamin Peterson99721e02009-03-23 23:10:14 +00001176 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1177 :class:`testCaseClass`.
1178
1179
1180 .. method:: loadTestsFromModule(module)
1181
1182 Return a suite of all tests cases contained in the given module. This
1183 method searches *module* for classes derived from :class:`TestCase` and
1184 creates an instance of the class for each test method defined for the
1185 class.
1186
Georg Brandl16a57f62009-04-27 15:29:09 +00001187 .. note::
Benjamin Peterson99721e02009-03-23 23:10:14 +00001188
1189 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1190 convenient in sharing fixtures and helper functions, defining test
1191 methods on base classes that are not intended to be instantiated
1192 directly does not play well with this method. Doing so, however, can
1193 be useful when the fixtures are different and defined in subclasses.
1194
Michael Foordb4a81c82009-05-29 20:33:46 +00001195 If a module provides a ``load_tests`` function it will be called to
1196 load the tests. This allows modules to customize test loading.
1197 This is the `load_tests protocol`_.
1198
1199 .. versionchanged:: 2.7
1200 Support for ``load_tests`` added.
1201
Benjamin Peterson99721e02009-03-23 23:10:14 +00001202
1203 .. method:: loadTestsFromName(name[, module])
1204
1205 Return a suite of all tests cases given a string specifier.
1206
1207 The specifier *name* is a "dotted name" that may resolve either to a
1208 module, a test case class, a test method within a test case class, a
1209 :class:`TestSuite` instance, or a callable object which returns a
1210 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1211 applied in the order listed here; that is, a method on a possible test
1212 case class will be picked up as "a test method within a test case class",
1213 rather than "a callable object".
1214
1215 For example, if you have a module :mod:`SampleTests` containing a
Michael Foordb4a81c82009-05-29 20:33:46 +00001216 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three
1217 test methods (:meth:`test_one`, :meth:`test_two`, and
1218 :meth:`test_three`), the specifier ``'SampleTests.SampleTestCase'``
1219 would cause this method to return a suite which will run all three test
1220 methods. Using the specifier ``'SampleTests.SampleTestCase.test_two'``
1221 would cause it to return a test suite which will run only the
1222 :meth:`test_two` test method. The specifier can refer to modules and
1223 packages which have not been imported; they will be imported as a
Benjamin Peterson99721e02009-03-23 23:10:14 +00001224 side-effect.
1225
1226 The method optionally resolves *name* relative to the given *module*.
1227
1228
1229 .. method:: loadTestsFromNames(names[, module])
1230
1231 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1232 than a single name. The return value is a test suite which supports all
1233 the tests defined for each name.
1234
1235
1236 .. method:: getTestCaseNames(testCaseClass)
1237
1238 Return a sorted sequence of method names found within *testCaseClass*;
1239 this should be a subclass of :class:`TestCase`.
1240
Michael Foordb4a81c82009-05-29 20:33:46 +00001241
1242 .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1243
1244 Find and return all test modules from the specified start directory,
1245 recursing into subdirectories to find them. Only test files that match
1246 *pattern* will be loaded. (Using shell style pattern matching.)
1247
1248 All test modules must be importable from the top level of the project. If
1249 the start directory is not the top level directory then the top level
1250 directory must be specified separately.
1251
1252 If a test package name (directory with :file:`__init__.py`) matches the
1253 pattern then the package will be checked for a ``load_tests``
1254 function. If this exists then it will be called with *loader*, *tests*,
1255 *pattern*.
1256
1257 If load_tests exists then discovery does *not* recurse into the package,
1258 ``load_tests`` is responsible for loading all tests in the package.
1259
1260 The pattern is deliberately not stored as a loader attribute so that
1261 packages can continue discovery themselves. *top_level_dir* is stored so
1262 ``load_tests`` does not need to pass this argument in to
1263 ``loader.discover()``.
1264
1265
Benjamin Peterson99721e02009-03-23 23:10:14 +00001266 The following attributes of a :class:`TestLoader` can be configured either by
1267 subclassing or assignment on an instance:
1268
1269
1270 .. attribute:: testMethodPrefix
1271
1272 String giving the prefix of method names which will be interpreted as test
1273 methods. The default value is ``'test'``.
1274
1275 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1276 methods.
1277
1278
1279 .. attribute:: sortTestMethodsUsing
1280
1281 Function to be used to compare method names when sorting them in
1282 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
1283 default value is the built-in :func:`cmp` function; the attribute can also
1284 be set to :const:`None` to disable the sort.
1285
1286
1287 .. attribute:: suiteClass
1288
1289 Callable object that constructs a test suite from a list of tests. No
1290 methods on the resulting object are needed. The default value is the
1291 :class:`TestSuite` class.
1292
1293 This affects all the :meth:`loadTestsFrom\*` methods.
1294
1295
Benjamin Peterson99721e02009-03-23 23:10:14 +00001296.. class:: TestResult
1297
1298 This class is used to compile information about which tests have succeeded
1299 and which have failed.
1300
1301 A :class:`TestResult` object stores the results of a set of tests. The
1302 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1303 properly recorded; test authors do not need to worry about recording the
1304 outcome of tests.
1305
1306 Testing frameworks built on top of :mod:`unittest` may want access to the
1307 :class:`TestResult` object generated by running a set of tests for reporting
1308 purposes; a :class:`TestResult` instance is returned by the
1309 :meth:`TestRunner.run` method for this purpose.
1310
1311 :class:`TestResult` instances have the following attributes that will be of
1312 interest when inspecting the results of running a set of tests:
1313
1314
1315 .. attribute:: errors
1316
1317 A list containing 2-tuples of :class:`TestCase` instances and strings
1318 holding formatted tracebacks. Each tuple represents a test which raised an
1319 unexpected exception.
1320
1321 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001322 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1323
1324
1325 .. attribute:: failures
1326
1327 A list containing 2-tuples of :class:`TestCase` instances and strings
1328 holding formatted tracebacks. Each tuple represents a test where a failure
1329 was explicitly signalled using the :meth:`TestCase.fail\*` or
1330 :meth:`TestCase.assert\*` methods.
1331
1332 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001333 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1334
1335 .. attribute:: skipped
1336
1337 A list containing 2-tuples of :class:`TestCase` instances and strings
1338 holding the reason for skipping the test.
1339
1340 .. versionadded:: 2.7
1341
1342 .. attribute:: expectedFailures
1343
1344 A list contaning 2-tuples of :class:`TestCase` instances and strings
1345 holding formatted tracebacks. Each tuple represents a expected failures
1346 of the test case.
1347
1348 .. attribute:: unexpectedSuccesses
1349
1350 A list containing :class:`TestCase` instances that were marked as expected
1351 failures, but succeeded.
1352
1353 .. attribute:: shouldStop
1354
1355 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1356
1357
1358 .. attribute:: testsRun
1359
1360 The total number of tests run so far.
1361
1362
1363 .. method:: wasSuccessful()
1364
1365 Return :const:`True` if all tests run so far have passed, otherwise returns
1366 :const:`False`.
1367
1368
1369 .. method:: stop()
1370
1371 This method can be called to signal that the set of tests being run should
1372 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1373 :class:`TestRunner` objects should respect this flag and return without
1374 running any additional tests.
1375
1376 For example, this feature is used by the :class:`TextTestRunner` class to
1377 stop the test framework when the user signals an interrupt from the
1378 keyboard. Interactive tools which provide :class:`TestRunner`
1379 implementations can use this in a similar manner.
1380
1381 The following methods of the :class:`TestResult` class are used to maintain
1382 the internal data structures, and may be extended in subclasses to support
1383 additional reporting requirements. This is particularly useful in building
1384 tools which support interactive reporting while tests are being run.
1385
1386
1387 .. method:: startTest(test)
1388
1389 Called when the test case *test* is about to be run.
1390
1391 The default implementation simply increments the instance's :attr:`testsRun`
1392 counter.
1393
1394
1395 .. method:: stopTest(test)
1396
1397 Called after the test case *test* has been executed, regardless of the
1398 outcome.
1399
1400 The default implementation does nothing.
1401
1402
Michael Foord07ef4872009-05-02 22:43:34 +00001403 .. method:: startTestRun(test)
1404
1405 Called once before any tests are executed.
1406
1407 .. versionadded:: 2.7
1408
1409
1410 .. method:: stopTestRun(test)
1411
1412 Called once before any tests are executed.
1413
1414 .. versionadded:: 2.7
1415
1416
Benjamin Peterson99721e02009-03-23 23:10:14 +00001417 .. method:: addError(test, err)
1418
1419 Called when the test case *test* raises an unexpected exception *err* is a
1420 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1421 traceback)``.
1422
1423 The default implementation appends a tuple ``(test, formatted_err)`` to
1424 the instance's :attr:`errors` attribute, where *formatted_err* is a
1425 formatted traceback derived from *err*.
1426
1427
1428 .. method:: addFailure(test, err)
1429
Michael Foordb4a81c82009-05-29 20:33:46 +00001430 Called when the test case *test* signals a failure. *err* is a tuple of
1431 the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
Benjamin Peterson99721e02009-03-23 23:10:14 +00001432
1433 The default implementation appends a tuple ``(test, formatted_err)`` to
1434 the instance's :attr:`failures` attribute, where *formatted_err* is a
1435 formatted traceback derived from *err*.
1436
1437
1438 .. method:: addSuccess(test)
1439
1440 Called when the test case *test* succeeds.
1441
1442 The default implementation does nothing.
1443
1444
1445 .. method:: addSkip(test, reason)
1446
1447 Called when the test case *test* is skipped. *reason* is the reason the
1448 test gave for skipping.
1449
1450 The default implementation appends a tuple ``(test, reason)`` to the
1451 instance's :attr:`skipped` attribute.
1452
1453
1454 .. method:: addExpectedFailure(test, err)
1455
1456 Called when the test case *test* fails, but was marked with the
1457 :func:`expectedFailure` decorator.
1458
1459 The default implementation appends a tuple ``(test, formatted_err)`` to
1460 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1461 is a formatted traceback derived from *err*.
1462
1463
1464 .. method:: addUnexpectedSuccess(test)
1465
1466 Called when the test case *test* was marked with the
1467 :func:`expectedFailure` decorator, but succeeded.
1468
1469 The default implementation appends the test to the instance's
1470 :attr:`unexpectedSuccesses` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001471
1472
1473.. data:: defaultTestLoader
1474
1475 Instance of the :class:`TestLoader` class intended to be shared. If no
1476 customization of the :class:`TestLoader` is needed, this instance can be used
1477 instead of repeatedly creating new instances.
1478
1479
1480.. class:: TextTestRunner([stream[, descriptions[, verbosity]]])
1481
1482 A basic test runner implementation which prints results on standard error. It
1483 has a few configurable parameters, but is essentially very simple. Graphical
1484 applications which run test suites should provide alternate implementations.
1485
Georg Brandl9bc66822009-04-27 17:04:23 +00001486 .. method:: _makeResult()
1487
1488 This method returns the instance of ``TestResult`` used by :meth:`run`.
1489 It is not intended to be called directly, but can be overridden in
1490 subclasses to provide a custom ``TestResult``.
1491
Georg Brandl8ec7f652007-08-15 14:28:01 +00001492
Michael Foord5d31e052009-05-11 17:59:43 +00001493.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit, [verbosity]]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001494
1495 A command-line program that runs a set of tests; this is primarily for making
1496 test modules conveniently executable. The simplest use for this function is to
1497 include the following line at the end of a test script::
1498
1499 if __name__ == '__main__':
1500 unittest.main()
1501
Michael Foord5d31e052009-05-11 17:59:43 +00001502 You can run tests with more detailed information by passing in the verbosity
1503 argument::
1504
1505 if __name__ == '__main__':
1506 unittest.main(verbosity=2)
1507
Georg Brandl8ec7f652007-08-15 14:28:01 +00001508 The *testRunner* argument can either be a test runner class or an already
Michael Foord829f6b82009-05-02 11:43:06 +00001509 created instance of it. By default ``main`` calls :func:`sys.exit` with
1510 an exit code indicating success or failure of the tests run.
1511
1512 ``main`` supports being used from the interactive interpreter by passing in the
1513 argument ``exit=False``. This displays the result on standard output without
1514 calling :func:`sys.exit`::
1515
1516 >>> from unittest import main
1517 >>> main(module='test_module', exit=False)
1518
1519 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1520 This stores the result of the tests run as the ``result`` attribute.
1521
1522 .. versionchanged:: 2.7
Michael Foord5d31e052009-05-11 17:59:43 +00001523 The ``exit`` and ``verbosity`` parameters were added.
Michael Foordb4a81c82009-05-29 20:33:46 +00001524
1525
1526load_tests Protocol
1527###################
1528
1529Modules or packages can customize how tests are loaded from them during normal
1530test runs or test discovery by implementing a function called ``load_tests``.
1531
1532If a test module defines ``load_tests`` it will be called by
1533:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1534
1535 load_tests(loader, standard_tests, None)
1536
1537It should return a :class:`TestSuite`.
1538
1539*loader* is the instance of :class:`TestLoader` doing the loading.
1540*standard_tests* are the tests that would be loaded by default from the
1541module. It is common for test modules to only want to add or remove tests
1542from the standard set of tests.
1543The third argument is used when loading packages as part of test discovery.
1544
1545A typical ``load_tests`` function that loads tests from a specific set of
1546:class:`TestCase` classes may look like::
1547
1548 test_cases = (TestCase1, TestCase2, TestCase3)
1549
1550 def load_tests(loader, tests, pattern):
1551 suite = TestSuite()
1552 for test_class in test_cases:
1553 tests = loader.loadTestsFromTestCase(test_class)
1554 suite.addTests(tests)
1555 return suite
1556
1557If discovery is started, either from the command line or by calling
1558:meth:`TestLoader.discover`, with a pattern that matches a package
1559name then the package :file:`__init__.py` will be checked for ``load_tests``.
1560
1561.. note::
1562
1563 The default pattern is 'test*.py'. This matches all python files
1564 that start with 'test' but *won't* match any test directories.
1565
1566 A pattern like 'test*' will match test packages as well as
1567 modules.
1568
1569If the package :file:`__init__.py` defines ``load_tests`` then it will be
1570called and discovery not continued into the package. ``load_tests``
1571is called with the following arguments::
1572
1573 load_tests(loader, standard_tests, pattern)
1574
1575This should return a :class:`TestSuite` representing all the tests
1576from the package. (``standard_tests`` will only contain tests
1577collected from :file:`__init__.py`.)
1578
1579Because the pattern is passed into ``load_tests`` the package is free to
1580continue (and potentially modify) test discovery. A 'do nothing'
1581``load_tests`` function for a test package would look like::
1582
1583 def load_tests(loader, standard_tests, pattern):
1584 # top level directory cached on loader instance
1585 this_dir = os.path.dirname(__file__)
1586 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1587 standard_tests.addTests(package_tests)
1588 return standard_tests