Python Testing with pytest: A Safety Net for Your Code
AI writes code fast, but only tests tell you whether one change broke something else. This guide starts from zero — installing pytest, writing your first test, reading failure output — then covers parametrize, fixtures, tmp_path, monkeypatch and mocking, finishing with coverage. Every example was actually run on Python 3.12 with pytest 9.2.0.

With AI writing code, the biggest change is not that you write faster — it is that you change faster. It used to take courage to edit one line of code; now AI rewrites it in seconds. But after the change, how do you know it did not quietly break something else? Reading the code by eye will not tell you. That is what tests are for: a small piece of code that automatically checks another piece of code. Change something, run the tests, green means you are safe, red tells you exactly what broke.
pytest is the most widely used testing tool in Python. You do not need to subclass anything or write boilerplate: a plain function plus one assert is already a test. This guide starts from zero — installing pytest, writing your first test, reading failure output — then covers parametrize, fixtures, tmp_path, monkeypatch and mocking, and finishes with coverage. Every example in this guide was actually run on Python 3.12.3 with pytest 9.2.0: 20 tests, all passing.
The running example is a tiny shopping cart: apply a discount, compute a line total, compute the whole order total. The code is short, but it is enough to practise every technique in this guide.
Step 1: install pytest
Create a virtual environment first, then install pytest into it. Do not install it into your system Python, or different projects will step on each other:
python3 -m venv .venv
source .venv/bin/activate
pip install pytest
pytest --version
On my machine this printed pytest 9.2.0 with Python 3.12.3. If you also want to measure coverage, install one plugin:
pip install pytest-cov
The pytest-cov used here is version 7.1.0. Build one habit now: always run tests inside the virtual environment, and always with the pytest command — never python test_xxx.py.
Your first test: deliberately write a wrong one
Create a file called test_failure_demo.py with a deliberately wrong expectation:
def add(x):
return x + 1
def test_add():
assert add(3) == 5
Run pytest -q test_failure_demo.py and you get this:
F [100%]
=================================== FAILURES ===================================
___________________________________ test_add ___________________________________
def test_add():
> assert add(3) == 5
E assert 4 == 5
E + where 4 = add(3)
test_failure_demo.py:5: AssertionError
=========================== short test summary info ============================
FAILED test_failure_demo.py::test_add - assert 4 == 5
1 failed in 0.02s
This output is worth reading line by line, because you will read it every day from now on. The F on the first line means one test failed; a pass shows as .. Then assert 4 == 5 states the failure, and the next line, where 4 = add(3), is pytest's best trick: it takes your assert expression apart and shows you the intermediate value. This is called assert rewriting — you just write a plain assert, and pytest prints the values inside it for you. The last block is the summary: which test failed, why, and how long the run took.
Change the expectation to 4 and run again, and the output becomes 1 passed in 0.02s. That is the whole idea: write down what you expect, and let the machine check it.
Where tests live and what they are called
pytest finds tests by fixed rules. Three are enough to remember. First, test files must be named test_*.py or *_test.py; the first form is the most common. Second, test functions must start with test_. Third, if you group tests in a class, the class name must start with Test and the class must not define __init__.
Test files can sit next to the code they test, or in a separate tests directory. When you are starting out, keep them in the same directory — imports stay simple, like from cart import apply_discount. Split them out once the project grows.
One common beginner mistake: giving a test function a return value, or a parameter pytest does not recognise. Test function parameters may only be fixture names (covered below); add any other parameter and pytest errors out saying it cannot find that fixture.
The code under test: a tiny shopping cart
Here is the code the whole guide tests, saved as cart.py. Three functions: apply a discount, compute a line total, compute the order total. Note the two checks: the price must not be negative, and the discount must not exceed 50%:
"""Tiny shopping-cart totals, used as the running example in this guide."""
DISCOUNT_LIMIT = 0.5
def apply_discount(price, percent):
if price < 0:
raise ValueError("price must not be negative")
if not 0 <= percent <= DISCOUNT_LIMIT:
raise ValueError("discount percent must be between 0 and 0.5")
return round(price * (1 - percent), 2)
def line_total(price, qty):
if qty < 0:
raise ValueError("qty must not be negative")
return round(price * qty, 2)
def cart_total(items, discount=0):
total = sum(line_total(price, qty) for price, qty in items)
return apply_discount(total, discount)
Before writing tests, decide what to verify: does the normal case compute correctly? Do the boundary values (0% and 50% discount) work? Does invalid input raise the expected error? Will floating-point arithmetic be slightly off? Those four questions map to the four techniques below.
Common ways to write asserts
The simplest form is a plain assert:
def test_apply_discount_basic():
assert apply_discount(100, 0.1) == 90.0
def test_apply_discount_zero():
assert apply_discount(59.9, 0) == 59.9
To check that code raises an error, use pytest.raises. It is a context manager: the code inside the with block must raise the given exception, or the test fails. The match argument also checks that the error message contains a word:
def test_negative_price_raises():
with pytest.raises(ValueError, match="negative"):
apply_discount(-5, 0.1)
def test_discount_over_limit_raises():
with pytest.raises(ValueError):
apply_discount(100, 0.9)
Be careful with floating-point comparison. 0.1 + 0.2 is not exactly 0.3 inside a computer, so a direct == 0.3 fails. pytest ships pytest.approx, which means “close enough”:
def test_float_approx():
assert 0.1 + 0.2 == pytest.approx(0.3)
Other plain forms work too — assert x in xs, assert x is None, assert len(xs) == 3 — and assert rewriting shows the intermediate values. One rule: only use assert in tests. Never hand-roll checks like if ...: print("fail"); a human can read your print, but a machine cannot.
parametrize: one test, many data sets
One data set is not enough for the discount function: 0%, 10%, 50% and a price with decimals all need checking. Copy-pasting a test function per data set makes the file unreadable fast. @pytest.mark.parametrize solves this: list several inputs with their expected outputs, and pytest runs the same test function once per row:
@pytest.mark.parametrize("price,percent,expected", [
(100, 0, 100.0),
(100, 0.1, 90.0),
(200, 0.5, 100.0),
(59.9, 0.2, 47.92),
])
def test_apply_discount_many(price, percent, expected):
assert apply_discount(price, percent) == expected
With pytest -v you will see it become four separate tests, each named with its parameters: test_apply_discount_many[100-0-100.0], test_apply_discount_many[59.9-0.2-47.92], and so on. When one fails, you know exactly which row it was.
Two details to watch. First, parameter values are passed as-is, with no copy — so do not mutate a list or dict passed in as a parameter inside the test, or the next row will see the change. Second, if you know a row currently fails but want to keep it, mark it with pytest.param(..., marks=pytest.mark.xfail) and it will show as xfailed instead of FAILED.
Fixtures: pull the setup work out
Many tests need the same data, such as a cart [(100, 2), (59.9, 1)]. Copying it at the top of every test is tedious and easy to miss when it changes. A fixture pulls the “prepare data” step into a function:
# content of conftest.py
import pytest
@pytest.fixture
def items():
"""Fresh cart for every test (function scope, the default)."""
return [(100, 2), (59.9, 1)]
@pytest.fixture(scope="module")
def catalog():
"""Loaded once per test module; read-only shared data."""
return {"book": 59.9, "pen": 12.5, "bag": 100.0}
A test just names the fixture as a parameter, and pytest runs it first and passes the return value in:
def test_items_is_fresh_each_time(items):
items.append((10, 1))
assert len(items) == 3
def test_items_starts_fresh_again(items):
assert len(items) == 2
assert cart_total(items) == 259.9
The first test adds an item to the list, but the second test still receives the original two items. That is the default function scope: every test gets fresh data, so tests cannot contaminate each other. I ran this for real, and both tests pass.
When is a wider scope worth it? When preparing the data is expensive — reading a large file, connecting to a database — redoing it for every test is slow, so you can switch the scope to module (shared by tests in one file) or even session (done once for the whole run). The price is that shared data must not be mutated by tests, or they will affect each other. So the rule is: mutable data stays at function scope; only read-only data gets a wider scope. The catalog above is a read-only dict, which is why module scope fits it.
conftest.py is a special file: fixtures defined in it apply to every test in its directory and below, with no import needed — just use the name. As a project grows, shared fixtures all live here.
tmp_path: what if a test needs to write a file?
Some code reads and writes files, for example saving a receipt. A test must not write into a real directory — what if it overwrites something? pytest ships a built-in tmp_path fixture that hands you a brand-new empty temporary directory on every call and cleans it up afterwards:
# content of receipt.py
from pathlib import Path
def save_receipt(path, lines):
text = "\n".join(lines) + "\n"
Path(path).write_text(text, encoding="utf-8")
return Path(path)
# content of test_receipt.py
from receipt import save_receipt
def test_save_receipt_writes_file(tmp_path):
target = tmp_path / "receipt.txt"
save_receipt(target, ["book x1 59.90", "total 59.90"])
assert target.read_text(encoding="utf-8") == "book x1 59.90\ntotal 59.90\n"
This test genuinely passes. One detail: pass encoding="utf-8" both when writing and when reading, so receipts with non-ASCII text do not get mangled on different systems.
monkeypatch: temporarily change env vars and functions
Some code reads environment variables, such as an API base URL. To test with a different URL without actually changing your system environment, use the built-in monkeypatch fixture:
# content of settings.py
import os
def api_base():
return os.environ.get("SHOP_API_BASE", "https://api.example.invalid")
# content of test_settings.py
from settings import api_base
def test_default_base():
assert api_base() == "https://api.example.invalid"
def test_env_overrides_base(monkeypatch):
monkeypatch.setenv("SHOP_API_BASE", "https://shop.test")
assert api_base() == "https://shop.test"
The key point: when the test ends, monkeypatch automatically restores the environment variable, so other tests are unaffected. It can also temporarily replace a function — monkeypatch.setattr(convert, "fetch_rate", lambda: 0.14) — and restore it afterwards. That is far less error-prone than hand-writing try/finally to undo the change.
Mocking: do not really go on the network
Consider a common case: the code calls an external API to fetch an exchange rate. Tests must not really hit the network — it is slow, flaky, and can cost money. The right move is to swap the “fetch the rate” step for a fake:
# content of convert.py
"""Currency conversion; fetch_rate() stands in for a real network call."""
def fetch_rate():
raise RuntimeError("no network in tests: patch fetch_rate")
def to_usd(cny):
return round(cny * fetch_rate(), 2)
Two ways to do it. First, with monkeypatch:
import convert
from convert import to_usd
def test_to_usd_with_monkeypatch(monkeypatch):
monkeypatch.setattr(convert, "fetch_rate", lambda: 0.14)
assert to_usd(100) == 14.0
Second, with the standard library's unittest.mock:
from unittest import mock
from convert import to_usd
def test_to_usd_with_mock_patch():
with mock.patch("convert.fetch_rate", return_value=0.14):
assert to_usd(100) == 14.0
Both work the same; pick whichever reads better to you. But mocking has two red lines. First, only mock things you do not own: the network, a database, a third-party service. Never mock the function you are actually testing — that is like peeking at the answer key during your own exam. Second, the mock's return value must look like the real thing: returning 0.14 for an exchange rate is fine, but if the real API returns a dict, your mock must return a dict too, or the test will pass while the real code still breaks.
I also ran the negative case: calling to_usd(100) with no patch raises RuntimeError with the message no network in tests, as expected. That test exists to prove the code really does reach for the network when unpatched — a useful self-check.
Running tests: -v, -k, -x and friends
The commands you will use most often:
pytest: run all tests in the current directory and below.pytest -v: verbose mode, one line per test with its name and status.pytest -q: quiet mode, just the result — handy when there are many tests.pytest -k discount: only run tests whose name contains “discount”. On my machine this printed7 passed, 12 deselected in 0.04s— 7 of the 20 tests selected.pytest test_cart.py: run a single file.pytest --collect-only -q: list the tests that would be collected, without running them. Use it to check naming mistakes, like a function missing itstest_prefix.pytest -x: stop at the first failure, fix it, then run everything again.pytest --lf: only re-run the tests that failed last time — the fastest loop when fixing a bug.
The full run of this guide's example looks like this — 20 tests, all passing:
============================== 20 passed in 0.06s ==============================
One function, test_apply_discount_many, contributes four test cases by itself, and the two fixture-scope tests prove data isolation really works.
One more practical trick: every line of -v output is a test's full name, in the form file::function[parameters] — for example test_cart.py::test_apply_discount_many[100-0-100.0]. You can pass that name straight to pytest to run just that one test: pytest "test_cart.py::test_apply_discount_many[100-0-100.0]". When one parameter combination fails, you can focus on that single case instead of re-running the whole suite, then run everything again once it is fixed.
Coverage: see which lines were never tested
All tests passing does not mean all code was tested. Coverage measures exactly that. With pytest-cov installed, run:
pytest --cov=cart --cov=convert --cov=receipt --cov=settings --cov-report=term-missing
My first run came back at 96%, not 100%:
Name Stmts Miss Cover Missing
-------------------------------------------
cart.py 14 1 93% 15
convert.py 4 0 100%
receipt.py 5 0 100%
settings.py 3 0 100%
-------------------------------------------
TOTAL 26 1 96%
The missing line was cart.py line 15 — the branch in line_total that raises when qty is negative. I had genuinely forgotten to test a negative quantity. One more test closed the gap:
def test_negative_qty_raises():
with pytest.raises(ValueError, match="qty"):
line_total(100, -1)
Run it again and TOTAL becomes 100%, with all four files at 100%. That is the value of coverage: it will not tell you whether your tests are good, but it will tell you precisely which lines never ran at all. By the way, adding that test caught a small mistake of my own first: I forgot to add line_total to the import, and the run came back NameError — test code is code too, and it has bugs that only running can reveal.
How much coverage is enough? There is no universal answer. A small project can aim for 100%; a large one is usually fine above 80%. Do not write meaningless tests just to push the number up — testing a bare return x line makes the number look good and your confidence no better.
How pytest differs from unittest
Python ships with a testing framework called unittest, and many tutorials teach it first. Both can write tests, but the style differs a lot. unittest requires tests inside a class that inherits from unittest.TestCase, assertions written as special methods like assertEqual and assertTrue, and setup work in setUp. pytest asks for none of that: plain functions, plain assert, and fixtures for setup — code that reads like everyday Python.
pytest is also more convenient in practice. When a unittest assertion fails it only tells you the values were not equal; pytest's assert rewriting shows both sides. Running one test over many data sets in unittest means writing your own loop or using subtests; in pytest it is one parametrize decorator. unittest has few plugins, while pytest has hundreds — coverage, parallel runs, randomised ordering, all ready-made. One more practical point: pytest can run unittest-style tests directly, with no rewriting. So if your project already has unittest tests, install pytest, run them as they are, and write new tests the pytest way — the two live side by side.
Does that make unittest useless? No. If you write standard-library-style code, or your team requires the standard library only, unittest is perfectly fine. But for someone learning testing, pytest has the lower barrier and the clearer feedback, so it is the better place to start. Once you are comfortable with it, unittest will look like the same ideas with different spelling.
The test pyramid: how tests should be layered
Tests come in three layers: the further down, the more of them, the faster and cheaper they are. At the bottom are unit tests: they test one function, run in milliseconds, and when one fails you know exactly which line broke — they should be the majority. In the middle are integration tests: they check that several modules work together, for example the cart plus the receipt module. At the top are end-to-end tests: they walk a whole real flow, like opening a web page, placing an order and receiving a receipt — the slowest and most fragile kind, kept few in number and only for the most important flows.
The classic beginner mistake is to build the pyramid upside down: almost no unit tests, and end-to-end tests doing all the work. The result is a suite that runs slowly and, when it fails, gives no clue which part broke. Do it the right way round: a solid bottom layer first, a moderate middle, and only the key flows at the top.
Seven common pitfalls, with fixes
- Forgetting the test_ prefix on a test function. pytest silently skips it, which is harder to spot than an error. Fix: run
pytest --collect-only -qand count the collected tests. - Tests affecting each other. One test changes a global, writes a file or touches a database, and the next test suffers. Fix: function-scoped fixtures for mutable data, tmp_path for files, monkeypatch for env vars.
- Judging results with print instead of assert. Tiring to read by eye, and useless in CI. Fix: express every check as an assert.
- Comparing floats with ==.
0.1 + 0.2 == 0.3is False. Fix: usepytest.approx, or store money as integer cents. - Mocking the function you are testing. Like copying the answers onto your own exam paper. Fix: only mock external dependencies — network, database, third-party services.
- Really hitting the network or a live database in tests. Slow, and randomly failing when the network wobbles. Fix: replace those calls with monkeypatch or mock, and keep one or two integration tests for the real thing.
- Running tests only on your own machine. Local and CI environments differ — paths, env vars, dependency versions. Fix: put
pytestin CI from day one so every commit runs the suite automatically.
Wrap-up: a checklist you can use right away
You now know enough to write tests that work. Next time you write code, walk through this order: create a virtual environment and install pytest; write one or two tests for the normal case of each function; cover boundary values and invalid input with parametrize and pytest.raises; pull shared setup into fixtures; use tmp_path for files; replace network calls with mocks; finally run coverage and look for lines you missed.
There is no silver bullet for good tests — only one standard: next time you change code, are you willing to run the tests, see green, and commit? If yes, the suite is good enough. If this guide got you there, it has done its job. One last habit for reading errors: look at the first and last lines first — most problems are stated right there; if you still cannot see it, paste the full error to an AI and ask it to point at the exact line and assertion.
A good next step is the fixture and parametrize chapters of the official pytest docs, or the first batch of tests for your own real project — start with the most important function, and do not try to do everything at once.
Comments (0)
Sources
Related articles
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.
Building stock of 2000 books moves current memory from 0.3 KiB to 582.7 KiB; subtracting two snapshots, the biggest line is line 85 at 568.1 KiB and 9699 blocks; getsizeof sees only 15.8 KiB, and clearing brings the line back to 0.0 KiB. Python 3.12.3 stdlib, measured.
Port 8000 in code, 8080 in the config file, 9090 from the environment: each layer changes only its own keys, and the last one wins. Defaults plus INI plus env vars, bool('False') is True, and a missing key should fail at startup. Python 3.12.3 stdlib only.