MrFaws Docs
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]) == 35

Install and run pytest:

python -m pip install pytest
python -m pytest

Test 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

  1. Reproduce the failure consistently.
  2. Read the complete traceback.
  3. Reduce the input.
  4. Add breakpoint() and inspect values.
  5. Write a failing test before the fix.
  6. Confirm the test passes afterward.

On this page