Learn Python
Testing and Debugging
Find defects faster with pytest, fixtures, mocks, logging and a debugger.
def calculate_total(prices: list[int]) -> int:
return sum(prices)
def test_calculate_total() -> None:
assert calculate_total([10, 20, 5]) == 35Install and run pytest:
python -m pip install pytest
python -m pytestTest failures too
import pytest
def divide(a: float, b: float) -> float:
if b == 0:
raise ValueError("b cannot be zero")
return a / b
def test_zero_is_rejected() -> None:
with pytest.raises(ValueError, match="cannot be zero"):
divide(10, 0)Use tmp_path for isolated file tests. Mock system boundaries such as time, network and email—not ordinary internal logic.
Debugging order
- Reproduce the failure consistently.
- Read the complete traceback.
- Reduce the input.
- Add
breakpoint()and inspect values. - Write a failing test before the fix.
- Confirm the test passes afterward.