Skip to main content

Programming languages · Intermediate · 18 min

How to Write and Run Tests in Python with pytest

By Padding · Updated 15 Nov 2026
Python 3.15 · pytest 9.2

You will install pytest 9.2 in a uv project, write tests for a small price-parsing module, run many cases from one test with parametrize, read a failure and fix the code, and use a fixture that gives each test its own temporary folder.

On this page

A test is a small program that runs your code and checks the answer. When you change something later, the tests tell you within seconds whether you broke what used to work. pytest is the most used Python test runner. A test is a plain function whose name starts with test_, and a check is a plain assert statement. There is almost nothing to learn before you start.

You will write tests for a tiny module that turns prices such as $12.50 into whole pence. Money is a good subject: it is easy to get wrong, and the right answer is exact. The tutorial finishes the series Python from zero.

Step 1 · Create a project and install pytest

Make a project and add pytest as a development dependency. A development dependency is something you need to work on the code, such as a test runner, but not to run it. uv records it in a separate dev group:

Bash
mkdir -p ~/pytest-demo
cd ~/pytest-demo
uv init --no-package
uv add --dev "pytest>=9.2,<9.3"
rm main.py

The last line removes the sample main.py that uv init made. Check the installed version:

Bash
uv run pytest --version

Check it worked

The output is pytest 9.2.0, or a later 9.2 release.

Step 2 · Write the code to test

Create cart.py. It has a function that converts a price string to an integer number of pence, so no floating-point rounding can creep in, and a function that adds a list of prices:

Bash
cat > cart.py <<'PY'
def parse_price(text):
    """Turn '12.50' or '$12.50' into an integer number of pence."""
    cleaned = text.strip().lstrip("$")
    try:
        whole, _, fraction = cleaned.partition(".")
        return int(whole) * 100 + int((fraction + "00")[:2])
    except ValueError:
        raise ValueError(f"not a price: {text!r}") from None


def total(prices):
    return sum(parse_price(price) for price in prices)
PY

Step 3 · Write and run your first tests

pytest looks for files named test_*.py. Put them in a tests/ folder:

Bash
mkdir -p tests
cat > tests/test_cart.py <<'PY'
import pytest

from cart import parse_price, total


def test_parse_plain_price():
    assert parse_price("12.50") == 1250


def test_total_adds_prices():
    assert total(["1.00", "2.50"]) == 350


def test_bad_price_raises():
    with pytest.raises(ValueError, match="not a price"):
        parse_price("free")
PY

The first two tests state a result and check it. The third checks that a call fails in the right way: pytest.raises passes only if the block raises ValueError with a message that matches the pattern. Tell pytest where to look and where to import your code from. Add two settings to pyproject.toml, the project file:

Bash
cat >> pyproject.toml <<'TOML'

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
TOML

pythonpath = ["."] adds the project folder to the import path, so from cart import ... works from inside tests/. Now run the tests:

Bash
uv run pytest

Check it worked

pytest prints a header with the Python and pytest versions, collected 3 items, a line tests/test_cart.py ... with one dot per passing test, and a final line like 3 passed in 0.01s.

Troubleshooting

ModuleNotFoundError: No module named 'cart' during collection means pytest cannot find your module. Check that the pythonpath line is in pyproject.toml, and that cart.py is in the project root, beside pyproject.toml. An F in the dot line is a failing test, and E is an error outside the assertion, such as an import problem.

Step 4 · Run many cases with parametrize

You rarely test one input. Writing a new function per input is tedious, and parametrize runs one test body with a table of inputs and expected results:

Bash
cat > tests/test_prices.py <<'PY'
import pytest

from cart import parse_price


@pytest.mark.parametrize(
    ("text", "pence"),
    [
        ("0.99", 99),
        ("5", 500),
        ("$3.5", 350),
        ("  7.25  ", 725),
        ("$1,200.00", 120000),
    ],
)
def test_parse_price(text, pence):
    assert parse_price(text) == pence
PY
uv run pytest tests/test_prices.py || echo "pytest exited with status $?"

Each row becomes its own test, reported separately. The last row is a price with a thousands separator, which parse_price does not handle yet, and the run shows the failure on purpose. The || echo keeps the shell going, and shows pytest's exit status. A passing run exits with 0 and any failure exits with 1, which is how CI knows to stop.

Check it worked

The summary reports 1 failed, 4 passed, and the status line reads exit status 1. In the failure report, the line starting with E names the problem: ValueError: not a price: '$1,200.00'. pytest also prints the test's arguments in its name, test_parse_price[$1,200.00-120000], so you can tell which row failed.

Step 5 · Fix the code and re-run

Read the failure from the bottom of the report upwards. The E lines say what went wrong, and the lines above show the code that was running. The test is right and the function is wrong: it must accept commas in the whole-number part. Change the function so it removes them:

Bash
cat > cart.py <<'PY'
def parse_price(text):
    """Turn '12.50' or '$12.50' into an integer number of pence."""
    cleaned = text.strip().lstrip("$").replace(",", "")
    try:
        whole, _, fraction = cleaned.partition(".")
        return int(whole) * 100 + int((fraction + "00")[:2])
    except ValueError:
        raise ValueError(f"not a price: {text!r}") from None


def total(prices):
    return sum(parse_price(price) for price in prices)
PY
uv run pytest --last-failed

--last-failed (or --lf) re-runs only the tests that failed in the previous run, which is quick when a suite is large. Then run everything, to see that the fix broke nothing else:

Bash
uv run pytest

Check it worked

The first command reports 1 passed, and the full run reports 8 passed: three tests from the first file and five from the table.

Step 6 · Use a fixture for files

A fixture is a function that prepares something a test needs. A test asks for it by naming it as an argument. pytest has several built in. tmp_path gives each test a new, empty folder that is removed later, so tests that write files never interfere with each other or with your own files. Add a function that saves a total to a receipt file, and test it:

Bash
cat >> cart.py <<'PY'


def save_receipt(path, prices):
    pence = total(prices)
    path.write_text(f"TOTAL {pence // 100}.{pence % 100:02d}\n", encoding="utf-8")
PY
cat > tests/test_receipt.py <<'PY'
import pytest

from cart import save_receipt


@pytest.fixture
def prices():
    return ["1.00", "2.50", "$0.75"]


def test_receipt_total(tmp_path, prices):
    receipt = tmp_path / "receipt.txt"
    save_receipt(receipt, prices)
    assert receipt.read_text(encoding="utf-8") == "TOTAL 4.25\n"


def test_receipt_for_empty_cart(tmp_path):
    receipt = tmp_path / "receipt.txt"
    save_receipt(receipt, [])
    assert receipt.read_text(encoding="utf-8") == "TOTAL 0.00\n"
PY
uv run pytest

The prices fixture is defined in the test file and is available to every test in it. For fixtures shared by many files, put them in a file named conftest.py in tests/, and pytest picks them up without an import.

Check it worked

The run reports 10 passed.

Step 7 · Choose which tests run

On a real project you rarely want to run everything each time. These options are the ones to know:

Bash
uv run pytest -v
uv run pytest -k receipt
uv run pytest -x -q

-v lists every test by name with PASSED beside it. -k receipt runs only tests whose names contain the word. -x stops at the first failure, and -q shortens the output. You can also name a single test, as in uv run pytest tests/test_cart.py::test_total_adds_prices.

Check it worked

-v shows ten lines ending in PASSED. -k receipt reports 2 passed, 8 deselected. The last command prints dots and 10 passed.

Remove the demo project when you are done:

Bash
cd ~
rm -rf ~/pytest-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.