Testing with pytest
A test is a small function that runs your code and checks the result with assert. pytest finds every function named test_* in files named test_*.py, runs them and reports what failed and why. Tests let you change code — or accept code from an AI assistant — with confidence.
assert: the core of every test
def slugify(title: str) -> str:
return "-".join(title.lower().split())
assert slugify("Hello World") == "hello-world"
assert slugify(" Python Rocks ") == "python-rocks"
print("All checks passed")All checks passed
assert condition does nothing when the condition is true and raises AssertionError when it's false. pytest builds on this plain Python statement.
Your first pytest file
def slugify(title: str) -> str:
return "-".join(title.lower().split())from text_utils import slugify
def test_simple_title():
assert slugify("Hello World") == "hello-world"
def test_extra_spaces():
assert slugify(" Python Rocks ") == "python-rocks"
def test_empty():
assert slugify("") == ""$ uv add --dev pytest
$ uv run pytest -q
... [100%]
3 passed in 0.01sWhen a test fails
$ uv run pytest -q
F.. [100%]
___________________ test_simple_title ___________________
def test_simple_title():
> assert slugify("Hello World") == "hello_world"
E AssertionError: assert 'hello-world' == 'hello_world'
test_text_utils.py:5: AssertionError
1 failed, 2 passed in 0.02spytest shows both values side by side, so you can see immediately whether the code or the test expectation is wrong.
Many cases, one test
import pytest
from text_utils import slugify
@pytest.mark.parametrize(
("title", "expected"),
[
("Hello World", "hello-world"),
("ONE", "one"),
("a b c", "a-b-c"),
],
)
def test_slugify(title: str, expected: str):
assert slugify(title) == expectedTesting that errors are raised
import pytest
def apply_discount(price: float, percent: float) -> float:
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return round(price * (1 - percent / 100), 2)
def test_discount():
assert apply_discount(80, 25) == 60
def test_invalid_percent():
with pytest.raises(ValueError, match="between 0 and 100"):
apply_discount(80, 150)Fixtures: shared test setup
import pytest
@pytest.fixture
def cart() -> list[dict]:
return [{"item": "mug", "price": 8.5}, {"item": "tea", "price": 3.0}]
def test_total(cart):
assert sum(line["price"] for line in cart) == 11.5
def test_count(cart):
assert len(cart) == 2A fixture is a function pytest runs before each test that asks for it by name. Every test gets a fresh copy, so tests can't affect each other.
Practice
Write is_palindrome(text: str) -> bool that ignores case and spaces, so "Never odd or even" is a palindrome. The starter includes plain assert tests; make them all pass so the program prints All tests passed.
All tests passed