On this page
  1. Testing and Debugging
  2. Contents
  3. Unit Testing (unittest & unittest.mock)
  4. Docstring Tests (doctest)
  5. Interactive Debugging (pdb & breakpoint())
  6. Structured Logging (logging)
  7. Profiling & Benchmarking (timeit & cProfile)

Testing and Debugging

Prev: Type Hinting and Static Analysis | Up: Intermediate Python & Software Engineering | Next: Advanced Python Internals
Rel: unittest, doctest, pdb, logging, cProfile, timeit, traceback
Ref: docs.python.org — unittest | docs.python.org — logging
Tags: #public #python3 #tutorials #software-engineering #testing #debugging #logging


Contents


Unit Testing (unittest & unittest.mock)

[[stdlib_module/unittest|unittest]] is Python's built-in xUnit-style testing framework, supporting fixtures (setUp/tearDown), parameterized subtests (subTest), and mocking (unittest.mock).

import unittest
from unittest.mock import patch

def divide(a: float, b: float) -> float:
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return a / b

class TestMathHelpers(unittest.TestCase):
    def test_divide_cases(self) -> None:
        for a, b, expected in [(10, 2, 5.0), (9, 3, 3.0)]:
            with self.subTest(a=a, b=b):
                self.assertEqual(divide(a, b), expected)

    def test_divide_by_zero(self) -> None:
        with self.assertRaises(ZeroDivisionError):
            divide(1, 0)

    def test_mocking_builtin(self) -> None:
        with patch("builtins.abs", return_value=99) as mock_abs:
            self.assertEqual(abs(-5), 99)
            mock_abs.assert_called_once_with(-5)

Run tests from the CLI with python3 -m unittest discover -v.


Docstring Tests (doctest)

[[stdlib_module/doctest|doctest]] executes interactive >>> examples inside docstrings and verifies their output matches.

import doctest

def clamp(value: int, low: int, high: int) -> int:
    """Clamp value to [low, high].

    >>> clamp(15, 0, 10)
    10
    >>> clamp(-3, 0, 10)
    0
    """
    return max(low, min(value, high))

result = doctest.testmod(verbose=False)
assert result.failed == 0

Interactive Debugging (pdb & breakpoint())

Insert breakpoint() anywhere in code to drop into [[stdlib_module/pdb|pdb]] (disable globally with PYTHONBREAKPOINT=0). Key pdb commands:


Structured Logging (logging)

Prefer [[stdlib_module/logging|logging]] over print() in applications so log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), formatting, and destinations can be configured cleanly.

import logging

logger = logging.getLogger("app.service")
logger.setLevel(logging.INFO)

handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))
logger.addHandler(handler)

logger.info("Service started on port %d", 8080)

Profiling & Benchmarking (timeit & cProfile)

import timeit

t_comp = timeit.timeit("[x * 2 for x in range(1000)]", number=500)
t_map = timeit.timeit("list(map(lambda x: x * 2, range(1000)))", number=500)
print(f"comprehension={t_comp:.4f}s, map={t_map:.4f}s")

Linked from

Related notes