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