blob: 4f321dc357239366c0f027852b983ce97c60e1a1 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`unittest` --- Unit testing framework
3==========================================
4
5.. module:: unittest
6 :synopsis: Unit testing framework for Python.
7.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
9.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
10.. sectionauthor:: Raymond Hettinger <python@rcn.com>
11
12
13.. versionadded:: 2.1
Benjamin Peterson692428e2009-03-23 21:50:21 +000014
Benjamin Peterson99721e02009-03-23 23:10:14 +000015.. versionchanged:: 2.7
16 Added test :ref:`skipping and expected failures <unittest-skipping>`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000017
18The Python unit testing framework, sometimes referred to as "PyUnit," is a
19Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
20turn, a Java version of Kent's Smalltalk testing framework. Each is the de
21facto standard unit testing framework for its respective language.
22
23:mod:`unittest` supports test automation, sharing of setup and shutdown code for
24tests, aggregation of tests into collections, and independence of the tests from
25the reporting framework. The :mod:`unittest` module provides classes that make
26it easy to support these qualities for a set of tests.
27
28To achieve this, :mod:`unittest` supports some important concepts:
29
30test fixture
31 A :dfn:`test fixture` represents the preparation needed to perform one or more
32 tests, and any associate cleanup actions. This may involve, for example,
33 creating temporary or proxy databases, directories, or starting a server
34 process.
35
36test case
37 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
38 response to a particular set of inputs. :mod:`unittest` provides a base class,
39 :class:`TestCase`, which may be used to create new test cases.
40
41test suite
42 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
43 used to aggregate tests that should be executed together.
44
45test runner
46 A :dfn:`test runner` is a component which orchestrates the execution of tests
47 and provides the outcome to the user. The runner may use a graphical interface,
48 a textual interface, or return a special value to indicate the results of
49 executing the tests.
50
51The test case and test fixture concepts are supported through the
52:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
53used when creating new tests, and the latter can be used when integrating
54existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson99721e02009-03-23 23:10:14 +000055fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
56:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
57and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
58can be passed to the constructor for these purposes. When the test is run, the
59fixture initialization is run first; if it succeeds, the cleanup method is run
60after the test has been executed, regardless of the outcome of the test. Each
61instance of the :class:`TestCase` will only be used to run a single test method,
62so a new fixture is created for each test.
Georg Brandl8ec7f652007-08-15 14:28:01 +000063
64Test suites are implemented by the :class:`TestSuite` class. This class allows
65individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson692428e2009-03-23 21:50:21 +000066all tests added directly to the suite and in "child" test suites are run. A
67:class:`ClassTestSuite` contains the test cases of a class.
Georg Brandl8ec7f652007-08-15 14:28:01 +000068
Benjamin Peterson99721e02009-03-23 23:10:14 +000069A test runner is an object that provides a single method,
70:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
71object as a parameter, and returns a result object. The class
72:class:`TestResult` is provided for use as the result object. :mod:`unittest`
73provides the :class:`TextTestRunner` as an example test runner which reports
74test results on the standard error stream by default. Alternate runners can be
75implemented for other environments (such as graphical environments) without any
76need to derive from a specific class.
Georg Brandl8ec7f652007-08-15 14:28:01 +000077
78
79.. seealso::
80
81 Module :mod:`doctest`
82 Another test-support module with a very different flavor.
83
84 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
85 Kent Beck's original paper on testing frameworks using the pattern shared by
86 :mod:`unittest`.
87
Raymond Hettinger21b617b2009-03-24 00:17:11 +000088 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
89 Third-party unittest frameworks with a lighter-weight syntax
90 for writing tests. For example, ``assert func(10) == 42``.
91
92 `python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
93 Tools for creating mock test objects (objects simulating external resources).
Georg Brandl8ec7f652007-08-15 14:28:01 +000094
95.. _unittest-minimal-example:
96
97Basic example
98-------------
99
100The :mod:`unittest` module provides a rich set of tools for constructing and
101running tests. This section demonstrates that a small subset of the tools
102suffice to meet the needs of most users.
103
104Here is a short script to test three functions from the :mod:`random` module::
105
106 import random
107 import unittest
108
109 class TestSequenceFunctions(unittest.TestCase):
110
111 def setUp(self):
112 self.seq = range(10)
113
Benjamin Peterson99721e02009-03-23 23:10:14 +0000114 def test_shuffle(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000115 # make sure the shuffled sequence does not lose any elements
116 random.shuffle(self.seq)
117 self.seq.sort()
118 self.assertEqual(self.seq, range(10))
119
Benjamin Peterson99721e02009-03-23 23:10:14 +0000120 def test_choice(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000121 element = random.choice(self.seq)
122 self.assert_(element in self.seq)
123
Benjamin Peterson99721e02009-03-23 23:10:14 +0000124 def test_sample(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000125 self.assertRaises(ValueError, random.sample, self.seq, 20)
126 for element in random.sample(self.seq, 5):
127 self.assert_(element in self.seq)
128
129 if __name__ == '__main__':
130 unittest.main()
131
Benjamin Peterson99721e02009-03-23 23:10:14 +0000132A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl8ec7f652007-08-15 14:28:01 +0000133individual tests are defined with methods whose names start with the letters
134``test``. This naming convention informs the test runner about which methods
135represent tests.
136
Benjamin Peterson99721e02009-03-23 23:10:14 +0000137The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
138expected result; :meth:`~TestCase.assert_` to verify a condition; or
139:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
140These methods are used instead of the :keyword:`assert` statement so the test
141runner can accumulate all test results and produce a report.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000142
Benjamin Peterson99721e02009-03-23 23:10:14 +0000143When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
144method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
145defined, the test runner will invoke that method after each test. In the
146example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
147test.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000148
149The final block shows a simple way to run the tests. :func:`unittest.main`
150provides a command line interface to the test script. When run from the command
151line, the above script produces an output that looks like this::
152
153 ...
154 ----------------------------------------------------------------------
155 Ran 3 tests in 0.000s
156
157 OK
158
159Instead of :func:`unittest.main`, there are other ways to run the tests with a
160finer level of control, less terse output, and no requirement to be run from the
161command line. For example, the last two lines may be replaced with::
162
163 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
164 unittest.TextTestRunner(verbosity=2).run(suite)
165
166Running the revised script from the interpreter or another script produces the
167following output::
168
169 testchoice (__main__.TestSequenceFunctions) ... ok
170 testsample (__main__.TestSequenceFunctions) ... ok
171 testshuffle (__main__.TestSequenceFunctions) ... ok
172
173 ----------------------------------------------------------------------
174 Ran 3 tests in 0.110s
175
176 OK
177
178The above examples show the most commonly used :mod:`unittest` features which
179are sufficient to meet many everyday testing needs. The remainder of the
180documentation explores the full feature set from first principles.
181
182
183.. _organizing-tests:
184
185Organizing test code
186--------------------
187
188The basic building blocks of unit testing are :dfn:`test cases` --- single
189scenarios that must be set up and checked for correctness. In :mod:`unittest`,
190test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
191class. To make your own test cases you must write subclasses of
192:class:`TestCase`, or use :class:`FunctionTestCase`.
193
194An instance of a :class:`TestCase`\ -derived class is an object that can
195completely run a single test method, together with optional set-up and tidy-up
196code.
197
198The testing code of a :class:`TestCase` instance should be entirely self
199contained, such that it can be run either in isolation or in arbitrary
200combination with any number of other test cases.
201
Benjamin Peterson99721e02009-03-23 23:10:14 +0000202The simplest :class:`TestCase` subclass will simply override the
203:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204
205 import unittest
206
207 class DefaultWidgetSizeTestCase(unittest.TestCase):
208 def runTest(self):
209 widget = Widget('The widget')
210 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
211
212Note that in order to test something, we use the one of the :meth:`assert\*` or
213:meth:`fail\*` methods provided by the :class:`TestCase` base class. If the
214test fails, an exception will be raised, and :mod:`unittest` will identify the
215test case as a :dfn:`failure`. Any other exceptions will be treated as
216:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
217caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
218caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
219function call.
220
221The way to run a test case will be described later. For now, note that to
222construct an instance of such a test case, we call its constructor without
223arguments::
224
225 testCase = DefaultWidgetSizeTestCase()
226
227Now, such test cases can be numerous, and their set-up can be repetitive. In
228the above case, constructing a :class:`Widget` in each of 100 Widget test case
229subclasses would mean unsightly duplication.
230
231Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson99721e02009-03-23 23:10:14 +0000232:meth:`~TestCase.setUp`, which the testing framework will automatically call for
233us when we run the test::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000234
235 import unittest
236
237 class SimpleWidgetTestCase(unittest.TestCase):
238 def setUp(self):
239 self.widget = Widget('The widget')
240
241 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
242 def runTest(self):
243 self.failUnless(self.widget.size() == (50,50),
244 'incorrect default size')
245
246 class WidgetResizeTestCase(SimpleWidgetTestCase):
247 def runTest(self):
248 self.widget.resize(100,150)
249 self.failUnless(self.widget.size() == (100,150),
250 'wrong size after resize')
251
Benjamin Peterson99721e02009-03-23 23:10:14 +0000252If the :meth:`~TestCase.setUp` method raises an exception while the test is
253running, the framework will consider the test to have suffered an error, and the
254:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000255
Benjamin Peterson99721e02009-03-23 23:10:14 +0000256Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
257after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000258
259 import unittest
260
261 class SimpleWidgetTestCase(unittest.TestCase):
262 def setUp(self):
263 self.widget = Widget('The widget')
264
265 def tearDown(self):
266 self.widget.dispose()
267 self.widget = None
268
Benjamin Peterson99721e02009-03-23 23:10:14 +0000269If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
270be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000271
272Such a working environment for the testing code is called a :dfn:`fixture`.
273
274Often, many small test cases will use the same fixture. In this case, we would
275end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
276classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
278mechanism::
279
280 import unittest
281
282 class WidgetTestCase(unittest.TestCase):
283 def setUp(self):
284 self.widget = Widget('The widget')
285
286 def tearDown(self):
287 self.widget.dispose()
288 self.widget = None
289
290 def testDefaultSize(self):
291 self.failUnless(self.widget.size() == (50,50),
292 'incorrect default size')
293
294 def testResize(self):
295 self.widget.resize(100,150)
296 self.failUnless(self.widget.size() == (100,150),
297 'wrong size after resize')
298
Benjamin Peterson99721e02009-03-23 23:10:14 +0000299Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
300provided two different test methods. Class instances will now each run one of
301the :meth:`test\*` methods, with ``self.widget`` created and destroyed
302separately for each instance. When creating an instance we must specify the
303test method it is to run. We do this by passing the method name in the
304constructor::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000305
306 defaultSizeTestCase = WidgetTestCase('testDefaultSize')
307 resizeTestCase = WidgetTestCase('testResize')
308
309Test case instances are grouped together according to the features they test.
310:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
311represented by :mod:`unittest`'s :class:`TestSuite` class::
312
313 widgetTestSuite = unittest.TestSuite()
314 widgetTestSuite.addTest(WidgetTestCase('testDefaultSize'))
315 widgetTestSuite.addTest(WidgetTestCase('testResize'))
316
317For the ease of running tests, as we will see later, it is a good idea to
318provide in each test module a callable object that returns a pre-built test
319suite::
320
321 def suite():
322 suite = unittest.TestSuite()
323 suite.addTest(WidgetTestCase('testDefaultSize'))
324 suite.addTest(WidgetTestCase('testResize'))
325 return suite
326
327or even::
328
329 def suite():
330 tests = ['testDefaultSize', 'testResize']
331
332 return unittest.TestSuite(map(WidgetTestCase, tests))
333
334Since it is a common pattern to create a :class:`TestCase` subclass with many
335similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
336class that can be used to automate the process of creating a test suite and
337populating it with individual tests. For example, ::
338
339 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
340
341will create a test suite that will run ``WidgetTestCase.testDefaultSize()`` and
342``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method
343name prefix to identify test methods automatically.
344
345Note that the order in which the various test cases will be run is determined by
346sorting the test function names with the built-in :func:`cmp` function.
347
348Often it is desirable to group suites of test cases together, so as to run tests
349for the whole system at once. This is easy, since :class:`TestSuite` instances
350can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
351added to a :class:`TestSuite`::
352
353 suite1 = module1.TheTestSuite()
354 suite2 = module2.TheTestSuite()
355 alltests = unittest.TestSuite([suite1, suite2])
356
357You can place the definitions of test cases and test suites in the same modules
358as the code they are to test (such as :file:`widget.py`), but there are several
359advantages to placing the test code in a separate module, such as
360:file:`test_widget.py`:
361
362* The test module can be run standalone from the command line.
363
364* The test code can more easily be separated from shipped code.
365
366* There is less temptation to change test code to fit the code it tests without
367 a good reason.
368
369* Test code should be modified much less frequently than the code it tests.
370
371* Tested code can be refactored more easily.
372
373* Tests for modules written in C must be in separate modules anyway, so why not
374 be consistent?
375
376* If the testing strategy changes, there is no need to change the source code.
377
378
379.. _legacy-unit-tests:
380
381Re-using old test code
382----------------------
383
384Some users will find that they have existing test code that they would like to
385run from :mod:`unittest`, without converting every old test function to a
386:class:`TestCase` subclass.
387
388For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
389This subclass of :class:`TestCase` can be used to wrap an existing test
390function. Set-up and tear-down functions can also be provided.
391
392Given the following test function::
393
394 def testSomething():
395 something = makeSomething()
396 assert something.name is not None
397 # ...
398
399one can create an equivalent test case instance as follows::
400
401 testcase = unittest.FunctionTestCase(testSomething)
402
403If there are additional set-up and tear-down methods that should be called as
404part of the test case's operation, they can also be provided like so::
405
406 testcase = unittest.FunctionTestCase(testSomething,
407 setUp=makeSomethingDB,
408 tearDown=deleteSomethingDB)
409
410To make migrating existing test suites easier, :mod:`unittest` supports tests
411raising :exc:`AssertionError` to indicate test failure. However, it is
412recommended that you use the explicit :meth:`TestCase.fail\*` and
413:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
414may treat :exc:`AssertionError` differently.
415
416.. note::
417
418 Even though :class:`FunctionTestCase` can be used to quickly convert an existing
419 test base over to a :mod:`unittest`\ -based system, this approach is not
420 recommended. Taking the time to set up proper :class:`TestCase` subclasses will
421 make future test refactorings infinitely easier.
422
Benjamin Peterson99721e02009-03-23 23:10:14 +0000423In some cases, the existing tests may have been written using the :mod:`doctest`
424module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
425automatically build :class:`unittest.TestSuite` instances from the existing
426:mod:`doctest`\ -based tests.
427
Georg Brandl8ec7f652007-08-15 14:28:01 +0000428
Benjamin Peterson692428e2009-03-23 21:50:21 +0000429.. _unittest-skipping:
430
431Skipping tests and expected failures
432------------------------------------
433
434Unittest supports skipping individual test methods and even whole classes of
435tests. In addition, it supports marking a test as a "expected failure," a test
436that is broken and will fail, but shouldn't be counted as a failure on a
437:class:`TestResult`.
438
439Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
440or one of its conditional variants.
441
442Basic skipping looks like this: ::
443
444 class MyTestCase(unittest.TestCase):
445
446 @unittest.skip("demonstrating skipping")
447 def test_nothing(self):
448 self.fail("shouldn't happen")
449
450This is the output of running the example above in verbose mode: ::
451
452 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
453
454 ----------------------------------------------------------------------
455 Ran 1 test in 0.072s
456
457Classes can be skipped just like methods: ::
458
459 @skip("showing class skipping")
460 class MySkippedTestCase(unittest.TestCase):
461 def test_not_run(self):
462 pass
463
Benjamin Peterson31b78062009-03-23 23:13:36 +0000464:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
465that needs to be set up is not available.
466
Benjamin Peterson692428e2009-03-23 21:50:21 +0000467Expected failures use the :func:`expectedFailure` decorator. ::
468
469 class ExpectedFailureTestCase(unittest.TestCase):
470 @unittest.expectedFailure
471 def test_fail(self):
472 self.assertEqual(1, 0, "broken")
473
474It's easy to roll your own skipping decorators by making a decorator that calls
475:func:`skip` on the test when it wants it to be skipped. This decorator skips
476the test unless the passed object has a certain attribute: ::
477
478 def skipUnlessHasattr(obj, attr):
479 if hasattr(obj, attr):
480 return lambda func: func
481 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
482
483The following decorators implement test skipping and expected failures:
484
485.. function:: skip(reason)
486
487 Unconditionally skip the decorated test. *reason* should describe why the
488 test is being skipped.
489
490.. function:: skipIf(condition, reason)
491
492 Skip the decorated test if *condition* is true.
493
494.. function:: skipUnless(condition, reason)
495
496 Skip the decoratored test unless *condition* is true.
497
498.. function:: expectedFailure
499
500 Mark the test as an expected failure. If the test fails when run, the test
501 is not counted as a failure.
502
503
Georg Brandl8ec7f652007-08-15 14:28:01 +0000504.. _unittest-contents:
505
506Classes and functions
507---------------------
508
Benjamin Peterson99721e02009-03-23 23:10:14 +0000509This section describes in depth the API of :mod:`unittest`.
510
511
512.. _testcase-objects:
513
514Test cases
515~~~~~~~~~~
Georg Brandl8ec7f652007-08-15 14:28:01 +0000516
517.. class:: TestCase([methodName])
518
519 Instances of the :class:`TestCase` class represent the smallest testable units
520 in the :mod:`unittest` universe. This class is intended to be used as a base
521 class, with specific tests being implemented by concrete subclasses. This class
522 implements the interface needed by the test runner to allow it to drive the
523 test, and methods that the test code can use to check for and report various
524 kinds of failure.
525
526 Each instance of :class:`TestCase` will run a single test method: the method
527 named *methodName*. If you remember, we had an earlier example that went
528 something like this::
529
530 def suite():
531 suite = unittest.TestSuite()
532 suite.addTest(WidgetTestCase('testDefaultSize'))
533 suite.addTest(WidgetTestCase('testResize'))
534 return suite
535
536 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
537 single test.
538
Benjamin Peterson99721e02009-03-23 23:10:14 +0000539 *methodName* defaults to :meth:`runTest`.
540
541 :class:`TestCase` instances provide three groups of methods: one group used
542 to run the test, another used by the test implementation to check conditions
543 and report failures, and some inquiry methods allowing information about the
544 test itself to be gathered.
545
546 Methods in the first group (running the test) are:
547
548
549 .. method:: setUp()
550
551 Method called to prepare the test fixture. This is called immediately
552 before calling the test method; any exception raised by this method will
553 be considered an error rather than a test failure. The default
554 implementation does nothing.
555
556
557 .. method:: tearDown()
558
559 Method called immediately after the test method has been called and the
560 result recorded. This is called even if the test method raised an
561 exception, so the implementation in subclasses may need to be particularly
562 careful about checking internal state. Any exception raised by this
563 method will be considered an error rather than a test failure. This
564 method will only be called if the :meth:`setUp` succeeds, regardless of
565 the outcome of the test method. The default implementation does nothing.
566
567
568 .. method:: run([result])
569
570 Run the test, collecting the result into the test result object passed as
571 *result*. If *result* is omitted or :const:`None`, a temporary result
572 object is created (by calling the :meth:`defaultTestCase` method) and
573 used; this result object is not returned to :meth:`run`'s caller.
574
575 The same effect may be had by simply calling the :class:`TestCase`
576 instance.
577
578
Benjamin Peterson47d97382009-03-26 20:05:50 +0000579 .. method:: skipTest(reason)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000580
Benjamin Peterson31b78062009-03-23 23:13:36 +0000581 Calling this during the a test method or :meth:`setUp` skips the current
582 test. See :ref:`unittest-skipping` for more information.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000583
584
585 .. method:: debug()
586
587 Run the test without collecting the result. This allows exceptions raised
588 by the test to be propagated to the caller, and can be used to support
589 running tests under a debugger.
590
591 The test code can use any of the following methods to check for and report
592 failures.
593
594
595 .. method:: assert_(expr[, msg])
596 failUnless(expr[, msg])
597 assertTrue(expr[, msg])
598
599 Signal a test failure if *expr* is false; the explanation for the error
600 will be *msg* if given, otherwise it will be :const:`None`.
601
602
603 .. method:: assertEqual(first, second[, msg])
604 failUnlessEqual(first, second[, msg])
605
606 Test that *first* and *second* are equal. If the values do not compare
607 equal, the test will fail with the explanation given by *msg*, or
608 :const:`None`. Note that using :meth:`failUnlessEqual` improves upon
609 doing the comparison as the first parameter to :meth:`failUnless`: the
610 default value for *msg* can be computed to include representations of both
611 *first* and *second*.
612
613
614 .. method:: assertNotEqual(first, second[, msg])
615 failIfEqual(first, second[, msg])
616
617 Test that *first* and *second* are not equal. If the values do compare
618 equal, the test will fail with the explanation given by *msg*, or
619 :const:`None`. Note that using :meth:`failIfEqual` improves upon doing
620 the comparison as the first parameter to :meth:`failUnless` is that the
621 default value for *msg* can be computed to include representations of both
622 *first* and *second*.
623
624
625 .. method:: assertAlmostEqual(first, second[, places[, msg]])
626 failUnlessAlmostEqual(first, second[, places[, msg]])
627
628 Test that *first* and *second* are approximately equal by computing the
629 difference, rounding to the given number of decimal *places* (default 7),
630 and comparing to zero.
631
632 Note that comparing a given number of decimal places is not the same as
633 comparing a given number of significant digits. If the values do not
634 compare equal, the test will fail with the explanation given by *msg*, or
635 :const:`None`.
636
637
638 .. method:: assertNotAlmostEqual(first, second[, places[, msg]])
639 failIfAlmostEqual(first, second[, places[, msg]])
640
641 Test that *first* and *second* are not approximately equal by computing
642 the difference, rounding to the given number of decimal *places* (default
643 7), and comparing to zero.
644
645 Note that comparing a given number of decimal places is not the same as
646 comparing a given number of significant digits. If the values do not
647 compare equal, the test will fail with the explanation given by *msg*, or
648 :const:`None`.
649
650
651 .. method:: assertRaises(exception[, callable, ...])
652 failUnlessRaises(exception[, callable, ...])
653
654 Test that an exception is raised when *callable* is called with any
655 positional or keyword arguments that are also passed to
656 :meth:`assertRaises`. The test passes if *exception* is raised, is an
657 error if another exception is raised, or fails if no exception is raised.
658 To catch any of a group of exceptions, a tuple containing the exception
659 classes may be passed as *exception*.
660
661 .. versionchanged:: 2.7
662
663 If *callable* is omitted or None, returns a context manager so that the
664 code under test can be written inline rather than as a function::
665
666 with self.failUnlessRaises(some_error_class):
667 do_something()
668
669 .. method:: failIf(expr[, msg])
670 assertFalse(expr[, msg])
671
672 The inverse of the :meth:`failUnless` method is the :meth:`failIf` method.
673 This signals a test failure if *expr* is true, with *msg* or :const:`None`
674 for the error message.
675
676
677 .. method:: fail([msg])
678
679 Signals a test failure unconditionally, with *msg* or :const:`None` for
680 the error message.
681
682
683 .. attribute:: failureException
684
685 This class attribute gives the exception raised by the test method. If a
686 test framework needs to use a specialized exception, possibly to carry
687 additional information, it must subclass this exception in order to "play
688 fair" with the framework. The initial value of this attribute is
689 :exc:`AssertionError`.
690
691 Testing frameworks can use the following methods to collect information on
692 the test:
693
694
695 .. method:: countTestCases()
696
697 Return the number of tests represented by this test object. For
698 :class:`TestCase` instances, this will always be ``1``.
699
700
701 .. method:: defaultTestResult()
702
703 Return an instance of the test result class that should be used for this
704 test case class (if no other result instance is provided to the
705 :meth:`run` method).
706
707 For :class:`TestCase` instances, this will always be an instance of
708 :class:`TestResult`; subclasses of :class:`TestCase` should override this
709 as necessary.
710
711
712 .. method:: id()
713
714 Return a string identifying the specific test case. This is usually the
715 full name of the test method, including the module and class name.
716
717
718 .. method:: shortDescription()
719
720 Returns a one-line description of the test, or :const:`None` if no
721 description has been provided. The default implementation of this method
722 returns the first line of the test method's docstring, if available, or
723 :const:`None`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000724
725
726.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
727
728 This class implements the portion of the :class:`TestCase` interface which
729 allows the test runner to drive the test, but does not provide the methods which
730 test code can use to check and report errors. This is used to create test cases
731 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
732 -based test framework.
733
734
Benjamin Peterson99721e02009-03-23 23:10:14 +0000735.. _testsuite-objects:
736
737Grouping tests
738~~~~~~~~~~~~~~
739
Georg Brandl8ec7f652007-08-15 14:28:01 +0000740.. class:: TestSuite([tests])
741
742 This class represents an aggregation of individual tests cases and test suites.
743 The class presents the interface needed by the test runner to allow it to be run
744 as any other test case. Running a :class:`TestSuite` instance is the same as
745 iterating over the suite, running each test individually.
746
747 If *tests* is given, it must be an iterable of individual test cases or other
748 test suites that will be used to build the suite initially. Additional methods
749 are provided to add test cases and suites to the collection later on.
750
Benjamin Peterson99721e02009-03-23 23:10:14 +0000751 :class:`TestSuite` (including :class:`ClassTestSuite`) objects behave much
752 like :class:`TestCase` objects, except they do not actually implement a test.
753 Instead, they are used to aggregate tests into groups of tests that should be
754 run together. Some additional methods are available to add tests to
755 :class:`TestSuite` instances:
756
757
758 .. method:: TestSuite.addTest(test)
759
760 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
761
762
763 .. method:: TestSuite.addTests(tests)
764
765 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
766 instances to this test suite.
767
768 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
769 element.
770
771 :class:`TestSuite` shares the following methods with :class:`TestCase`:
772
773
774 .. method:: run(result)
775
776 Run the tests associated with this suite, collecting the result into the
777 test result object passed as *result*. Note that unlike
778 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
779 be passed in.
780
781
782 .. method:: debug()
783
784 Run the tests associated with this suite without collecting the
785 result. This allows exceptions raised by the test to be propagated to the
786 caller and can be used to support running tests under a debugger.
787
788
789 .. method:: countTestCases()
790
791 Return the number of tests represented by this test object, including all
792 individual tests and sub-suites.
793
794 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
795 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
796
797
Benjamin Peterson692428e2009-03-23 21:50:21 +0000798.. class:: ClassTestSuite(tests, collected_from)
799
800 This subclass of :class:`TestSuite` repesents an aggregation of individuals
801 tests from one :class:`TestCase` class. *tests* is an iterable of
802 :class:`TestCase` instances created from the class. *collected_from* is the
803 class they came from.
804
Georg Brandl8ec7f652007-08-15 14:28:01 +0000805
Benjamin Peterson99721e02009-03-23 23:10:14 +0000806Loading and running tests
807~~~~~~~~~~~~~~~~~~~~~~~~~
808
Georg Brandl8ec7f652007-08-15 14:28:01 +0000809.. class:: TestLoader()
810
Benjamin Peterson99721e02009-03-23 23:10:14 +0000811 The :class:`TestLoader` class is used to create test suites from classes and
812 modules. Normally, there is no need to create an instance of this class; the
813 :mod:`unittest` module provides an instance that can be shared as
814 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
815 customization of some configurable properties.
816
817 :class:`TestLoader` objects have the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000818
819
Benjamin Peterson99721e02009-03-23 23:10:14 +0000820 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000821
Benjamin Peterson99721e02009-03-23 23:10:14 +0000822 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
823 :class:`testCaseClass`.
824
825
826 .. method:: loadTestsFromModule(module)
827
828 Return a suite of all tests cases contained in the given module. This
829 method searches *module* for classes derived from :class:`TestCase` and
830 creates an instance of the class for each test method defined for the
831 class.
832
833 .. warning::
834
835 While using a hierarchy of :class:`TestCase`\ -derived classes can be
836 convenient in sharing fixtures and helper functions, defining test
837 methods on base classes that are not intended to be instantiated
838 directly does not play well with this method. Doing so, however, can
839 be useful when the fixtures are different and defined in subclasses.
840
841
842 .. method:: loadTestsFromName(name[, module])
843
844 Return a suite of all tests cases given a string specifier.
845
846 The specifier *name* is a "dotted name" that may resolve either to a
847 module, a test case class, a test method within a test case class, a
848 :class:`TestSuite` instance, or a callable object which returns a
849 :class:`TestCase` or :class:`TestSuite` instance. These checks are
850 applied in the order listed here; that is, a method on a possible test
851 case class will be picked up as "a test method within a test case class",
852 rather than "a callable object".
853
854 For example, if you have a module :mod:`SampleTests` containing a
855 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
856 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
857 specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
858 suite which will run all three test methods. Using the specifier
859 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
860 which will run only the :meth:`test_two` test method. The specifier can refer
861 to modules and packages which have not been imported; they will be imported as a
862 side-effect.
863
864 The method optionally resolves *name* relative to the given *module*.
865
866
867 .. method:: loadTestsFromNames(names[, module])
868
869 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
870 than a single name. The return value is a test suite which supports all
871 the tests defined for each name.
872
873
874 .. method:: getTestCaseNames(testCaseClass)
875
876 Return a sorted sequence of method names found within *testCaseClass*;
877 this should be a subclass of :class:`TestCase`.
878
879 The following attributes of a :class:`TestLoader` can be configured either by
880 subclassing or assignment on an instance:
881
882
883 .. attribute:: testMethodPrefix
884
885 String giving the prefix of method names which will be interpreted as test
886 methods. The default value is ``'test'``.
887
888 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
889 methods.
890
891
892 .. attribute:: sortTestMethodsUsing
893
894 Function to be used to compare method names when sorting them in
895 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
896 default value is the built-in :func:`cmp` function; the attribute can also
897 be set to :const:`None` to disable the sort.
898
899
900 .. attribute:: suiteClass
901
902 Callable object that constructs a test suite from a list of tests. No
903 methods on the resulting object are needed. The default value is the
904 :class:`TestSuite` class.
905
906 This affects all the :meth:`loadTestsFrom\*` methods.
907
908
909 .. attribute:: classSuiteClass
910
911 Callable object that constructs a test suite for the tests cases from one
912 class. The default value is :class:`ClassTestSuite`.
913
914
915.. class:: TestResult
916
917 This class is used to compile information about which tests have succeeded
918 and which have failed.
919
920 A :class:`TestResult` object stores the results of a set of tests. The
921 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
922 properly recorded; test authors do not need to worry about recording the
923 outcome of tests.
924
925 Testing frameworks built on top of :mod:`unittest` may want access to the
926 :class:`TestResult` object generated by running a set of tests for reporting
927 purposes; a :class:`TestResult` instance is returned by the
928 :meth:`TestRunner.run` method for this purpose.
929
930 :class:`TestResult` instances have the following attributes that will be of
931 interest when inspecting the results of running a set of tests:
932
933
934 .. attribute:: errors
935
936 A list containing 2-tuples of :class:`TestCase` instances and strings
937 holding formatted tracebacks. Each tuple represents a test which raised an
938 unexpected exception.
939
940 .. versionchanged:: 2.2
941
942 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
943
944
945 .. attribute:: failures
946
947 A list containing 2-tuples of :class:`TestCase` instances and strings
948 holding formatted tracebacks. Each tuple represents a test where a failure
949 was explicitly signalled using the :meth:`TestCase.fail\*` or
950 :meth:`TestCase.assert\*` methods.
951
952 .. versionchanged:: 2.2
953
954 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
955
956 .. attribute:: skipped
957
958 A list containing 2-tuples of :class:`TestCase` instances and strings
959 holding the reason for skipping the test.
960
961 .. versionadded:: 2.7
962
963 .. attribute:: expectedFailures
964
965 A list contaning 2-tuples of :class:`TestCase` instances and strings
966 holding formatted tracebacks. Each tuple represents a expected failures
967 of the test case.
968
969 .. attribute:: unexpectedSuccesses
970
971 A list containing :class:`TestCase` instances that were marked as expected
972 failures, but succeeded.
973
974 .. attribute:: shouldStop
975
976 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
977
978
979 .. attribute:: testsRun
980
981 The total number of tests run so far.
982
983
984 .. method:: wasSuccessful()
985
986 Return :const:`True` if all tests run so far have passed, otherwise returns
987 :const:`False`.
988
989
990 .. method:: stop()
991
992 This method can be called to signal that the set of tests being run should
993 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
994 :class:`TestRunner` objects should respect this flag and return without
995 running any additional tests.
996
997 For example, this feature is used by the :class:`TextTestRunner` class to
998 stop the test framework when the user signals an interrupt from the
999 keyboard. Interactive tools which provide :class:`TestRunner`
1000 implementations can use this in a similar manner.
1001
1002 The following methods of the :class:`TestResult` class are used to maintain
1003 the internal data structures, and may be extended in subclasses to support
1004 additional reporting requirements. This is particularly useful in building
1005 tools which support interactive reporting while tests are being run.
1006
1007
1008 .. method:: startTest(test)
1009
1010 Called when the test case *test* is about to be run.
1011
1012 The default implementation simply increments the instance's :attr:`testsRun`
1013 counter.
1014
1015
1016 .. method:: stopTest(test)
1017
1018 Called after the test case *test* has been executed, regardless of the
1019 outcome.
1020
1021 The default implementation does nothing.
1022
1023
1024 .. method:: addError(test, err)
1025
1026 Called when the test case *test* raises an unexpected exception *err* is a
1027 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1028 traceback)``.
1029
1030 The default implementation appends a tuple ``(test, formatted_err)`` to
1031 the instance's :attr:`errors` attribute, where *formatted_err* is a
1032 formatted traceback derived from *err*.
1033
1034
1035 .. method:: addFailure(test, err)
1036
1037 Called when the test case *test* signals a failure. *err* is a tuple of the form
1038 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1039
1040 The default implementation appends a tuple ``(test, formatted_err)`` to
1041 the instance's :attr:`failures` attribute, where *formatted_err* is a
1042 formatted traceback derived from *err*.
1043
1044
1045 .. method:: addSuccess(test)
1046
1047 Called when the test case *test* succeeds.
1048
1049 The default implementation does nothing.
1050
1051
1052 .. method:: addSkip(test, reason)
1053
1054 Called when the test case *test* is skipped. *reason* is the reason the
1055 test gave for skipping.
1056
1057 The default implementation appends a tuple ``(test, reason)`` to the
1058 instance's :attr:`skipped` attribute.
1059
1060
1061 .. method:: addExpectedFailure(test, err)
1062
1063 Called when the test case *test* fails, but was marked with the
1064 :func:`expectedFailure` decorator.
1065
1066 The default implementation appends a tuple ``(test, formatted_err)`` to
1067 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1068 is a formatted traceback derived from *err*.
1069
1070
1071 .. method:: addUnexpectedSuccess(test)
1072
1073 Called when the test case *test* was marked with the
1074 :func:`expectedFailure` decorator, but succeeded.
1075
1076 The default implementation appends the test to the instance's
1077 :attr:`unexpectedSuccesses` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001078
1079
1080.. data:: defaultTestLoader
1081
1082 Instance of the :class:`TestLoader` class intended to be shared. If no
1083 customization of the :class:`TestLoader` is needed, this instance can be used
1084 instead of repeatedly creating new instances.
1085
1086
1087.. class:: TextTestRunner([stream[, descriptions[, verbosity]]])
1088
1089 A basic test runner implementation which prints results on standard error. It
1090 has a few configurable parameters, but is essentially very simple. Graphical
1091 applications which run test suites should provide alternate implementations.
1092
1093
1094.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader]]]]])
1095
1096 A command-line program that runs a set of tests; this is primarily for making
1097 test modules conveniently executable. The simplest use for this function is to
1098 include the following line at the end of a test script::
1099
1100 if __name__ == '__main__':
1101 unittest.main()
1102
1103 The *testRunner* argument can either be a test runner class or an already
1104 created instance of it.