Skip to content
Visual explainer 4h to learn 5 steps

Testing with pytest

Write unit tests with fixtures and parametrisation and run them on every change.

By Invicly Tech, , in Python Programming from Zero. About 10 minutes to read.

Topic 25 of 34

In short

pytest finds functions named test_* and runs them, reporting which assertions fail. Fixtures share setup and parametrize runs one test over many inputs, so checking your code after every change takes seconds.

Explained simply

A test is a small piece of code that runs your real code and checks the answer. Instead of starting your program and clicking around after every change, you run one command and see in seconds whether everything still works.

pytest is the most popular tool for this in Python. You write normal functions whose names start with test_, and inside them you use plain assert statements, like assert add(2, 3) == 5. pytest finds these functions, runs them all, and shows a clear report of what passed and what failed.

When a test fails, pytest shows both sides of the comparison, so you can see exactly what came back. A green run gives you confidence to change code. A red run tells you which change broke what, while it is still fresh in your mind.

Two features save a lot of typing. Fixtures prepare things a test needs, such as sample data or a temporary folder. Parametrize runs one test many times with different inputs. Together they let you test many cases with very little code.

Press Play on a diagram to walk through it one step at a time.

CycleTest-driven loop
  1. 1
    Write a test

    Describe the behaviour you want

  2. 2
    Run: it fails

    Red: proves the test can catch a bug

  3. 3
    Write the code

    Simplest code that passes

  4. 4
    Run: it passes

    Green: behaviour confirmed

  5. 5
    Refactor

    Clean up while tests keep you safe

  6. Back to step 1
MapBuilt-in fixtures worth knowing
pytest fixtures
  • tmp_path
    • Fresh temporary folder per test
    • A pathlib.Path
  • monkeypatch
    • setenv / delenv
    • setattr to replace a function
    • Undone after the test
  • capsys
    • readouterr().out
    • Checks what was printed
  • Your own (conftest.py)
    • Sample data
    • A database connection
    • Shared by a whole folder

In depth

How a pytest run works

pytest starts from the current folder (or the testpaths you configure) and collects tests: files named test_*.py or *_test.py, functions named test_*, and methods named test_* inside classes named Test* (which must not have an __init__). For each test, it creates the fixtures the test asks for, runs it, then tears the fixtures down.

pytest rewrites assert statements when it imports test files, which is how it can show the values on both sides of a failed comparison. The process exit code tells scripts and CI what happened: 0 means all passed, 1 means some failed, 2 means the run was interrupted, and 5 means no tests were collected, often a sign of a naming mistake.

  • pytest -x stops at the first failure
  • pytest -k discount runs only tests whose names match
  • pytest --lf reruns only the tests that failed last time
  • pytest -s shows print() output while tests run
FlowOne pytest run
  1. 1
    Collect

    Find test_*.py files and test_* functions

  2. 2
    Set up fixtures

    Build what each test asks for

  3. 3
    Run the test

    Rewritten asserts record values

  4. 4
    Tear down

    Code after yield in fixtures runs

  5. 5
    Report and exit

    Exit code 0 only if all passed

Checking errors and floats properly

with pytest.raises(ValueError): passes only if the block raises ValueError (or a subclass). Add match="negative" to also check the message; match is a regular expression searched in str(error). Write with pytest.raises(ValueError) as excinfo: when you want to inspect the error afterwards through excinfo.value. Keep only the one line that should fail inside the block, so an earlier line cannot raise by accident and make the test pass for the wrong reason.

Floats need care: 0.1 + 0.2 == 0.3 is False in Python because of how binary floating point works. Use assert 0.1 + 0.2 == pytest.approx(0.3), which allows a tiny relative difference (one millionth by default). approx also works on lists and dicts of numbers.

  • with pytest.raises(KeyError, match="user"):
  • assert total == pytest.approx(19.99)
  • assert result == pytest.approx([0.33, 0.67], abs=0.01)

Fixtures: setup, teardown and scope

A fixture is a function marked with @pytest.fixture. A test asks for it simply by naming it as a parameter, and pytest passes in the return value. If the fixture uses yield instead of return, the code after yield runs as teardown, even when the test fails, which is perfect for closing connections or deleting files.

By default a fixture is rebuilt for every test (scope="function"), so tests cannot leak state into each other. For expensive setup, use scope="module" or scope="session" to share one instance. Put fixtures in a file named conftest.py and every test in that folder can use them without importing anything. Learn three built-ins early: tmp_path gives a fresh temporary folder, monkeypatch changes environment variables or attributes and undoes it after, and capsys captures printed output.

SequenceA yield fixture around one test
pytest
fixture db
test_add
  1. 1run code before yield
    pytest to fixture db: run code before yield
  2. 2yield connection
    fixture db to pytest: yield connection
  3. 3call test_add(db=connection)
    pytest to test_add: call test_add(db=connection)
  4. 4pass or fail
    test_add to pytest: pass or fail
  5. 5resume after yield: close it
    pytest to fixture db: resume after yield: close it

Parametrize in more detail

@pytest.mark.parametrize("a, b, expected", [(1, 2, 3), (0, 0, 0)]) turns one test function into one test per tuple. Each case is reported on its own, with an id built from the values, like test_add[1-2-3], so one failing case does not hide the others. Pass ids=["small", "zero"] for readable names.

Stacking two parametrize decorators runs every combination: 3 values times 4 values gives 12 tests. Wrap a single case in pytest.param(..., marks=pytest.mark.xfail) to mark a known bug without deleting the case. Parametrize is ideal for edge cases: empty input, zero, negative numbers, very large values, unusual characters. Writing them as a table makes missing cases easy to spot.

Making tests part of every change

A common layout is your code in a package (for example src/tracker/) and tests in a tests/ folder. Configure pytest in pyproject.toml under [tool.pytest.ini_options], for example testpaths = ["tests"]. Run python -m pytest rather than plain pytest if imports fail: it adds the current folder to the import path.

Then make running tests automatic. Run the suite before every commit, or let CI (for example GitHub Actions) run it on every push and pull request, so a failing test blocks the merge. Keep unit tests fast, ideally the whole suite in seconds, by avoiding real network calls and big files. The pytest-cov plugin (pytest --cov=tracker) shows which lines were never run by any test, which is a good guide to what to test next.

  • pip install pytest pytest-cov
  • python -m pytest -q
  • pytest --cov=tracker --cov-report=term-missing

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Install pytest and write first tests~50m
  2. 2
    Use assert and pytest.raises~50m
  3. 3
    Share setup with fixtures~50m
  4. 4
    Parametrise tests over many inputs~50m
  5. 5
    Run tests on every change~50m

Key points

  • Put tests in files named test_*.py and functions named test_*.
  • Plain assert statements are enough; pytest shows the values that differed.
  • with pytest.raises(ValueError): checks that an error is raised.
  • @pytest.fixture provides shared setup; built-in tmp_path gives a temp folder.
  • @pytest.mark.parametrize runs one test against many input cases.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
# test_pricing.py
import pytest
from pricing import apply_discount

@pytest.mark.parametrize("price, pct, expected", [
    (100, 10, 90),
    (50, 0, 50),
    (20, 100, 0),
])
def test_apply_discount(price, pct, expected):
    assert apply_discount(price, pct) == expected

def test_rejects_negative_percent():
    with pytest.raises(ValueError):
        apply_discount(100, -5)  # run with: pytest -q

A fixture with teardown shared through conftest.py

Several test files need a fresh store backed by a real file. Step 1: put the fixture in conftest.py so every test file can use it without importing. Step 2: build the store inside tmp_path, so real data is never touched. Step 3: yield it to the test; the close() after yield always runs. Step 4: the test only names store as a parameter.

python
# tests/conftest.py
import pytest
from tracker.storage import Store

@pytest.fixture
def store(tmp_path):
    s = Store(tmp_path / "data.json")
    yield s            # the test runs here
    s.close()          # teardown, even if the test failed

# tests/test_store.py
def test_add_then_list(store):
    store.add("coffee", 3.5)
    assert store.list() == [("coffee", 3.5)]

Testing environment variables and printed output

greet() reads a name from an environment variable and prints a greeting. Step 1: monkeypatch.setenv sets the variable for this test only and restores it afterwards. Step 2: call the function. Step 3: capsys.readouterr().out returns everything printed so far, including the newline that print adds.

python
# greet.py
import os
def greet():
    name = os.environ.get("USER_NAME", "friend")
    print(f"Hello, {name}!")

# test_greet.py
from greet import greet

def test_greet_uses_env(monkeypatch, capsys):
    monkeypatch.setenv("USER_NAME", "Ana")
    greet()
    assert capsys.readouterr().out == "Hello, Ana!\n"

Quick reference

  • Files test_*.py, functions test_*; run with python -m pytest -q
  • with pytest.raises(ValueError, match="negative"): checks type and message
  • Compare floats with pytest.approx, never plain ==
  • Fixtures in conftest.py are available to every test in that folder
  • yield in a fixture: code after it is teardown and always runs
  • pytest -x stops at first failure; --lf reruns last failures; -k filters by name
  • Exit code 5 means no tests were collected: check your file and function names

Common mistakes

  • Tests that depend on each other's order or shared global state.
  • Only testing the happy path, never the error cases.
  • Comparing floats with == instead of pytest.approx().

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1pytest reports "no tests ran" and exits with code 5. What is the most likely cause?

Question 2

2What does assert 0.1 + 0.2 == 0.3 do in a test?

Question 3

3A fixture has code after its yield statement. When does that code run?

Question 4

4Two stacked parametrize decorators have 3 and 4 values. How many tests run?

Question 5

5Which built-in fixture lets a test set an environment variable that is restored afterwards?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write slugify(text) that lowercases text and replaces spaces with hyphens, plus two tests: a normal title and an empty string.

  2. Exercise 2medium

    Test apply_discount(price, pct) over at least four cases with readable ids, including a float result, and check that pct above 100 raises ValueError with a message containing "pct".

  3. Exercise 3hard

    weather.py has temp(city) which calls requests.get(URL, params={"city": city}, timeout=10) and returns r.json()["temp"]. Test it offline, and check which params were sent.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

pytest or unittest?
unittest is built in and uses classes with methods like self.assertEqual. pytest needs an install but is shorter, has fixtures and parametrize, and can also run unittest-style tests, so most new projects use it.
Why does pytest say ModuleNotFoundError for my own module?
The project folder is not on the import path. Run python -m pytest from the project root, install your package in the venv with pip install -e ., or set pythonpath in the pytest config.
How many tests should I write?
Cover every important behaviour and every bug you fix, plus edge cases like empty input. Coverage reports help find untested code, but 100% coverage is not the goal by itself.
Should tests print things?
No, use asserts. pytest hides output of passing tests anyway; run with -s if you need to see prints while debugging.

Go deeper

ShareXLinkedInWhatsApp