Testing Python Code with pytest: A Beginner's Guide
Part 13 of the Python for Everyone track. Last updated: September 2026.
pytest is the de facto standard for testing Python — simpler than unittest, no boilerplate classes required. If you write code that matters, test it; pytest makes the habit painless.
Your first test
# test_math_utils.py
from math_utils import add
def test_add_positive():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, -1) == -2
Run with pytest in the terminal. Test functions just use plain assert — pytest rewrites assertions to show beautiful failure diffs.
Testing exceptions with pytest.raises
import pytest
from accounts import withdraw
def test_withdraw_too_much():
with pytest.raises(ValueError, match="insufficient funds"):
withdraw(100, 200)
Fixtures: reusable setup
import pytest
@pytest.fixture
def sample_user():
return {"name": "Ada", "age": 36} # fresh dict for EVERY test
def test_user_name(sample_user):
assert sample_user["name"] == "Ada" # just name the fixture as a parameter!
def test_user_age(sample_user):
assert sample_user["age"] == 36
Fixtures are pytest's superpower: declare setup once with @pytest.fixture, inject it by naming it as a parameter. Each test gets a fresh copy.
Parametrize: one test, many cases
import pytest
from math_utils import is_even
@pytest.mark.parametrize("n,expected", [
(2, True), (3, False), (0, True), (-4, True),
])
def test_is_even(n, expected):
assert is_even(n) == expected
@pytest.mark.parametrize runs the same test with different inputs — four test cases from one function.
Key takeaways
- Test files named test_*.py, test functions named test_* — pytest discovers them automatically.
- Plain assert is all you need; pytest gives rich failure output.
- pytest.raises tests exceptions; @pytest.fixture shares setup; @pytest.mark.parametrize multiplies cases.
- Run pytest -v for verbose output, pytest -x to stop at the first failure.
Next in this series: Async Python: asyncio Crash Course — the final post in the core track.
Comments
Post a Comment