blob: 689f1f28403ae29b79846b275296be0306e06a3e [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
14
15The Python unit testing framework, sometimes referred to as "PyUnit," is a
16Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
17turn, a Java version of Kent's Smalltalk testing framework. Each is the de
18facto standard unit testing framework for its respective language.
19
20:mod:`unittest` supports test automation, sharing of setup and shutdown code for
21tests, aggregation of tests into collections, and independence of the tests from
22the reporting framework. The :mod:`unittest` module provides classes that make
23it easy to support these qualities for a set of tests.
24
25To achieve this, :mod:`unittest` supports some important concepts:
26
27test fixture
28 A :dfn:`test fixture` represents the preparation needed to perform one or more
29 tests, and any associate cleanup actions. This may involve, for example,
30 creating temporary or proxy databases, directories, or starting a server
31 process.
32
33test case
34 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
35 response to a particular set of inputs. :mod:`unittest` provides a base class,
36 :class:`TestCase`, which may be used to create new test cases.
37
38test suite
39 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
40 used to aggregate tests that should be executed together.
41
42test runner
43 A :dfn:`test runner` is a component which orchestrates the execution of tests
44 and provides the outcome to the user. The runner may use a graphical interface,
45 a textual interface, or return a special value to indicate the results of
46 executing the tests.
47
48The test case and test fixture concepts are supported through the
49:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
50used when creating new tests, and the latter can be used when integrating
51existing test code with a :mod:`unittest`\ -driven framework. When building test
52fixtures using :class:`TestCase`, the :meth:`setUp` and :meth:`tearDown` methods
53can be overridden to provide initialization and cleanup for the fixture. With
54:class:`FunctionTestCase`, existing functions can be passed to the constructor
55for these purposes. When the test is run, the fixture initialization is run
56first; if it succeeds, the cleanup method is run after the test has been
57executed, regardless of the outcome of the test. Each instance of the
58:class:`TestCase` will only be used to run a single test method, so a new
59fixture is created for each test.
60
61Test suites are implemented by the :class:`TestSuite` class. This class allows
62individual tests and test suites to be aggregated; when the suite is executed,
63all tests added directly to the suite and in "child" test suites are run.
64
65A test runner is an object that provides a single method, :meth:`run`, which
66accepts a :class:`TestCase` or :class:`TestSuite` object as a parameter, and
67returns a result object. The class :class:`TestResult` is provided for use as
68the result object. :mod:`unittest` provides the :class:`TextTestRunner` as an
69example test runner which reports test results on the standard error stream by
70default. Alternate runners can be implemented for other environments (such as
71graphical environments) without any need to derive from a specific class.
72
73
74.. seealso::
75
76 Module :mod:`doctest`
77 Another test-support module with a very different flavor.
78
79 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
80 Kent Beck's original paper on testing frameworks using the pattern shared by
81 :mod:`unittest`.
82
Raymond Hettingerf7009762009-03-24 00:21:36 +000083 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
84 Third-party unittest frameworks with a lighter-weight syntax
85 for writing tests. For example, ``assert func(10) == 42``.
86
87 `python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
88 Tools for creating mock test objects (objects simulating external resources).
Georg Brandl8ec7f652007-08-15 14:28:01 +000089
90.. _unittest-minimal-example:
91
92Basic example
93-------------
94
95The :mod:`unittest` module provides a rich set of tools for constructing and
96running tests. This section demonstrates that a small subset of the tools
97suffice to meet the needs of most users.
98
99Here is a short script to test three functions from the :mod:`random` module::
100
101 import random
102 import unittest
103
104 class TestSequenceFunctions(unittest.TestCase):
105
106 def setUp(self):
107 self.seq = range(10)
108
Ezio Melotti5d702382010-02-28 03:42:56 +0000109 def test_shuffle(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000110 # make sure the shuffled sequence does not lose any elements
111 random.shuffle(self.seq)
112 self.seq.sort()
113 self.assertEqual(self.seq, range(10))
114
Ezio Melotti5d702382010-02-28 03:42:56 +0000115 def test_choice(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000116 element = random.choice(self.seq)
Ezio Melottif85bba52010-02-04 20:22:44 +0000117 self.assertTrue(element in self.seq)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000118
Ezio Melotti5d702382010-02-28 03:42:56 +0000119 def test_sample(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000120 self.assertRaises(ValueError, random.sample, self.seq, 20)
121 for element in random.sample(self.seq, 5):
Ezio Melottif85bba52010-02-04 20:22:44 +0000122 self.assertTrue(element in self.seq)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000123
124 if __name__ == '__main__':
125 unittest.main()
126
127A testcase is created by subclassing :class:`unittest.TestCase`. The three
128individual tests are defined with methods whose names start with the letters
129``test``. This naming convention informs the test runner about which methods
130represent tests.
131
132The crux of each test is a call to :meth:`assertEqual` to check for an expected
133result; :meth:`assert_` to verify a condition; or :meth:`assertRaises` to verify
134that an expected exception gets raised. These methods are used instead of the
135:keyword:`assert` statement so the test runner can accumulate all test results
136and produce a report.
137
138When a :meth:`setUp` method is defined, the test runner will run that method
139prior to each test. Likewise, if a :meth:`tearDown` method is defined, the test
140runner will invoke that method after each test. In the example, :meth:`setUp`
141was used to create a fresh sequence for each test.
142
143The final block shows a simple way to run the tests. :func:`unittest.main`
144provides a command line interface to the test script. When run from the command
145line, the above script produces an output that looks like this::
146
147 ...
148 ----------------------------------------------------------------------
149 Ran 3 tests in 0.000s
150
151 OK
152
153Instead of :func:`unittest.main`, there are other ways to run the tests with a
154finer level of control, less terse output, and no requirement to be run from the
155command line. For example, the last two lines may be replaced with::
156
157 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
158 unittest.TextTestRunner(verbosity=2).run(suite)
159
160Running the revised script from the interpreter or another script produces the
161following output::
162
Ezio Melotti5d702382010-02-28 03:42:56 +0000163 test_choice (__main__.TestSequenceFunctions) ... ok
164 test_sample (__main__.TestSequenceFunctions) ... ok
165 test_shuffle (__main__.TestSequenceFunctions) ... ok
Georg Brandl8ec7f652007-08-15 14:28:01 +0000166
167 ----------------------------------------------------------------------
168 Ran 3 tests in 0.110s
169
170 OK
171
172The above examples show the most commonly used :mod:`unittest` features which
173are sufficient to meet many everyday testing needs. The remainder of the
174documentation explores the full feature set from first principles.
175
176
177.. _organizing-tests:
178
179Organizing test code
180--------------------
181
182The basic building blocks of unit testing are :dfn:`test cases` --- single
183scenarios that must be set up and checked for correctness. In :mod:`unittest`,
184test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
185class. To make your own test cases you must write subclasses of
186:class:`TestCase`, or use :class:`FunctionTestCase`.
187
188An instance of a :class:`TestCase`\ -derived class is an object that can
189completely run a single test method, together with optional set-up and tidy-up
190code.
191
192The testing code of a :class:`TestCase` instance should be entirely self
193contained, such that it can be run either in isolation or in arbitrary
194combination with any number of other test cases.
195
196The simplest :class:`TestCase` subclass will simply override the :meth:`runTest`
197method in order to perform specific testing code::
198
199 import unittest
200
201 class DefaultWidgetSizeTestCase(unittest.TestCase):
202 def runTest(self):
203 widget = Widget('The widget')
204 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
205
206Note that in order to test something, we use the one of the :meth:`assert\*` or
207:meth:`fail\*` methods provided by the :class:`TestCase` base class. If the
208test fails, an exception will be raised, and :mod:`unittest` will identify the
209test case as a :dfn:`failure`. Any other exceptions will be treated as
210:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
211caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
212caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
213function call.
214
215The way to run a test case will be described later. For now, note that to
216construct an instance of such a test case, we call its constructor without
217arguments::
218
219 testCase = DefaultWidgetSizeTestCase()
220
221Now, such test cases can be numerous, and their set-up can be repetitive. In
222the above case, constructing a :class:`Widget` in each of 100 Widget test case
223subclasses would mean unsightly duplication.
224
225Luckily, we can factor out such set-up code by implementing a method called
226:meth:`setUp`, which the testing framework will automatically call for us when
227we run the test::
228
229 import unittest
230
231 class SimpleWidgetTestCase(unittest.TestCase):
232 def setUp(self):
233 self.widget = Widget('The widget')
234
235 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
236 def runTest(self):
Ezio Melottif85bba52010-02-04 20:22:44 +0000237 self.assertEqual(self.widget.size(), (50,50),
238 'incorrect default size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000239
240 class WidgetResizeTestCase(SimpleWidgetTestCase):
241 def runTest(self):
242 self.widget.resize(100,150)
Ezio Melottif85bba52010-02-04 20:22:44 +0000243 self.assertEqual(self.widget.size(), (100,150),
244 'wrong size after resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000245
246If the :meth:`setUp` method raises an exception while the test is running, the
247framework will consider the test to have suffered an error, and the
248:meth:`runTest` method will not be executed.
249
250Similarly, we can provide a :meth:`tearDown` method that tidies up after the
251:meth:`runTest` method has been run::
252
253 import unittest
254
255 class SimpleWidgetTestCase(unittest.TestCase):
256 def setUp(self):
257 self.widget = Widget('The widget')
258
259 def tearDown(self):
260 self.widget.dispose()
261 self.widget = None
262
263If :meth:`setUp` succeeded, the :meth:`tearDown` method will be run whether
264:meth:`runTest` succeeded or not.
265
266Such a working environment for the testing code is called a :dfn:`fixture`.
267
268Often, many small test cases will use the same fixture. In this case, we would
269end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
270classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000271discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
272mechanism::
273
274 import unittest
275
276 class WidgetTestCase(unittest.TestCase):
277 def setUp(self):
278 self.widget = Widget('The widget')
279
280 def tearDown(self):
281 self.widget.dispose()
282 self.widget = None
283
Ezio Melotti5d702382010-02-28 03:42:56 +0000284 def test_default_size(self):
Ezio Melottif85bba52010-02-04 20:22:44 +0000285 self.assertEqual(self.widget.size(), (50,50),
286 'incorrect default size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000287
Ezio Melotti5d702382010-02-28 03:42:56 +0000288 def test_resize(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000289 self.widget.resize(100,150)
Ezio Melottif85bba52010-02-04 20:22:44 +0000290 self.assertEqual(self.widget.size(), (100,150),
291 'wrong size after resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000292
Ezio Melotti5d702382010-02-28 03:42:56 +0000293Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
294provided two different test methods. Class instances will now each run one of
295the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
296separately for each instance. When creating an instance we must specify the
297test method it is to run. We do this by passing the method name in the
298constructor::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000299
Ezio Melotti5d702382010-02-28 03:42:56 +0000300 defaultSizeTestCase = WidgetTestCase('test_default_size')
301 resizeTestCase = WidgetTestCase('test_resize')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000302
303Test case instances are grouped together according to the features they test.
304:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
305represented by :mod:`unittest`'s :class:`TestSuite` class::
306
307 widgetTestSuite = unittest.TestSuite()
Ezio Melotti5d702382010-02-28 03:42:56 +0000308 widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
309 widgetTestSuite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000310
311For the ease of running tests, as we will see later, it is a good idea to
312provide in each test module a callable object that returns a pre-built test
313suite::
314
315 def suite():
316 suite = unittest.TestSuite()
Ezio Melotti5d702382010-02-28 03:42:56 +0000317 suite.addTest(WidgetTestCase('test_default_size'))
318 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000319 return suite
320
321or even::
322
323 def suite():
Ezio Melotti5d702382010-02-28 03:42:56 +0000324 tests = ['test_default_size', 'test_resize']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000325
326 return unittest.TestSuite(map(WidgetTestCase, tests))
327
328Since it is a common pattern to create a :class:`TestCase` subclass with many
329similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
330class that can be used to automate the process of creating a test suite and
331populating it with individual tests. For example, ::
332
333 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
334
Ezio Melotti5d702382010-02-28 03:42:56 +0000335will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
336``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
Georg Brandl8ec7f652007-08-15 14:28:01 +0000337name prefix to identify test methods automatically.
338
339Note that the order in which the various test cases will be run is determined by
340sorting the test function names with the built-in :func:`cmp` function.
341
342Often it is desirable to group suites of test cases together, so as to run tests
343for the whole system at once. This is easy, since :class:`TestSuite` instances
344can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
345added to a :class:`TestSuite`::
346
347 suite1 = module1.TheTestSuite()
348 suite2 = module2.TheTestSuite()
349 alltests = unittest.TestSuite([suite1, suite2])
350
351You can place the definitions of test cases and test suites in the same modules
352as the code they are to test (such as :file:`widget.py`), but there are several
353advantages to placing the test code in a separate module, such as
354:file:`test_widget.py`:
355
356* The test module can be run standalone from the command line.
357
358* The test code can more easily be separated from shipped code.
359
360* There is less temptation to change test code to fit the code it tests without
361 a good reason.
362
363* Test code should be modified much less frequently than the code it tests.
364
365* Tested code can be refactored more easily.
366
367* Tests for modules written in C must be in separate modules anyway, so why not
368 be consistent?
369
370* If the testing strategy changes, there is no need to change the source code.
371
372
373.. _legacy-unit-tests:
374
375Re-using old test code
376----------------------
377
378Some users will find that they have existing test code that they would like to
379run from :mod:`unittest`, without converting every old test function to a
380:class:`TestCase` subclass.
381
382For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
383This subclass of :class:`TestCase` can be used to wrap an existing test
384function. Set-up and tear-down functions can also be provided.
385
386Given the following test function::
387
388 def testSomething():
389 something = makeSomething()
390 assert something.name is not None
391 # ...
392
393one can create an equivalent test case instance as follows::
394
395 testcase = unittest.FunctionTestCase(testSomething)
396
397If there are additional set-up and tear-down methods that should be called as
398part of the test case's operation, they can also be provided like so::
399
400 testcase = unittest.FunctionTestCase(testSomething,
401 setUp=makeSomethingDB,
402 tearDown=deleteSomethingDB)
403
404To make migrating existing test suites easier, :mod:`unittest` supports tests
405raising :exc:`AssertionError` to indicate test failure. However, it is
406recommended that you use the explicit :meth:`TestCase.fail\*` and
407:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
408may treat :exc:`AssertionError` differently.
409
410.. note::
411
412 Even though :class:`FunctionTestCase` can be used to quickly convert an existing
413 test base over to a :mod:`unittest`\ -based system, this approach is not
414 recommended. Taking the time to set up proper :class:`TestCase` subclasses will
415 make future test refactorings infinitely easier.
416
417
418.. _unittest-contents:
419
420Classes and functions
421---------------------
422
423
424.. class:: TestCase([methodName])
425
426 Instances of the :class:`TestCase` class represent the smallest testable units
427 in the :mod:`unittest` universe. This class is intended to be used as a base
428 class, with specific tests being implemented by concrete subclasses. This class
429 implements the interface needed by the test runner to allow it to drive the
430 test, and methods that the test code can use to check for and report various
431 kinds of failure.
432
433 Each instance of :class:`TestCase` will run a single test method: the method
434 named *methodName*. If you remember, we had an earlier example that went
435 something like this::
436
437 def suite():
438 suite = unittest.TestSuite()
Ezio Melotti5d702382010-02-28 03:42:56 +0000439 suite.addTest(WidgetTestCase('test_default_size'))
440 suite.addTest(WidgetTestCase('test_resize'))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000441 return suite
442
443 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
444 single test.
445
446 *methodName* defaults to ``'runTest'``.
447
448
449.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
450
451 This class implements the portion of the :class:`TestCase` interface which
452 allows the test runner to drive the test, but does not provide the methods which
453 test code can use to check and report errors. This is used to create test cases
454 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
455 -based test framework.
456
457
458.. class:: TestSuite([tests])
459
460 This class represents an aggregation of individual tests cases and test suites.
461 The class presents the interface needed by the test runner to allow it to be run
462 as any other test case. Running a :class:`TestSuite` instance is the same as
463 iterating over the suite, running each test individually.
464
465 If *tests* is given, it must be an iterable of individual test cases or other
466 test suites that will be used to build the suite initially. Additional methods
467 are provided to add test cases and suites to the collection later on.
468
469
470.. class:: TestLoader()
471
472 This class is responsible for loading tests according to various criteria and
473 returning them wrapped in a :class:`TestSuite`. It can load all tests within a
474 given module or :class:`TestCase` subclass.
475
476
477.. class:: TestResult()
478
479 This class is used to compile information about which tests have succeeded and
480 which have failed.
481
482
483.. data:: defaultTestLoader
484
485 Instance of the :class:`TestLoader` class intended to be shared. If no
486 customization of the :class:`TestLoader` is needed, this instance can be used
487 instead of repeatedly creating new instances.
488
489
490.. class:: TextTestRunner([stream[, descriptions[, verbosity]]])
491
492 A basic test runner implementation which prints results on standard error. It
493 has a few configurable parameters, but is essentially very simple. Graphical
494 applications which run test suites should provide alternate implementations.
495
496
497.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader]]]]])
498
499 A command-line program that runs a set of tests; this is primarily for making
500 test modules conveniently executable. The simplest use for this function is to
501 include the following line at the end of a test script::
502
503 if __name__ == '__main__':
504 unittest.main()
505
506 The *testRunner* argument can either be a test runner class or an already
507 created instance of it.
508
509In some cases, the existing tests may have been written using the :mod:`doctest`
510module. If so, that module provides a :class:`DocTestSuite` class that can
511automatically build :class:`unittest.TestSuite` instances from the existing
512:mod:`doctest`\ -based tests.
513
514.. versionadded:: 2.3
515
516
517.. _testcase-objects:
518
519TestCase Objects
520----------------
521
522Each :class:`TestCase` instance represents a single test, but each concrete
523subclass may be used to define multiple tests --- the concrete class represents
524a single test fixture. The fixture is created and cleaned up for each test
525case.
526
527:class:`TestCase` instances provide three groups of methods: one group used to
528run the test, another used by the test implementation to check conditions and
529report failures, and some inquiry methods allowing information about the test
530itself to be gathered.
531
532Methods in the first group (running the test) are:
533
534
535.. method:: TestCase.setUp()
536
537 Method called to prepare the test fixture. This is called immediately before
538 calling the test method; any exception raised by this method will be considered
539 an error rather than a test failure. The default implementation does nothing.
540
541
542.. method:: TestCase.tearDown()
543
544 Method called immediately after the test method has been called and the result
545 recorded. This is called even if the test method raised an exception, so the
546 implementation in subclasses may need to be particularly careful about checking
547 internal state. Any exception raised by this method will be considered an error
548 rather than a test failure. This method will only be called if the
549 :meth:`setUp` succeeds, regardless of the outcome of the test method. The
550 default implementation does nothing.
551
552
553.. method:: TestCase.run([result])
554
555 Run the test, collecting the result into the test result object passed as
556 *result*. If *result* is omitted or :const:`None`, a temporary result object is
557 created (by calling the :meth:`defaultTestCase` method) and used; this result
558 object is not returned to :meth:`run`'s caller.
559
560 The same effect may be had by simply calling the :class:`TestCase` instance.
561
562
563.. method:: TestCase.debug()
564
565 Run the test without collecting the result. This allows exceptions raised by
566 the test to be propagated to the caller, and can be used to support running
567 tests under a debugger.
568
569The test code can use any of the following methods to check for and report
570failures.
571
572
573.. method:: TestCase.assert_(expr[, msg])
574 TestCase.failUnless(expr[, msg])
Georg Brandlc557db52008-03-09 15:11:39 +0000575 TestCase.assertTrue(expr[, msg])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000576
577 Signal a test failure if *expr* is false; the explanation for the error will be
578 *msg* if given, otherwise it will be :const:`None`.
579
580
581.. method:: TestCase.assertEqual(first, second[, msg])
582 TestCase.failUnlessEqual(first, second[, msg])
583
584 Test that *first* and *second* are equal. If the values do not compare equal,
585 the test will fail with the explanation given by *msg*, or :const:`None`. Note
586 that using :meth:`failUnlessEqual` improves upon doing the comparison as the
587 first parameter to :meth:`failUnless`: the default value for *msg* can be
588 computed to include representations of both *first* and *second*.
589
590
591.. method:: TestCase.assertNotEqual(first, second[, msg])
592 TestCase.failIfEqual(first, second[, msg])
593
594 Test that *first* and *second* are not equal. If the values do compare equal,
595 the test will fail with the explanation given by *msg*, or :const:`None`. Note
596 that using :meth:`failIfEqual` improves upon doing the comparison as the first
597 parameter to :meth:`failUnless` is that the default value for *msg* can be
598 computed to include representations of both *first* and *second*.
599
600
601.. method:: TestCase.assertAlmostEqual(first, second[, places[, msg]])
602 TestCase.failUnlessAlmostEqual(first, second[, places[, msg]])
603
604 Test that *first* and *second* are approximately equal by computing the
Georg Brandl734373c2009-01-03 21:55:17 +0000605 difference, rounding to the given number of decimal *places* (default 7),
Georg Brandl45173232008-09-21 07:15:59 +0000606 and comparing to zero.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000607 Note that comparing a given number of decimal places is not the same as
608 comparing a given number of significant digits. If the values do not compare
609 equal, the test will fail with the explanation given by *msg*, or :const:`None`.
610
611
612.. method:: TestCase.assertNotAlmostEqual(first, second[, places[, msg]])
613 TestCase.failIfAlmostEqual(first, second[, places[, msg]])
614
615 Test that *first* and *second* are not approximately equal by computing the
Georg Brandl734373c2009-01-03 21:55:17 +0000616 difference, rounding to the given number of decimal *places* (default 7),
Georg Brandl45173232008-09-21 07:15:59 +0000617 and comparing to zero.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000618 Note that comparing a given number of decimal places is not the same as
619 comparing a given number of significant digits. If the values do not compare
620 equal, the test will fail with the explanation given by *msg*, or :const:`None`.
621
622
623.. method:: TestCase.assertRaises(exception, callable, ...)
624 TestCase.failUnlessRaises(exception, callable, ...)
625
626 Test that an exception is raised when *callable* is called with any positional
627 or keyword arguments that are also passed to :meth:`assertRaises`. The test
628 passes if *exception* is raised, is an error if another exception is raised, or
629 fails if no exception is raised. To catch any of a group of exceptions, a tuple
630 containing the exception classes may be passed as *exception*.
631
632
633.. method:: TestCase.failIf(expr[, msg])
Georg Brandlc557db52008-03-09 15:11:39 +0000634 TestCase.assertFalse(expr[, msg])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
636 The inverse of the :meth:`failUnless` method is the :meth:`failIf` method. This
637 signals a test failure if *expr* is true, with *msg* or :const:`None` for the
638 error message.
639
640
641.. method:: TestCase.fail([msg])
642
643 Signals a test failure unconditionally, with *msg* or :const:`None` for the
644 error message.
645
646
647.. attribute:: TestCase.failureException
648
649 This class attribute gives the exception raised by the :meth:`test` method. If
650 a test framework needs to use a specialized exception, possibly to carry
651 additional information, it must subclass this exception in order to "play fair"
652 with the framework. The initial value of this attribute is
653 :exc:`AssertionError`.
654
655Testing frameworks can use the following methods to collect information on the
656test:
657
658
659.. method:: TestCase.countTestCases()
660
661 Return the number of tests represented by this test object. For
662 :class:`TestCase` instances, this will always be ``1``.
663
664
665.. method:: TestCase.defaultTestResult()
666
667 Return an instance of the test result class that should be used for this test
668 case class (if no other result instance is provided to the :meth:`run` method).
669
670 For :class:`TestCase` instances, this will always be an instance of
671 :class:`TestResult`; subclasses of :class:`TestCase` should override this as
672 necessary.
673
674
675.. method:: TestCase.id()
676
677 Return a string identifying the specific test case. This is usually the full
678 name of the test method, including the module and class name.
679
680
681.. method:: TestCase.shortDescription()
682
683 Returns a one-line description of the test, or :const:`None` if no description
684 has been provided. The default implementation of this method returns the first
685 line of the test method's docstring, if available, or :const:`None`.
686
687
688.. _testsuite-objects:
689
690TestSuite Objects
691-----------------
692
693:class:`TestSuite` objects behave much like :class:`TestCase` objects, except
694they do not actually implement a test. Instead, they are used to aggregate
695tests into groups of tests that should be run together. Some additional methods
696are available to add tests to :class:`TestSuite` instances:
697
698
699.. method:: TestSuite.addTest(test)
700
701 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
702
703
704.. method:: TestSuite.addTests(tests)
705
706 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
707 instances to this test suite.
708
709 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
710 element.
711
712:class:`TestSuite` shares the following methods with :class:`TestCase`:
713
714
715.. method:: TestSuite.run(result)
716
717 Run the tests associated with this suite, collecting the result into the test
718 result object passed as *result*. Note that unlike :meth:`TestCase.run`,
719 :meth:`TestSuite.run` requires the result object to be passed in.
720
721
722.. method:: TestSuite.debug()
723
724 Run the tests associated with this suite without collecting the result. This
725 allows exceptions raised by the test to be propagated to the caller and can be
726 used to support running tests under a debugger.
727
728
729.. method:: TestSuite.countTestCases()
730
731 Return the number of tests represented by this test object, including all
732 individual tests and sub-suites.
733
734In the typical usage of a :class:`TestSuite` object, the :meth:`run` method is
735invoked by a :class:`TestRunner` rather than by the end-user test harness.
736
737
738.. _testresult-objects:
739
740TestResult Objects
741------------------
742
743A :class:`TestResult` object stores the results of a set of tests. The
744:class:`TestCase` and :class:`TestSuite` classes ensure that results are
745properly recorded; test authors do not need to worry about recording the outcome
746of tests.
747
748Testing frameworks built on top of :mod:`unittest` may want access to the
749:class:`TestResult` object generated by running a set of tests for reporting
750purposes; a :class:`TestResult` instance is returned by the
751:meth:`TestRunner.run` method for this purpose.
752
753:class:`TestResult` instances have the following attributes that will be of
754interest when inspecting the results of running a set of tests:
755
756
757.. attribute:: TestResult.errors
758
759 A list containing 2-tuples of :class:`TestCase` instances and strings holding
760 formatted tracebacks. Each tuple represents a test which raised an unexpected
761 exception.
762
763 .. versionchanged:: 2.2
764 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
765
766
767.. attribute:: TestResult.failures
768
769 A list containing 2-tuples of :class:`TestCase` instances and strings holding
770 formatted tracebacks. Each tuple represents a test where a failure was
771 explicitly signalled using the :meth:`TestCase.fail\*` or
772 :meth:`TestCase.assert\*` methods.
773
774 .. versionchanged:: 2.2
775 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
776
777
778.. attribute:: TestResult.testsRun
779
780 The total number of tests run so far.
781
782
783.. method:: TestResult.wasSuccessful()
784
785 Returns :const:`True` if all tests run so far have passed, otherwise returns
786 :const:`False`.
787
788
789.. method:: TestResult.stop()
790
791 This method can be called to signal that the set of tests being run should be
792 aborted by setting the :class:`TestResult`'s ``shouldStop`` attribute to
793 :const:`True`. :class:`TestRunner` objects should respect this flag and return
794 without running any additional tests.
795
796 For example, this feature is used by the :class:`TextTestRunner` class to stop
797 the test framework when the user signals an interrupt from the keyboard.
798 Interactive tools which provide :class:`TestRunner` implementations can use this
799 in a similar manner.
800
801The following methods of the :class:`TestResult` class are used to maintain the
802internal data structures, and may be extended in subclasses to support
803additional reporting requirements. This is particularly useful in building
804tools which support interactive reporting while tests are being run.
805
806
807.. method:: TestResult.startTest(test)
808
809 Called when the test case *test* is about to be run.
810
811 The default implementation simply increments the instance's ``testsRun``
812 counter.
813
814
815.. method:: TestResult.stopTest(test)
816
817 Called after the test case *test* has been executed, regardless of the outcome.
818
819 The default implementation does nothing.
820
821
822.. method:: TestResult.addError(test, err)
823
824 Called when the test case *test* raises an unexpected exception *err* is a tuple
825 of the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
826
Georg Brandl586edab2007-11-24 11:39:13 +0000827 The default implementation appends a tuple ``(test, formatted_err)`` to the
828 instance's ``errors`` attribute, where *formatted_err* is a formatted
829 traceback derived from *err*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000830
831
832.. method:: TestResult.addFailure(test, err)
833
834 Called when the test case *test* signals a failure. *err* is a tuple of the form
835 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
836
Georg Brandl586edab2007-11-24 11:39:13 +0000837 The default implementation appends a tuple ``(test, formatted_err)`` to the
838 instance's ``failures`` attribute, where *formatted_err* is a formatted
839 traceback derived from *err*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000840
841
842.. method:: TestResult.addSuccess(test)
843
844 Called when the test case *test* succeeds.
845
846 The default implementation does nothing.
847
848
849.. _testloader-objects:
850
851TestLoader Objects
852------------------
853
854The :class:`TestLoader` class is used to create test suites from classes and
855modules. Normally, there is no need to create an instance of this class; the
856:mod:`unittest` module provides an instance that can be shared as
857``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
858customization of some configurable properties.
859
860:class:`TestLoader` objects have the following methods:
861
862
863.. method:: TestLoader.loadTestsFromTestCase(testCaseClass)
864
865 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
866 :class:`testCaseClass`.
867
868
869.. method:: TestLoader.loadTestsFromModule(module)
870
871 Return a suite of all tests cases contained in the given module. This method
872 searches *module* for classes derived from :class:`TestCase` and creates an
873 instance of the class for each test method defined for the class.
874
875 .. warning::
876
877 While using a hierarchy of :class:`TestCase`\ -derived classes can be convenient
878 in sharing fixtures and helper functions, defining test methods on base classes
879 that are not intended to be instantiated directly does not play well with this
880 method. Doing so, however, can be useful when the fixtures are different and
881 defined in subclasses.
882
883
884.. method:: TestLoader.loadTestsFromName(name[, module])
885
886 Return a suite of all tests cases given a string specifier.
887
888 The specifier *name* is a "dotted name" that may resolve either to a module, a
889 test case class, a test method within a test case class, a :class:`TestSuite`
890 instance, or a callable object which returns a :class:`TestCase` or
891 :class:`TestSuite` instance. These checks are applied in the order listed here;
892 that is, a method on a possible test case class will be picked up as "a test
893 method within a test case class", rather than "a callable object".
894
895 For example, if you have a module :mod:`SampleTests` containing a
896 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
897 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
898 specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
899 suite which will run all three test methods. Using the specifier
900 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
901 which will run only the :meth:`test_two` test method. The specifier can refer
902 to modules and packages which have not been imported; they will be imported as a
903 side-effect.
904
905 The method optionally resolves *name* relative to the given *module*.
906
907
908.. method:: TestLoader.loadTestsFromNames(names[, module])
909
910 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather than
911 a single name. The return value is a test suite which supports all the tests
912 defined for each name.
913
914
915.. method:: TestLoader.getTestCaseNames(testCaseClass)
916
917 Return a sorted sequence of method names found within *testCaseClass*; this
918 should be a subclass of :class:`TestCase`.
919
920The following attributes of a :class:`TestLoader` can be configured either by
921subclassing or assignment on an instance:
922
923
924.. attribute:: TestLoader.testMethodPrefix
925
926 String giving the prefix of method names which will be interpreted as test
927 methods. The default value is ``'test'``.
928
929 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
930 methods.
931
932
933.. attribute:: TestLoader.sortTestMethodsUsing
934
935 Function to be used to compare method names when sorting them in
936 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
937 default value is the built-in :func:`cmp` function; the attribute can also be
938 set to :const:`None` to disable the sort.
939
940
941.. attribute:: TestLoader.suiteClass
942
943 Callable object that constructs a test suite from a list of tests. No methods on
944 the resulting object are needed. The default value is the :class:`TestSuite`
945 class.
946
947 This affects all the :meth:`loadTestsFrom\*` methods.
948