Testing and QA · Beginner · 16 min
Write unit tests that stay useful as the code changes
By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · pytest 9.2.0 · uv 0.13
You will replace a brittle pytest suite with behaviour tests that catch a real boundary bug and stay green when the code under them is rewritten.
On this page
A test suite earns its keep when you change code. If every rename or tidy-up turns the suite red, people stop trusting it, then stop running it. The usual cause is tests that check how the code works inside, instead of what it promises to the code that calls it.
In this tutorial you start with a small delivery-fee module and an old test suite that passes but is fragile. You write a new suite against the module's public function, find a bug the old suite missed, then rewrite the module completely. The new suite stays green through the rewrite; the old one fails on every test, although nothing a caller can see has changed.
The ideas carry over to any language. For the JavaScript side, see the Vitest tutorial linked at the end.
Step 1 · Create the project and the code under test
Make a throwaway project and add pytest as a development dependency:
mkdir -p ~/unit-tests-demo
cd ~/unit-tests-demo
uv init --no-package
uv add --dev "pytest>=9.2,<9.3"
rm main.py
cat >> pyproject.toml <<'TOML'
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
TOMLNow the module. shipping.py works out a delivery fee for an online shop. Amounts are whole minor units (cents, kobo, pence), so 20000 means 200.00 in the shop's currency and no floating-point rounding creeps into money. The rules, as the shop wrote them down:
- A delivery costs 500 plus 120 per kilometre.
- Parcels over 10 kg pay an extra 800.
- Orders of 200.00 or more deliver free.
- A negative distance or a weight of zero or less is an error.
cat > shipping.py <<'PY'
"""Delivery fees for a small online shop. Amounts are in minor units."""
BASE_FEE = 500
PER_KM = 120
HEAVY_LIMIT_KG = 10
HEAVY_SURCHARGE = 800
FREE_DELIVERY_FROM = 20000
def _distance_fee(distance_km):
return round(distance_km * PER_KM)
def _weight_fee(weight_kg):
if weight_kg > HEAVY_LIMIT_KG:
return HEAVY_SURCHARGE
return 0
def delivery_fee(order_total, distance_km, weight_kg):
"""Return the delivery fee for an order, in minor units."""
if distance_km < 0:
raise ValueError(f"distance_km must be 0 or more, got {distance_km}")
if weight_kg <= 0:
raise ValueError(f"weight_kg must be above 0, got {weight_kg}")
if order_total > FREE_DELIVERY_FROM:
return 0
return BASE_FEE + _distance_fee(distance_km) + _weight_fee(weight_kg)
PY
uv run python -c "from shipping import delivery_fee; print(delivery_fee(5000, 3, 2))"delivery_fee is the public function: it is what the checkout code calls. The names that start with an underscore are private helpers, and the constants are details of how the fee is worked out today.
Check it worked
The last command prints 860: 500 base plus 3 km at 120.
Step 2 · Run the old suite and spot what makes it brittle
Here is the kind of suite that grows when tests are written by looking at the code rather than at the rules. Put it in its own folder, legacy_tests/, so you can compare it with the new one later:
mkdir -p legacy_tests
cat > legacy_tests/test_shipping_old.py <<'PY'
from unittest import mock
import shipping
def test_distance_fee():
assert shipping._distance_fee(5) == 5 * shipping.PER_KM
def test_weight_fee_called():
with mock.patch("shipping._weight_fee", return_value=0) as weight_fee:
shipping.delivery_fee(1000, 2, 3)
weight_fee.assert_called_once_with(3)
def test_delivery_fee():
for km in [0, 1, 5, 12]:
expected = shipping.BASE_FEE + km * shipping.PER_KM
assert shipping.delivery_fee(1000, km, 2) == expected
assert shipping.delivery_fee(25000, 4, 2) == 0
assert (
shipping.delivery_fee(1000, 4, 15)
== shipping.BASE_FEE + 4 * shipping.PER_KM + shipping.HEAVY_SURCHARGE
)
PY
uv run pytest legacy_tests -qAll three pass, and each has a problem that will hurt later:
test_distance_feecalls a private helper. Rename or inline_distance_feeand the test breaks, though no caller would notice.test_weight_fee_calledreplaces a helper with a mock and checks it was called. It tests the wiring inside the function, not the fee a customer pays.test_delivery_feerebuilds the expected answer with the same formula as the code. If the formula is wrong, the test is wrong in the same way. It also has a loop and checks six things, so when it fails the name tells you nothing about which rule broke.
Note what the old suite never checks: an order of exactly 20000. The rule says "200.00 or more"; the only free-delivery case it tries is 25000.
Check it worked
The output ends with 3 passed. You can point to the line in each test that reaches inside shipping (an underscore name, a mock.patch string, or a constant such as shipping.PER_KM).
Step 3 · Write a first test through the public function
Start the new suite in tests/. Each test follows arrange, act, assert: set up the inputs, make one call, check the result. Name the test after the rule it protects, so a failing name reads like a broken promise:
mkdir -p tests
cat > tests/test_delivery_fee.py <<'PY'
import pytest
from shipping import delivery_fee
def test_local_delivery_costs_base_fee_plus_120_per_km():
# Arrange
order_total, distance_km, weight_kg = 5000, 3, 2
# Act
fee = delivery_fee(order_total, distance_km, weight_kg)
# Assert
assert fee == 860 # 500 base + 3 km at 120
PY
uv run pytest -qTwo choices here matter more than they look. The test imports only delivery_fee, so it does not care what else lives in shipping.py. And the expected value is a plain number you worked out by hand from the written rule, not a sum built from the module's constants. If someone mistypes PER_KM as 210, this test fails; the old test_delivery_fee would pass.
The # Arrange, # Act, # Assert comments are there for teaching. In your own suites a blank line between the three parts is usually enough.
Check it worked
The run prints 1 passed. Read the test name aloud: it should sound like a line from the shop's rules.
Step 4 · Give each test one reason to fail
The old test_delivery_fee looped over distances inside one test. Replace that with parametrize, which makes each row its own test with its own result. Readable ids show up in the report, so a failure names the case:
cat >> tests/test_delivery_fee.py <<'PY'
@pytest.mark.parametrize(
("distance_km", "expected_fee"),
[
pytest.param(0, 500, id="collection-point-0-km"),
pytest.param(1, 620, id="1-km"),
pytest.param(12, 1940, id="12-km"),
pytest.param(2.5, 800, id="part-kilometre"),
],
)
def test_fee_rises_by_120_for_each_km(distance_km, expected_fee):
assert delivery_fee(5000, distance_km, 2) == expected_fee
PY
uv run pytest -vEvery expected fee in the table is a literal. There is no if, no loop and no arithmetic in the test body, so there is nothing in the test that can itself be wrong in a way you would miss. When you feel the urge to compute an expected value, write the number in and add a short comment showing where it came from.
Check it worked
-v lists five tests ending in PASSED, including test_fee_rises_by_120_for_each_km[part-kilometre], and the summary reads 5 passed.
Step 5 · Test the edges, with messages that explain the rule
Bugs gather at boundaries: exactly 10 kg, exactly 200.00. Test both sides of each one, and the error cases. Where a bare number would not tell the next reader why it matters, add a message after the assert:
cat >> tests/test_delivery_fee.py <<'PY'
def test_parcels_over_10_kg_add_a_heavy_surcharge():
assert delivery_fee(5000, 3, 10.5) == 1660 # 860 + 800
def test_a_parcel_of_exactly_10_kg_has_no_surcharge():
assert delivery_fee(5000, 3, 10) == 860
def test_orders_of_200_or_more_deliver_free():
fee = delivery_fee(20000, 3, 2)
assert fee == 0, "an order of exactly 200.00 must qualify for free delivery"
def test_orders_just_under_200_pay_the_fee():
assert delivery_fee(19999, 3, 2) == 860
def test_a_negative_distance_is_rejected():
with pytest.raises(ValueError, match="distance_km"):
delivery_fee(5000, -1, 2)
def test_a_zero_weight_is_rejected():
with pytest.raises(ValueError, match="weight_kg"):
delivery_fee(5000, 3, 0)
PY
uv run pytest -q || echo "pytest exited with status $?"pytest already shows both sides of a failed ==, so you do not need a message that repeats the values. The message is for the why: the rule the number comes from.
Check it worked
The summary reads 1 failed, 10 passed and the status is 1. The failure is test_orders_of_200_or_more_deliver_free, and the report shows something like:
AssertionError: an order of exactly 200.00 must qualify for free delivery
assert 860 == 0The new suite has found a real bug: the code uses > where the rule says "or more". The old suite passed with the same bug in place.
Step 6 · Fix the bug and run both suites
The test is right and the code is wrong, so change the code. Rewrite shipping.py with >= in the free-delivery check:
cat > shipping.py <<'PY'
"""Delivery fees for a small online shop. Amounts are in minor units."""
BASE_FEE = 500
PER_KM = 120
HEAVY_LIMIT_KG = 10
HEAVY_SURCHARGE = 800
FREE_DELIVERY_FROM = 20000
def _distance_fee(distance_km):
return round(distance_km * PER_KM)
def _weight_fee(weight_kg):
if weight_kg > HEAVY_LIMIT_KG:
return HEAVY_SURCHARGE
return 0
def delivery_fee(order_total, distance_km, weight_kg):
"""Return the delivery fee for an order, in minor units."""
if distance_km < 0:
raise ValueError(f"distance_km must be 0 or more, got {distance_km}")
if weight_kg <= 0:
raise ValueError(f"weight_kg must be above 0, got {weight_kg}")
if order_total >= FREE_DELIVERY_FROM:
return 0
return BASE_FEE + _distance_fee(distance_km) + _weight_fee(weight_kg)
PY
uv run pytest -q
uv run pytest legacy_tests -qCheck it worked
The new suite reports 11 passed and the old one still reports 3 passed. Both are green, but only one of them would have stopped the bug from reaching customers.
Step 7 · Rewrite the module and see which suite survives
Now a change that real code goes through: someone wants different tariffs for different cities, so the loose constants and helpers become one Tariff record, and the helpers are folded into delivery_fee. The function keeps its name and arguments, and every fee stays the same. Replace the whole file:
cat > shipping.py <<'PY'
"""Delivery fees for a small online shop. Amounts are in minor units."""
from dataclasses import dataclass
@dataclass(frozen=True)
class Tariff:
base: int = 500
per_km: int = 120
heavy_over_kg: float = 10
heavy_surcharge: int = 800
free_from: int = 20000
STANDARD = Tariff()
def delivery_fee(order_total, distance_km, weight_kg, tariff=STANDARD):
"""Return the delivery fee for an order, in minor units."""
if distance_km < 0:
raise ValueError(f"distance_km must be 0 or more, got {distance_km}")
if weight_kg <= 0:
raise ValueError(f"weight_kg must be above 0, got {weight_kg}")
if order_total >= tariff.free_from:
return 0
fee = tariff.base + round(distance_km * tariff.per_km)
if weight_kg > tariff.heavy_over_kg:
fee += tariff.heavy_surcharge
return fee
PY
uv run pytest -q
uv run pytest legacy_tests -q || echo "pytest exited with status $?"Read the old suite's failures. Each one is an AttributeError: shipping no longer has _distance_fee, mock.patch cannot find _weight_fee to replace, and BASE_FEE is gone. None of them is about a wrong fee. That is the cost of tests tied to implementation: they fail when the code improves, and someone has to spend time proving nothing is actually broken.
Check it worked
The new suite still reports 11 passed. The old one reports 3 failed with AttributeError lines, and the status is 1.
Step 8 · Retire the old suite and keep a review checklist
A suite that fails on safe changes is a cost, not a safety net. Delete it now that the new tests cover the same rules and more:
rm -r legacy_tests
uv run pytest -qWhen you review tests, yours or a colleague's, ask these questions of each one:
- Does it call only what other code calls? No underscore names, no reaching for module constants.
- Does its name state a rule a non-programmer would recognise?
- Is the expected value written out, with a comment if its origin is not obvious?
- Could it fail for only one reason? One action, one outcome checked.
- Is there no loop,
ifor arithmetic in the test body? - Does it cover both sides of each boundary in the rules?
- If it uses a mock, is that mock standing in for something slow or outside your control (a network call, a payment provider), rather than your own code?
If your team works on modest laptops or pays for mobile data by the megabyte, this style also helps there: tests that call plain functions need no network or extra services, and a suite like this runs in well under a second.
Remove the demo project when you are done:
cd ~
rm -rf ~/unit-tests-demoCheck it worked
Before the clean-up, uv run pytest -q reported 11 passed with only the tests/ folder left. Afterwards, ls ~/unit-tests-demo reports that the folder does not exist.
Next steps
- Refresh the pytest basics this tutorial builds on: write and run tests in Python with pytest.
- Apply the same idea to user interfaces, querying what the user sees: test UI code with Vitest and Testing Library.
- Learn when a test double is the right tool and when it ties you to the implementation: choose between mocks, stubs and fakes.
Related tutorials
- Write property-based tests in TypeScript with fast-checkYou will use fast-check and Vitest to find a rounding bug in a TypeScript money module, replay the failure from its seed, fix it, and model-test a shopping cart with generated command sequences.
- Write negative tests for an API: bad input, auth and limitsYou will build a pytest and httpx suite that attacks a small FastAPI ordering API with missing and extra fields, wrong types, boundary values, long and multilingual text, bad tokens, another user's data, rate limits and reused idempotency keys, and proves every error comes back in one RFC 9457 format.
- Write Java unit tests with JUnit 6 and AssertJYou will test a small transfer-fee calculator with JUnit 6.1 and AssertJ 3.27, using display names, nested and parameterised tests, exception checks, soft assertions, a temporary folder and one Mockito mock, and finish with 18 passing tests from mvn test.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials