On this page
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`)
- > Docstring Tests (`doctest`)
- > Interactive Debugging (`pdb` & `breakpoint()`)
- > Structured Logging (`logging`)
- > Profiling & Benchmarking (`timeit` & `cProfile`)
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:
n(next line),s(step into),c(continue),r(return from function)l(list source),w(stack trace),p expr/pp expr(evaluate & print),q(quit)- Post-mortem debugging:
python3 -m pdb script.py
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)
- Use
[[stdlib_module/timeit|timeit]]for micro-benchmarks of small snippets. - Use
[[stdlib_module/cProfile|cProfile]]+[[stdlib_module/pstats|pstats]]to locate hot functions in full programs.
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
- tuts/programming/software_design
- tuts/programming/software_design/testing_and_maintainability
- tuts/python3/tutorials
- tuts/python3/tutorials/intermediate_python_and_software_engineering
- tuts/python3/tutorials/intermediate_python_and_software_engineering/testing_and_debugging
- tuts/python3/tutorials/intermediate_python_and_software_engineering/type_hinting_and_static_analysis
- tuts/web/tutorials/devtools_and_debugging
Related notes
- tuts/python3/tutorials/intermediate_python_and_software_engineering Linked here; links to this page; shared tags: #tutorials
- tuts/python3/tutorials/intermediate_python_and_software_engineering/type_hinting_and_static_analysis Linked here; links to this page; shared tags: #tutorials
- tuts/web/tutorials/devtools_and_debugging links to this page; shared tags: #debugging, #testing, #tutorials
- tuts/programming/software_design/testing_and_maintainability links to this page; shared tags: #testing
- tuts/python3/tutorials links to this page; shared tags: #tutorials
- tuts/python3/tutorials/advanced_python_internals Linked here; shared tags: #tutorials
- tuts/programming/software_design links to this page
- tuts/python3/stdlib_module/cProfile Linked here
- tuts/python3/stdlib_module/doctest Linked here
- tuts/python3/stdlib_module/logging Linked here