cpython / Doc / library / unittest.rst

:mod:`unittest` --- Unit testing framework

(If you are already familiar with the basic concepts of testing, you might want to skip to :ref:`the list of assert methods <assert-methods>`.)

The :mod:`unittest` unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.

To achieve this, :mod:`unittest` supports some important concepts in an object-oriented way:

test fixture
A :dfn:`test fixture` represents the preparation needed to perform one or more tests, and any associate cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process.
test case
A :dfn:`test case` is the individual unit of testing. It checks for a specific response to a particular set of inputs. :mod:`unittest` provides a base class, :class:`TestCase`, which may be used to create new test cases.
test suite
A :dfn:`test suite` is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.
test runner
A :dfn:`test runner` is a component which orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests.

Basic example

The :mod:`unittest` module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users.

Here is a short script to test three functions from the :mod:`random` module:

import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = list(range(10))

    def test_shuffle(self):
        # make sure the shuffled sequence does not lose any elements
        self.assertEqual(self.seq, list(range(10)))

        # should raise an exception for an immutable sequence
        self.assertRaises(TypeError, random.shuffle, (1,2,3))

    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

    def test_sample(self):
        with self.assertRaises(ValueError):
            random.sample(self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assertTrue(element in self.seq)

if __name__ == '__main__':

A testcase is created by subclassing :class:`unittest.TestCase`. The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests.

The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an expected result; :meth:`~TestCase.assertTrue` to verify a condition; or :meth:`~TestCase.assertRaises` to verify that an expected exception gets raised. These methods are used instead of the :keyword:`assert` statement so the test runner can accumulate all test results and produce a report.

When a :meth:`~TestCase.setUp` method is defined, the test runner will run that method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is defined, the test runner will invoke that method after each test. In the example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each test.

The final block shows a simple way to run the tests. :func:`unittest.main` provides a command-line interface to the test script. When run from the command line, the above script produces an output that looks like this:

Ran 3 tests in 0.000s


Passing the -v option to your test script will instruct :func:`unittest.main` to enable a higher level of verbosity, and produce the following output:

test_choice (__main__.TestSequenceFunctions) ... ok
test_sample (__main__.TestSequenceFunctions) ... ok
test_shuffle (__main__.TestSequenceFunctions) ... ok

Ran 3 tests in 0.110s


The above examples show the most commonly used :mod:`unittest` features which are sufficient to meet many everyday testing needs. The remainder of the documentation explores the full feature set from first principles.

Command-Line Interface

The unittest module can be used from the command line to run tests from modules, classes or even individual test methods:

python -m unittest test_module1 test_module2
python -m unittest test_module.TestClass
python -m unittest test_module.TestClass.test_method

You can pass in a list with any combination of module names, and fully qualified class or method names.

Test modules can be specified by file path as well:

python -m unittest tests/

This allows you to use the shell filename completion to specify the test module. The file specified must still be importable as a module. The path is converted to a module name by removing the '.py' and converting path separators into '.'. If you want to execute a test file that isn't importable as a module you should execute the file directly instead.

You can run tests with more detail (higher verbosity) by passing in the -v flag:

python -m unittest -v test_module

When executed without arguments :ref:`unittest-test-discovery` is started:

python -m unittest

For a list of all the command-line options:

python -m unittest -h

Command-line options

:program:`unittest` supports these command-line options:

The command line can also be used for test discovery, for running all of the tests in a project or just a subset.

Test Discovery

Unittest supports simple test discovery. In order to be compatible with test discovery, all of the test files must be :ref:`modules <tut-modules>` or :ref:`packages <tut-packages>` importable from the top-level directory of the project (this means that their filenames must be valid :ref:`identifiers <identifiers>`).

Test discovery is implemented in :meth:``, but can also be used from the command line. The basic command-line usage is:

cd project_directory
python -m unittest discover


As a shortcut, python -m unittest is the equivalent of python -m unittest discover. If you want to pass arguments to test discovery the discover sub-command must be used explicitly.

The discover sub-command has the following options:

The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in as positional arguments in that order. The following two command lines are equivalent:

python -m unittest discover -s project_directory -p '*'
python -m unittest discover project_directory '*'

As well as being a path it is possible to pass a package name, for example myproject.subpackage.test, as the start directory. The package name you supply will then be imported and its location on the filesystem will be used as the start directory.


Test discovery loads tests by importing them. Once test discovery has found all the test files from the start directory you specify it turns the paths into package names to import. For example :file:`foo/bar/` will be imported as

If you have a package installed globally and attempt test discovery on a different copy of the package then the import could happen from the wrong place. If this happens test discovery will warn you and exit.

If you supply the start directory as a package name rather than a path to a directory then discover assumes that whichever location it imports from is the location you intended, so you will not get the warning.

Test modules and packages can customize test loading and discovery by through the load_tests protocol.

Organizing test code

The basic building blocks of unit testing are :dfn:`test cases` --- single scenarios that must be set up and checked for correctness. In :mod:`unittest`, test cases are represented by :class:`unittest.TestCase` instances. To make your own test cases you must write subclasses of :class:`TestCase` or use :class:`FunctionTestCase`.

The testing code of a :class:`TestCase` instance should be entirely self contained, such that it can be run either in isolation or in arbitrary combination with any number of other test cases.

The simplest :class:`TestCase` subclass will simply implement a test method (i.e. a method whose name starts with test) in order to perform specific testing code:

import unittest

class DefaultWidgetSizeTestCase(unittest.TestCase):
    def test_default_widget_size(self):
        widget = Widget('The widget')
        self.assertEqual(widget.size(), (50, 50))

Note that in order to test something, we use one of the :meth:`assert\*` methods provided by the :class:`TestCase` base class. If the test fails, an exception will be raised, and :mod:`unittest` will identify the test case as a :dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`.

Tests can be numerous, and their set-up can be repetitive. Luckily, we can factor out set-up code by implementing a method called :meth:`~TestCase.setUp`, which the testing framework will automatically call for every single test we run:

import unittest

class SimpleWidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def test_default_widget_size(self):
        self.assertEqual(self.widget.size(), (50,50),
                         'incorrect default size')

    def test_widget_resize(self):
        self.assertEqual(self.widget.size(), (100,150),
                         'wrong size after resize')


The order in which the various tests will be run is determined by sorting the test method names with respect to the built-in ordering for strings.

If the :meth:`~TestCase.setUp` method raises an exception while the test is running, the framework will consider the test to have suffered an error, and the test method will not be executed.

Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up after the test method has been run:

import unittest

class SimpleWidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def tearDown(self):

If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be run whether the test method succeeded or not.

Such a working environment for the testing code is called a :dfn:`fixture`.

Test case instances are grouped together according to the features they test. :mod:`unittest` provides a mechanism for this: the :dfn:`test suite`, represented by :mod:`unittest`'s :class:`TestSuite` class. In most cases, calling :func:`unittest.main` will do the right thing and collect all the module's test cases for you, and then execute them.

However, should you want to customize the building of your test suite, you can do it yourself:

def suite():
    suite = unittest.TestSuite()
    return suite

You can place the definitions of test cases and test suites in the same modules as the code they are to test (such as :file:``), but there are several advantages to placing the test code in a separate module, such as :file:``:

  • The test module can be run standalone from the command line.
  • The test code can more easily be separated from shipped code.
  • There is less temptation to change test code to fit the code it tests without a good reason.
  • Test code should be modified much less frequently than the code it tests.
  • Tested code can be refactored more easily.
  • Tests for modules written in C must be in separate modules anyway, so why not be consistent?
  • If the testing strategy changes, there is no need to change the source code.

Re-using old test code

Some users will find that they have existing test code that they would like to run from :mod:`unittest`, without converting every old test function to a :class:`TestCase` subclass.

For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class. This subclass of :class:`TestCase` can be used to wrap an existing test function. Set-up and tear-down functions can also be provided.

Given the following test function:

def testSomething():
    something = makeSomething()
    assert is not None
    # ...

one can create an equivalent test case instance as follows, with optional set-up and tear-down methods:

testcase = unittest.FunctionTestCase(testSomething,


Even though :class:`FunctionTestCase` can be used to quickly convert an existing test base over to a :mod:`unittest`-based system, this approach is not recommended. Taking the time to set up proper :class:`TestCase` subclasses will make future test refactorings infinitely easier.

In some cases, the existing tests may have been written using the :mod:`doctest` module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can automatically build :class:`unittest.TestSuite` instances from the existing :mod:`doctest`-based tests.

Skipping tests and expected failures

Unittest supports skipping individual test methods and even whole classes of tests. In addition, it supports marking a test as a "expected failure," a test that is broken and will fail, but shouldn't be counted as a failure on a :class:`TestResult`.

Skipping a test is simply a matter of using the :func:`skip` :term:`decorator` or one of its conditional variants.

Basic skipping looks like this:

class MyTestCase(unittest.TestCase):

    @unittest.skip("demonstrating skipping")
    def test_nothing(self):"shouldn't happen")

    @unittest.skipIf(mylib.__version__ < (1, 3),
                     "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.

    @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_windows_support(self):
        # windows specific testing code

This is the output of running the example above in verbose mode:

test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'

Ran 3 tests in 0.005s

OK (skipped=3)

Classes can be skipped just like methods:

@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
    def test_not_run(self):

:meth:`TestCase.setUp` can also skip the test. This is useful when a resource that needs to be set up is not available.

Expected failures use the :func:`expectedFailure` decorator.

class ExpectedFailureTestCase(unittest.TestCase):
    def test_fail(self):
        self.assertEqual(1, 0, "broken")

It's easy to roll your own skipping decorators by making a decorator that calls :func:`skip` on the test when it wants it to be skipped. This decorator skips the test unless the passed object has a certain attribute:

def skipUnlessHasattr(obj, attr):
    if hasattr(obj, attr):
        return lambda func: func
    return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))

The following decorators implement test skipping and expected failures:

Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them. Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.

Distinguishing test iterations using subtests

When some of your tests differ only by a some very small differences, for instance some parameters, unittest allows you to distinguish them inside the body of a test method using the :meth:`~TestCase.subTest` context manager.

For example, the following test:

class NumbersTest(unittest.TestCase):

    def test_even(self):
        Test that numbers between 0 and 5 are all even.
        for i in range(0, 6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)

will produce the following output:

FAIL: test_even (__main__.NumbersTest) (i=1)
Traceback (most recent call last):
  File "", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

FAIL: test_even (__main__.NumbersTest) (i=3)
Traceback (most recent call last):
  File "", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

FAIL: test_even (__main__.NumbersTest) (i=5)
Traceback (most recent call last):
  File "", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

Without using a subtest, execution would stop after the first failure, and the error would be less easy to diagnose because the value of i wouldn't be displayed:

FAIL: test_even (__main__.NumbersTest)
Traceback (most recent call last):
  File "", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

Classes and functions

This section describes in depth the API of :mod:`unittest`.

Test cases

Instances of the :class:`TestCase` class represent the logical test units in the :mod:`unittest` universe. This class is intended to be used as a base class, with specific tests being implemented by concrete subclasses. This class implements the interface needed by the test runner to allow it to drive the tests, and methods that the test code can use to check for and report various kinds of failure.

Each instance of :class:`TestCase` will run a single base method: the method named methodName. However, the standard implementation of the default methodName, runTest(), will run every method starting with test as an individual test, and count successes and failures accordingly. Therefore, in most uses of :class:`TestCase`, you will neither change the methodName nor reimplement the default runTest() method.

:class:`TestCase` instances provide three groups of methods: one group used to run the test, another used by the test implementation to check conditions and report failures, and some inquiry methods allowing information about the test itself to be gathered.

Methods in the first group (running the test) are:

The :class:`TestCase` class provides a number of methods to check for and report failures, such as:

Method Checks that New in
:meth:`assertEqual(a, b) <TestCase.assertEqual>` a == b  
:meth:`assertNotEqual(a, b) <TestCase.assertNotEqual>` a != b  
:meth:`assertTrue(x) <TestCase.assertTrue>` bool(x) is True  
:meth:`assertFalse(x) <TestCase.assertFalse>` bool(x) is False  
:meth:`assertIs(a, b) <TestCase.assertIs>` a is b 3.1
:meth:`assertIsNot(a, b) <TestCase.assertIsNot>` a is not b 3.1
:meth:`assertIsNone(x) <TestCase.assertIsNone>` x is None 3.1
:meth:`assertIsNotNone(x) <TestCase.assertIsNotNone>` x is not None 3.1
:meth:`assertIn(a, b) <TestCase.assertIn>` a in b 3.1
:meth:`assertNotIn(a, b) <TestCase.assertNotIn>` a not in b 3.1
:meth:`assertIsInstance(a, b) <TestCase.assertIsInstance>` isinstance(a, b) 3.2
:meth:`assertNotIsInstance(a, b) <TestCase.assertNotIsInstance>` not isinstance(a, b) 3.2

All the assert methods accept a msg argument that, if specified, is used as the error message on failure (see also :data:`longMessage`). Note that the msg keyword argument can be passed to :meth:`assertRaises`, :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex` only when they are used as a context manager.

It is also possible to check that exceptions and warnings are raised using the following methods:

Method Checks that New in
:meth:`assertRaises(exc, fun, *args, **kwds) <TestCase.assertRaises>` fun(*args, **kwds) raises exc  
:meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) <TestCase.assertRaisesRegex>` fun(*args, **kwds) raises exc and the message matches re 3.1
:meth:`assertWarns(warn, fun, *args, **kwds) <TestCase.assertWarns>` fun(*args, **kwds) raises warn 3.2
:meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) <TestCase.assertWarnsRegex>` fun(*args, **kwds) raises warn and the message matches re 3.2

There are also other methods used to perform more specific checks, such as:

Method Checks that New in
:meth:`assertAlmostEqual(a, b) <TestCase.assertAlmostEqual>` round(a-b, 7) == 0  
:meth:`assertNotAlmostEqual(a, b) <TestCase.assertNotAlmostEqual>` round(a-b, 7) != 0  
:meth:`assertGreater(a, b) <TestCase.assertGreater>` a > b 3.1
:meth:`assertGreaterEqual(a, b) <TestCase.assertGreaterEqual>` a >= b 3.1
:meth:`assertLess(a, b) <TestCase.assertLess>` a < b 3.1
:meth:`assertLessEqual(a, b) <TestCase.assertLessEqual>` a <= b 3.1
:meth:`assertRegex(s, re) <TestCase.assertRegex>` 3.1
:meth:`assertNotRegex(s, re) <TestCase.assertNotRegex>` not 3.2
:meth:`assertCountEqual(a, b) <TestCase.assertCountEqual>` a and b have the same elements in the same number, regardless of their order 3.2

The :meth:`assertEqual` method dispatches the equality check for objects of the same type to different type-specific methods. These methods are already implemented for most of the built-in types, but it's also possible to register new methods using :meth:`addTypeEqualityFunc`:

The list of type-specific methods automatically used by :meth:`~TestCase.assertEqual` are summarized in the following table. Note that it's usually not necessary to invoke these methods directly.

Method Used to compare New in
:meth:`assertMultiLineEqual(a, b) <TestCase.assertMultiLineEqual>` strings 3.1
:meth:`assertSequenceEqual(a, b) <TestCase.assertSequenceEqual>` sequences 3.1
:meth:`assertListEqual(a, b) <TestCase.assertListEqual>` lists 3.1
:meth:`assertTupleEqual(a, b) <TestCase.assertTupleEqual>` tuples 3.1
:meth:`assertSetEqual(a, b) <TestCase.assertSetEqual>` sets or frozensets 3.1
:meth:`assertDictEqual(a, b) <TestCase.assertDictEqual>` dicts 3.1

Finally the :class:`TestCase` provides the following methods and attributes:

Testing frameworks can use the following methods to collect information on the test:

This class implements the portion of the :class:`TestCase` interface which allows the test runner to drive the test, but does not provide the methods which test code can use to check and report errors. This is used to create test cases using legacy test code, allowing it to be integrated into a :mod:`unittest`-based test framework.

Deprecated aliases

For historical reasons, some of the :class:`TestCase` methods had one or more aliases that are now deprecated. The following table lists the correct names along with their deprecated aliases:

Method Name Deprecated alias Deprecated alias
:meth:`.assertEqual` failUnlessEqual assertEquals
:meth:`.assertNotEqual` failIfEqual assertNotEquals
:meth:`.assertTrue` failUnless assert_
:meth:`.assertFalse` failIf  
:meth:`.assertRaises` failUnlessRaises  
:meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
:meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
:meth:`.assertRegex`   assertRegexpMatches
:meth:`.assertRaisesRegex`   assertRaisesRegexp

Grouping tests

This class represents an aggregation of individual tests cases and test suites. The class presents the interface needed by the test runner to allow it to be run as any other test case. Running a :class:`TestSuite` instance is the same as iterating over the suite, running each test individually.

If tests is given, it must be an iterable of individual test cases or other test suites that will be used to build the suite initially. Additional methods are provided to add test cases and suites to the collection later on.

:class:`TestSuite` objects behave much like :class:`TestCase` objects, except they do not actually implement a test. Instead, they are used to aggregate tests into groups of tests that should be run together. Some additional methods are available to add tests to :class:`TestSuite` instances:

:class:`TestSuite` shares the following methods with :class:`TestCase`:

In the typical usage of a :class:`TestSuite` object, the :meth:`run` method is invoked by a :class:`TestRunner` rather than by the end-user test harness.

Loading and running tests

The :class:`TestLoader` class is used to create test suites from classes and modules. Normally, there is no need to create an instance of this class; the :mod:`unittest` module provides an instance that can be shared as :data:`unittest.defaultTestLoader`. Using a subclass or instance, however, allows customization of some configurable properties.

:class:`TestLoader` objects have the following methods:

The following attributes of a :class:`TestLoader` can be configured either by subclassing or assignment on an instance:

This class is used to compile information about which tests have succeeded and which have failed.

A :class:`TestResult` object stores the results of a set of tests. The :class:`TestCase` and :class:`TestSuite` classes ensure that results are properly recorded; test authors do not need to worry about recording the outcome of tests.

Testing frameworks built on top of :mod:`unittest` may want access to the :class:`TestResult` object generated by running a set of tests for reporting purposes; a :class:`TestResult` instance is returned by the :meth:`` method for this purpose.

:class:`TestResult` instances have the following attributes that will be of interest when inspecting the results of running a set of tests:

The following methods of the :class:`TestResult` class are used to maintain the internal data structures, and may be extended in subclasses to support additional reporting requirements. This is particularly useful in building tools which support interactive reporting while tests are being run.

A concrete implementation of :class:`TestResult` used by the :class:`TextTestRunner`.

load_tests Protocol

Modules or packages can customize how tests are loaded from them during normal test runs or test discovery by implementing a function called load_tests.

If a test module defines load_tests it will be called by :meth:`TestLoader.loadTestsFromModule` with the following arguments:

load_tests(loader, standard_tests, None)

It should return a :class:`TestSuite`.

loader is the instance of :class:`TestLoader` doing the loading. standard_tests are the tests that would be loaded by default from the module. It is common for test modules to only want to add or remove tests from the standard set of tests. The third argument is used when loading packages as part of test discovery.

A typical load_tests function that loads tests from a specific set of :class:`TestCase` classes may look like:

test_cases = (TestCase1, TestCase2, TestCase3)

def load_tests(loader, tests, pattern):
    suite = TestSuite()
    for test_class in test_cases:
        tests = loader.loadTestsFromTestCase(test_class)
    return suite

If discovery is started, either from the command line or by calling :meth:``, with a pattern that matches a package name then the package :file:`` will be checked for load_tests.


The default pattern is 'test*.py'. This matches all Python files that start with 'test' but won't match any test directories.

A pattern like 'test*' will match test packages as well as modules.

If the package :file:`` defines load_tests then it will be called and discovery not continued into the package. load_tests is called with the following arguments:

load_tests(loader, standard_tests, pattern)

This should return a :class:`TestSuite` representing all the tests from the package. (standard_tests will only contain tests collected from :file:``.)

Because the pattern is passed into load_tests the package is free to continue (and potentially modify) test discovery. A 'do nothing' load_tests function for a test package would look like:

def load_tests(loader, standard_tests, pattern):
    # top level directory cached on loader instance
    this_dir = os.path.dirname(__file__)
    package_tests =, pattern=pattern)
    return standard_tests

Class and Module Fixtures

Class and module level fixtures are implemented in :class:`TestSuite`. When the test suite encounters a test from a new class then :meth:`tearDownClass` from the previous class (if there is one) is called, followed by :meth:`setUpClass` from the new class.

Similarly if a test is from a different module from the previous test then tearDownModule from the previous module is run, followed by setUpModule from the new module.

After all the tests have run the final tearDownClass and tearDownModule are run.

Note that shared fixtures do not play well with [potential] features like test parallelization and they break test isolation. They should be used with care.

The default ordering of tests created by the unittest test loaders is to group all tests from the same modules and classes together. This will lead to setUpClass / setUpModule (etc) being called exactly once per class and module. If you randomize the order, so that tests from different modules and classes are adjacent to each other, then these shared fixture functions may be called multiple times in a single test run.

Shared fixtures are not intended to work with suites with non-standard ordering. A BaseTestSuite still exists for frameworks that don't want to support shared fixtures.

If there are any exceptions raised during one of the shared fixture functions the test is reported as an error. Because there is no corresponding test instance an _ErrorHolder object (that has the same interface as a :class:`TestCase`) is created to represent the error. If you are just using the standard unittest test runner then this detail doesn't matter, but if you are a framework author it may be relevant.

setUpClass and tearDownClass

These must be implemented as class methods:

import unittest

class Test(unittest.TestCase):
    def setUpClass(cls):
        cls._connection = createExpensiveConnectionObject()

    def tearDownClass(cls):

If you want the setUpClass and tearDownClass on base classes called then you must call up to them yourself. The implementations in :class:`TestCase` are empty.

If an exception is raised during a setUpClass then the tests in the class are not run and the tearDownClass is not run. Skipped classes will not have setUpClass or tearDownClass run. If the exception is a :exc:`SkipTest` exception then the class will be reported as having been skipped instead of as an error.

setUpModule and tearDownModule

These should be implemented as functions:

def setUpModule():

def tearDownModule():

If an exception is raised in a setUpModule then none of the tests in the module will be run and the tearDownModule will not be run. If the exception is a :exc:`SkipTest` exception then the module will be reported as having been skipped instead of as an error.

Signal Handling

The :option:`-c/--catch <unittest -c>` command-line option to unittest, along with the catchbreak parameter to :func:`unittest.main()`, provide more friendly handling of control-C during a test run. With catch break behavior enabled control-C will allow the currently running test to complete, and the test run will then end and report all the results so far. A second control-c will raise a :exc:`KeyboardInterrupt` in the usual way.

The control-c handling signal handler attempts to remain compatible with code or tests that install their own :const:`signal.SIGINT` handler. If the unittest handler is called but isn't the installed :const:`signal.SIGINT` handler, i.e. it has been replaced by the system under test and delegated to, then it calls the default handler. This will normally be the expected behavior by code that replaces an installed handler and delegates to it. For individual tests that need unittest control-c handling disabled the :func:`removeHandler` decorator can be used.

There are a few utility functions for framework authors to enable control-c handling functionality within test frameworks.