Learn / Intermediate / Lesson 9

Testing with pytest

12 min Tested on Python 3.15Updated By
In short

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

Python
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")
Output
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

text_utils.py
def slugify(title: str) -> str:
    return "-".join(title.lower().split())
test_text_utils.py
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("") == ""
terminal
$ uv add --dev pytest
$ uv run pytest -q
...                                                  [100%]
3 passed in 0.01s

When a test fails

terminal
$ 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.02s

pytest shows both values side by side, so you can see immediately whether the code or the test expectation is wrong.

Many cases, one test

test_text_utils.py
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) == expected

Testing that errors are raised

test_pricing.py
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

test_cart.py
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) == 2

A 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.

Expected output:
All tests passed
Your code

Quick check

1. Which function will pytest run as a test?

2. How do you check that code raises a ValueError?

3. What does @pytest.mark.parametrize do?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →