On this page
  1. unittest
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Parameterized Cases with subTest() & Guaranteed Cleanup (addCleanup)
  7. 2. Isolating External Calls with unittest.mock.patch
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

unittest

Prev: unicodedata | Up: stdlib_module | Next: urllib
Rel: typing, annotationlib, pydoc, pydoc_data, doctest
Ref: docs.python.org — unittest
Tags: #public #python3 #stdlib


Import

import unittest

Overview

Zero-dependency xUnit-style test runner, assertion library, and mocking framework (unittest.mock) built into Python. Ideal for stdlib-only packages (python -m unittest discover -s tests) where you want reliable CI across platforms with zero external test dependencies.

Quick Start

import unittest

def add(a: int, b: int) -> int:
    return a + b

class TestMath(unittest.TestCase):
    def test_add(self) -> None:
        self.assertEqual(add(2, 3), 5)

    def test_type_error(self) -> None:
        with self.assertRaises(TypeError):
            add("a", 1)  # type: ignore[arg-type]

Implementation Walkthrough

1. Parameterized Cases with subTest() & Guaranteed Cleanup (addCleanup)

subTest() reports every failing case instead of stopping at the first failure; addCleanup() runs even if setUp() fails partway through:

import tempfile
import unittest
from pathlib import Path

class TestSlugify(unittest.TestCase):
    def setUp(self) -> None:
        self.tmp = tempfile.TemporaryDirectory()
        self.addCleanup(self.tmp.cleanup)

    def test_cases(self) -> None:
        for raw, expected in [("Hello World", "hello-world"), ("A  B", "a-b")]:
            with self.subTest(raw=raw):
                self.assertEqual("-".join(raw.lower().split()), expected)

2. Isolating External Calls with unittest.mock.patch

from unittest.mock import patch
import os

with patch.dict(os.environ, {"APP_ENV": "test"}, clear=False):
    assert os.environ["APP_ENV"] == "test"

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes