Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Standard Library: Concurrency, Network and Tools

The unittest module

Reference for Python's unittest module: TestCase, assert methods, assertRaises, setUp and tearDown, subTest, skip decorators, mock basics and running tests.

unittest is the testing framework in Python's standard library. You write classes that inherit from unittest.TestCase, name each test method test_..., and check results with assertion methods. The framework discovers and runs the tests, then reports passes, failures and errors.

A failure means an assertion was false; an error means the test raised some other exception. Each test method runs on a fresh instance of the class, so tests cannot leak state into each other through self.

Python
import unittest

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(1 + 1, 2)

# Command line: python -m unittest

Try it

Scripts usually end with unittest.main(), which prints a progress line, any failure reports and a timing summary. Here we build a suite and run it into a plain TestResult, so the output is just the counts. Use unittest.TextTestRunner(verbosity=2) to get the full report.

Python A test case with setUp and exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Reading a failure, skipping, and mocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
class MyTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls): ...
    def setUp(self): ...
    def test_something(self): ...
    def tearDown(self): ...
    @classmethod
    def tearDownClass(cls): ...

unittest.main()                    # run the tests found in this file

Common assertions:

Method Checks
assertEqual(a, b), assertNotEqual(a, b) a == b / a != b, with a readable diff for lists, dicts and strings.
assertTrue(x), assertFalse(x) Truthiness.
assertIs(a, b), assertIsNone(x) Identity.
assertIn(a, b), assertNotIn(a, b) Membership.
assertIsInstance(obj, cls) Type check.
assertAlmostEqual(a, b, places=7) Floats equal after rounding (or delta=).
assertGreater, assertLess, and the ...Equal forms Ordering.
assertRaises(Exc), assertRaisesRegex(Exc, pattern) An exception is raised; use as a context manager to inspect it.
assertWarns(Warn), assertLogs(logger, level) A warning or log message is produced.
assertCountEqual(a, b) Same elements regardless of order.
assertRegex(text, pattern) Regular expression matches.
fail(msg), subTest(**params) Force a failure; run parts of a test independently.

Decorators: @skip(reason), @skipIf(cond, reason), @skipUnless(cond, reason), @expectedFailure.

Return value: a runner returns a TestResult with wasSuccessful(), failures, errors and testsRun. unittest.main() exits the process with status 0 on success and 1 otherwise.

Usage notes

  • Discovery finds files named test*.py with python -m unittest discover (or just python -m unittest in a project), and runs classes that inherit from TestCase.
  • Tests run in alphabetical order inside a class, but you should never depend on order. Each test must set up what it needs.
  • assertEqual(a, b) prints both values when it fails. Prefer it to assertTrue(a == b), which only says "False is not true".
  • Order of arguments: assertEqual(actual, expected) is the convention; mixing them only affects readability of the message.
  • Floats: never compare with ==; use assertAlmostEqual.
  • subTest keeps going after a failing case and reports every failing parameter set.
  • Mocks: unittest.mock provides Mock, MagicMock and patch() to replace slow or external parts such as network calls. Patch the name where it is used, not where it is defined.
  • Cleanup: addCleanup(func) runs after the test even if setUp failed halfway, and is simpler than a long tearDown.
  • Async code: use unittest.IsolatedAsyncioTestCase and async def test_....
  • pytest (third-party) runs unittest tests too and adds shorter plain-assert style tests and fixtures.