DEV Community

Cover image for Pytest Tutorial: Test a Real Shop Orders App in Python
The Practical Developer
The Practical Developer

Posted on Originally published at practicaldevblog.blogspot.com

Pytest Tutorial: Test a Real Shop Orders App in Python

Quick answer

Pytest is the testing tool most Python teams reach for: plain functions whose names start with test_, a few asserts, and pytest prints what passed and what failed. This post tests that module with four real orders, a fixture for the data, and parametrize for the city totals, and the first run catches a wrong total before the code ever ships.

A shop in Karachi keeps its orders in a notebook: Sana, Karachi, Rs 9,800; Daniyal, Lahore, Rs 13,400; Mahnoor, Islamabad, Rs 11,200; Hamza, Karachi, Rs 6,750. The owner wants a small Python module that totals sales per city, adds a grand total, and discounts big orders by 5 percent. The module is short, but a wrong total is easy to miss, and a wrong discount costs real money. A few tests before trusting the module cost less than explaining a wrong bill to a customer, and pytest makes that check almost free: no test class, no boilerplate, just functions and asserts.

What I would check before using it

My first check is whether a wrong answer would look like a right one. A greeting script can fail loudly and nobody loses money, but a totals function off by Rs 50 looks fine until a customer checks the bill. Pytest earns its place here: the tests are plain functions with plain asserts, and a failing test names the exact numbers that disagree.

My second check is how the test data is shared: if every test rebuilds the same four orders by hand, the tests rot the moment the data changes. A fixture builds the data once and hands each test a fresh copy, the same idea as the Pydantic: Catch Bad Data Before It Reaches Your Database post, which validates data in one place.

My third check is the tooling: pytest runs from the terminal, VS Code, and CI with one command, and works inside the virtual environments the uv Python Tutorial: Manage Projects Without the Mess post sets up. If the team already writes unittest classes, switching costs little: pytest runs them unchanged.

My fourth check is the next reader. Parametrize looks strange at first, but one decorator replaces four near-identical tests, and every case sits in one visible list.

My verdict, as judgement: use pytest for Python code that totals money, orders, or data others rely on. Keep unittest only when a large suite already exists and nobody wants to move it. The recommendation flips for a one-off script nobody will run twice, or if the team standard forbids third-party test tools.

Four orders, seven tests, and one wrong total

Four orders belong to one small shop: Sana in Karachi, Rs 9,800; Daniyal in Lahore, Rs 13,400; Mahnoor in Islamabad, Rs 11,200; Hamza in Karachi, Rs 6,750.

First, create a virtual environment and install pytest; the install takes seconds.

$ python3 -m venv .venv
$ .venv/bin/pip install pytest
$ .venv/bin/pytest --version
pytest 9.2.0
Enter fullscreen mode Exit fullscreen mode

The module under test is orders.py: it keeps the four orders in one list, with total_for_city for one city, grand_total for everything, and discounted_total, which takes 5 percent off any order of Rs 10,000 or more.

"""Shop orders module for the Pytest demo.

A small shop in Karachi keeps four orders on file. The helpers total
sales per city, add up a grand total, and apply a 5 percent discount
to any single order of Rs 10,000 or more.
"""

ORDERS = [
    {"customer": "Sana", "city": "Karachi", "total": 9800},
    {"customer": "Daniyal", "city": "Lahore", "total": 13400},
    {"customer": "Mahnoor", "city": "Islamabad", "total": 11200},
    {"customer": "Hamza", "city": "Karachi", "total": 6750},
]

DISCOUNT_THRESHOLD = 10000
DISCOUNT_RATE = 0.05


def total_for_city(orders, city):
    """Add up the totals of every order shipped to one city."""
    return sum(order["total"] for order in orders if order["city"] == city)


def grand_total(orders):
    """Add up the totals of every order on file."""
    return sum(order["total"] for order in orders)


def discounted_total(total):
    """Apply a 5 percent discount to a single order of Rs 10,000 or more."""
    if total >= DISCOUNT_THRESHOLD:
        return total * (1 - DISCOUNT_RATE)
    return total
Enter fullscreen mode Exit fullscreen mode

The tests live in test_orders.py, where a fixture called orders hands every test a fresh copy of the four orders. Parametrize runs the city-total test once per city instead of three near-identical tests, and the discount test checks three totals: two that earn the discount, one that does not.

"""Tests for the shop orders module, written with Pytest.

The fixture hands every test a fresh copy of the four real orders, so
no test can change the data another test sees. The city totals are
checked with parametrize instead of four near-identical tests.
"""

import pytest

from orders import ORDERS, discounted_total, grand_total, total_for_city


@pytest.fixture
def orders():
    return list(ORDERS)


@pytest.mark.parametrize(
    "city, expected",
    [
        ("Karachi", 16500),
        ("Lahore", 13400),
        ("Islamabad", 11200),
    ],
)
def test_total_for_city(orders, city, expected):
    assert total_for_city(orders, city) == expected


def test_grand_total(orders):
    assert grand_total(orders) == 41150


@pytest.mark.parametrize(
    "total, expected",
    [
        (13400, 12730.0),
        (11200, 10640.0),
        (9800, 9800),
    ],
)
def test_discounted_total(total, expected):
    assert discounted_total(total) == expected
Enter fullscreen mode Exit fullscreen mode

The first run fails on exactly one test: I added 9,800 and 6,750 in my head and wrote 16,500, while the real total is 16,550. Pytest shows both numbers side by side, so the fix is obvious: correct the expectation, not the code.

$ .venv/bin/pytest -v
...
test_orders.py::test_total_for_city[Karachi-16500] FAILED                [ 14%]
test_orders.py::test_total_for_city[Lahore-13400] PASSED                 [ 28%]
test_orders.py::test_total_for_city[Islamabad-11200] PASSED              [ 42%]
test_orders.py::test_grand_total PASSED                                  [ 57%]
test_orders.py::test_discounted_total[13400-12730.0] PASSED              [ 71%]
test_orders.py::test_discounted_total[11200-10640.0] PASSED              [ 85%]
test_orders.py::test_discounted_total[9800-9800] PASSED                  [100%]

E       AssertionError: assert 16550 == 16500

========================= 1 failed, 6 passed in 0.04s ==========================
Enter fullscreen mode Exit fullscreen mode

Changing 16500 to 16550 fixes it, and the rerun passes all seven tests: three city totals, the grand total, and three discount cases.

$ .venv/bin/pytest -v
============================= test session starts ==============================
platform linux -- Python 3.12.3, pytest-9.2.0, pluggy-1.7.0 -- /home/hatch/workspace/.toolchains/verify/batch57-pytest/.venv/bin/python3
collecting ... collected 7 items

test_orders.py::test_total_for_city[Karachi-16550] PASSED                [ 14%]
test_orders.py::test_total_for_city[Lahore-13400] PASSED                 [ 28%]
test_orders.py::test_total_for_city[Islamabad-11200] PASSED              [ 42%]
test_orders.py::test_grand_total PASSED                                  [ 57%]
test_orders.py::test_discounted_total[13400-12730.0] PASSED              [ 71%]
test_orders.py::test_discounted_total[11200-10640.0] PASSED              [ 85%]
test_orders.py::test_discounted_total[9800-9800] PASSED                  [100%]

============================== 7 passed in 0.02s ===============================
Enter fullscreen mode Exit fullscreen mode

Terminal output showing a Pytest run: seven tests on a shop orders module passing, with an earlier failing run showing AssertionError assert 16550 == 16500 on the Karachi city total.

The numbers check out: Karachi Rs 9,800 plus Rs 6,750 is Rs 16,550, and the four orders add to Rs 41,150. The discount works too: Rs 13,400 becomes Rs 12,730, Rs 11,200 becomes Rs 10,640, and Rs 9,800 stays put, below the Rs 10,000 threshold.

Common mistakes and how to fix them

First, writing the right answer wrong. The symptom is AssertionError: assert 16550 == 16500, exactly as the demo showed: I added 9,800 and 6,750 in my head and wrote 16,500. The fix is to re-add the numbers from the data, not from memory.

Second, naming a test function without the test_ prefix. The symptom is pytest printing collected 0 items and no tests ran, with exit code 5, even though the file holds a good check. The fix is to rename the function, or the file, so it starts with test_.

Third, running the test file with Python instead of pytest. The symptom is nothing at all: python test_orders.py prints no output and exits with code 0, because the file only defines functions. The fix is to run pytest, which finds and calls them.

Fourth, matching a city name with the wrong case. The symptom is AssertionError: assert 0 == 16550, because total_for_city compares with ==, 'karachi' never equals 'Karachi', and no order matches, so the sum is zero. The fix is to use the exact spelling from the data, or normalise both sides with .lower() first.

Frequently Asked Questions

Do I need to install pytest, or does Python include it? Pytest is a third-party package: install it with pip install pytest, ideally inside a virtual environment. Python ships unittest in the standard library, and pytest can run unittest-style tests too.

What is a fixture? A fixture is a setup helper: a function marked with @pytest.fixture that builds what a test needs, such as the four orders here, and hands a fresh copy to each test. Setup stays in one place, so changing the data means changing one function, not every test.

Why does pytest say no tests ran? The usual cause is naming: test files must start with test_ or end with test.py, and test functions must start with test. Rename the file or function and run pytest again.

How do I run just one test? Name it on the command line, for example pytest test_orders.py::test_grand_total -v. Pytest runs only that test, handy when one failure needs attention and the rest is slow.

What to remember

  • Test functions are plain functions whose names start with test_, and pytest finds them by name.
  • A fixture builds shared data once and hands each test a fresh copy.
  • Parametrize runs one test once per case, so every case stays visible in one list.
  • A failing assert shows both numbers, which usually points at the fix.
  • Run pytest, not python, on the test file, or nothing happens at all.

Where this leaves you

Pytest earns its place the moment a Python module totals anything real, because a wrong number looks exactly like a right one until a test says otherwise. The demo proved it in minutes: seven small tests, one fixture, one parametrize list, and the first run caught a total I had added up wrong in my head. Pick one small module you already trust, write three tests for it, and run pytest. The first failure you catch before a customer does is the test suite paying for itself.

Further reading

Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

Top comments (0)