Updated for Python 3.12+ ยท June 2026

Testing with pytest
Write tests you actually trust

A complete, practical guide to pytest โ€” from your first assert to fixtures, parametrisation, mocking, coverage, and test-driven development. Runnable examples throughout.

test_math.py
def add(a, b):
    return a + b

def test_add_positive():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-2, -3) == -5
$ pytest -q
..
2 passed in 0.01s

๐Ÿงช Why Test at All?

Tests are the safety net that lets you change code without fear

The Real Value of Tests

Tests are often described as proof that code works. That's only half the story. Their bigger job is to catch regressions โ€” the moment a change breaks something that used to work. Without tests, every edit carries a quiet risk, and that risk compounds as a codebase grows.

A good test suite also acts as executable documentation. When a new developer wants to understand what a function is supposed to do, the tests show the expected behaviour more directly than any comment. And because tests run automatically, they stay accurate in a way that comments never do.

The final benefit is confidence to refactor. With a solid test suite in place, you can restructure code freely and let the tests tell you immediately if you broke something. That's what makes long-term maintenance possible.

Why pytest?

pytest is the de facto standard testing framework for Python. It requires far less boilerplate than unittest, uses plain assert statements with rich failure output, and has a deep fixture system that makes test setup reusable. It's installable with pip install pytest.

  • โœ“Write and run your first tests with plain assert
  • โœ“Use fixtures to share setup code without repetition
  • โœ“Parametrise tests to cover many inputs in one function
  • โœ“Mock external dependencies so tests stay fast and deterministic
  • โœ“Measure coverage and interpret the results honestly
  • โœ“Apply test-driven development to a real feature

๐Ÿฃ Your First Test

Install pytest, write a test, run it

pytest discovers tests automatically. By convention, test files are named test_*.py or *_test.py, and test functions are named test_*. Run pytest in your project root and it finds them.

terminal โ€” install & run
# Install pytest into your virtual environment
python -m pip install pytest

# Run all tests in the current directory
pytest

# Run a single file
pytest test_math.py

# Run a single test by name
pytest test_math.py::test_add_positive

# Quiet output
pytest -q

# Stop at first failure
pytest -x

A complete example

test_math.py
def add(a, b):
    return a + b

def divide(a, b):
    if b == 0:
        raise ValueError("cannot divide by zero")
    return a / b

def test_add():
    assert add(2, 3) == 5

def test_divide():
    assert divide(10, 2) == 5.0

def test_divide_by_zero_raises():
    import pytest
    with pytest.raises(ValueError):
        divide(1, 0)
Plain assert is the point. Unlike unittest, which requires self.assertEqual, self.assertTrue, and so on, pytest lets you write ordinary Python assertions. When one fails, pytest rewrites the expression and shows you exactly which values were involved.

Reading a failure

# Suppose test_add was wrong: assert add(2, 3) == 6

$ pytest -q
F                                                          [100%]
================================= FAILURES =================================
_________________________________ test_add _________________________________
    def test_add():
>       assert add(2, 3) == 6
E       assert 5 == 6
E        +  where 5 = add(2, 3)
========================= short test summary info ==========================
FAILED test_math.py::test_add - assert 5 == 6

The failure output shows the exact values on both sides. This is what makes pytest's assertion rewriting so useful โ€” you don't need to add custom messages for most failures.

โœ๏ธ Assertions & Exceptions

Testing both outcomes and errors

Test behaviour, not implementation. Good tests describe what a function does from the outside. They shouldn't reach into internal state unless that state is part of the public contract.

Common assertion patterns

What you're checkingpytest wayNotes
Equalityassert result == expectedMost common form
Truthinessassert resultWorks for non-empty containers
Membershipassert item in collectionReads naturally
Identityassert result is NoneUse is for singletons
Approximate floatsassert value == pytest.approx(3.14)Handles float precision
Raises an exceptionwith pytest.raises(ValueError):Context manager form

Testing exceptions and their messages

import pytest

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError(f"insufficient funds: {amount} > {balance}")
    return balance - amount

def test_withdraw_raises_on_insufficient_funds():
    with pytest.raises(ValueError) as excinfo:
        withdraw(100, 150)

    assert "insufficient funds" in str(excinfo.value)

def test_withdraw_succeeds():
    assert withdraw(100, 40) == 60
Use pytest.raises rather than a bare try/except in tests. If the exception isn't raised, pytest.raises fails the test automatically; a bare try/except would silently pass.

Float comparisons

import pytest

def test_float_precision():
    # 0.1 + 0.2 != 0.3 exactly in binary floating point
    assert 0.1 + 0.2 == pytest.approx(0.3)

def test_circle_area():
    import math
    area = math.pi * 2 ** 2
    assert area == pytest.approx(12.566, rel=1e-3)

pytest.approx supports both absolute tolerance (abs) and relative tolerance (rel). Use it whenever a value went through floating-point arithmetic.

๐Ÿ”ง Fixtures โ€” Reusable Setup

Share setup code across tests without copy-paste

A fixture is a function that provides data or setup to tests. Declare it with @pytest.fixture, then name it as a parameter in any test that needs it. pytest will call the fixture and pass in its return value.

test_fixtures.py
import pytest

@pytest.fixture
def sample_user():
    return {"name": "Ana", "age": 30, "active": True}

def test_user_is_active(sample_user):
    assert sample_user["active"] is True

def test_user_has_name(sample_user):
    assert sample_user["name"] == "Ana"

def test_user_age(sample_user):
    assert sample_user["age"] >= 18
Fixtures are composable. A fixture can request other fixtures as parameters. That makes it easy to build layered setup: a database fixture that depends on a config fixture, for example.

Setup and teardown with yield

import pytest

@pytest.fixture
def temp_file(tmp_path):
    # SETUP
    path = tmp_path / "data.txt"
    path.write_text("hello")
    yield path
    # TEARDOWN (runs after the test finishes)
    if path.exists():
        path.unlink()

def test_file_contents(temp_file):
    assert temp_file.read_text() == "hello"

Everything after yield is teardown. This runs even if the test fails, which is what you want for cleanup.

Fixture scopes

ScopeCreatedBest for
function (default)Once per testMost fixtures โ€” isolated state
classOnce per test classShared setup for related tests
moduleOnce per test fileExpensive setup (DB schema)
sessionOnce per test runVery expensive, read-only resources
Wider scopes are faster but riskier. A session-scoped fixture shared across tests can hide bugs caused by state leakage. Start with function scope and widen only when you have a measured reason to.

Where to put fixtures

  • In the test file itself for fixtures used by only that file
  • In conftest.py for fixtures shared across multiple test files in the same directory
  • In a plugin or a top-level conftest.py for fixtures shared across the whole project

pytest discovers conftest.py automatically โ€” you don't import it. This is the standard way to share fixtures without duplicating code.

๐ŸŽ›๏ธ Parametrize โ€” Many Cases, One Test

Cover multiple inputs without writing multiple functions

@pytest.mark.parametrize runs one test function once per parameter set. When one case fails, pytest reports which inputs caused it โ€” so you get the coverage of many tests without the repetition.

test_parametrize.py
import pytest

def is_palindrome(s):
    return s == s[::-1]

@pytest.mark.parametrize("word, expected", [
    ("racecar", True),
    ("level",   True),
    ("hello",   False),
    ("",        True),
    ("a",       True),
])
def test_is_palindrome(word, expected):
    assert is_palindrome(word) is expected
Failure isolation. If "hello" was incorrectly classified as a palindrome, only that case would fail โ€” the other four would still pass. That makes it easy to see exactly which input broke.

Multiple parameter sets

import pytest

@pytest.mark.parametrize("a, b, expected", [
    (1, 2, 3),
    (0, 0, 0),
    (-1, 1, 0),
])
@pytest.mark.parametrize("offset", [0, 10])
def test_add_with_offset(a, b, expected, offset):
    assert (a + b) + offset == expected + offset

Stacked parametrize decorators produce a Cartesian product. The example above runs 3 ร— 2 = 6 test cases.

Parametrising with readable IDs

import pytest

@pytest.mark.parametrize("value, expected", [
    ("2024-01-01", True),
    ("not-a-date", False),
], ids=["valid_date", "invalid_date"])
def test_date_validator(value, expected):
    from datetime import datetime
    try:
        datetime.strptime(value, "%Y-%m-%d")
        valid = True
    except ValueError:
        valid = False
    assert valid is expected

Custom IDs make the pytest output readable: test_date_validator[valid_date] instead of test_date_validator[value0-True].

๐ŸŽญ Mocking โ€” Isolate External Dependencies

Test logic without hitting the network, disk, or clock

A mock replaces a real dependency with a controllable stand-in. Use it when the real thing is slow, unreliable, expensive, or has side effects you don't want in a test โ€” HTTP calls, database writes, email sending, time.

test_mocking.py
from unittest.mock import patch
import requests

def fetch_user(user_id):
    response = requests.get(f"https://api.example.com/users/{user_id}")
    response.raise_for_status()
    return response.json()

@patch("requests.get")
def test_fetch_user_success(mock_get):
    mock_get.return_value.json.return_value = {"id": 1, "name": "Ana"}
    mock_get.return_value.raise_for_status.return_value = None

    user = fetch_user(1)

    assert user["name"] == "Ana"
    mock_get.assert_called_once_with("https://api.example.com/users/1")
Patch where a name is looked up, not where it is defined. In the example above, requests.get is patched because that's the module the function calls through. If the function had done from requests import get, you'd patch test_mocking.get instead.

Common mock patterns

GoalCode
Return a fixed valuemock.return_value = 42
Raise an exceptionmock.side_effect = ValueError
Return different values per callmock.side_effect = [1, 2, 3]
Verify it was calledmock.assert_called_once()
Verify call argumentsmock.assert_called_with(1, 2)
Patch an attributepatch.object(obj, "method")

Patching time for determinism

from unittest.mock import patch
from datetime import datetime, timezone

def is_weekend():
    return datetime.now(timezone.utc).weekday() >= 5

@patch("test_mocking.datetime")
def test_is_weekend_saturday(mock_dt):
    mock_dt.now.return_value = datetime(2024, 3, 16, tzinfo=timezone.utc)  # Saturday
    assert is_weekend() is True

Tests that depend on the real clock are flaky by definition. Patch datetime or inject a clock object so the test always sees the same date.

Mock at the boundary. Ideally you mock only external systems (HTTP, databases, filesystems). Mocking your own internal functions makes tests brittle โ€” refactoring internal code then breaks tests that shouldn't care. Prefer dependency injection over deep mocking when you can.

๐Ÿ“Š Coverage โ€” What Did the Tests Miss?

Measure which lines ran, and read the number honestly

Coverage measures how much of your code executed during the test run. It's a useful signal, not a goal in itself. 100% coverage with weak assertions is worse than 70% coverage with meaningful tests.

terminal โ€” coverage
# Install the pytest coverage plugin
python -m pip install pytest-cov

# Run tests with a coverage report
pytest --cov=my_app

# Show which lines are missing
pytest --cov=my_app --cov-report=term-missing

# Generate an HTML report
pytest --cov=my_app --cov-report=html

# Fail the build if coverage drops below 80%
pytest --cov=my_app --cov-fail-under=80

Reading a coverage report

$ pytest --cov=my_app --cov-report=term-missing

---------- coverage: platform linux, python 3.12.2 -----------
Name              Stmts   Miss  Cover   Missing
-----------------------------------------------
my_app/__init__.py     0      0   100%
my_app/calc.py        18      2    89%   24-25
my_app/utils.py        7      0   100%
-----------------------------------------------
TOTAL                 25      2    92%

The Missing column lists the exact lines that never executed. Open the file at those lines and ask whether a test should cover them. Sometimes the honest answer is no โ€” defensive error handling that's hard to trigger, for example.

CoverageTypical interpretationAction
< 50%Large gapsPrioritise tests for core logic
50โ€“75%Reasonable startAdd tests for error paths
75โ€“90%SolidFocus on edge cases
90%+StrongAudit assertion quality
Coverage tells you what ran, not what was checked. A test that calls a function without asserting anything still counts as covered. High coverage is necessary but not sufficient โ€” read the tests too.

Branch coverage

# Line coverage misses untested branches inside conditionals
pytest --cov=my_app --cov-branch

# A function with if/else has two branches. Line coverage counts
# it as covered even if only the "if" side ran. Branch coverage
# requires both sides.

For any code with conditionals, branch coverage is a more honest metric than line coverage. It's worth enabling by default.

๐Ÿ” Test-Driven Development

Write the test first, then the code

TDD is a short loop: red, green, refactor. Write a failing test, make it pass with the simplest code, then improve the code while keeping the test green. The discipline forces you to think about the interface before the implementation.

tdd_workflow.py
# STEP 1 โ€” RED: write a failing test
def test_fizzbuzz_returns_number():
    assert fizzbuzz(1) == "1"
    assert fizzbuzz(2) == "2"

# STEP 2 โ€” GREEN: minimal implementation
def fizzbuzz(n):
    return str(n)

# STEP 3 โ€” REFACTOR: add the next failing test
def test_fizzbuzz_multiple_of_three():
    assert fizzbuzz(3) == "Fizz"

# Repeat: RED, GREEN, REFACTOR until done
TDD is a design tool, not a religion. The real benefit is that writing the test first forces you to use your own API before you build it โ€” which exposes awkward interfaces early. You don't have to apply it to every line of code, but it's especially effective for library and API design.

When TDD pays off

  • Building a library or API that others will call
  • Implementing business logic with clear rules
  • Fixing a bug โ€” write a test that reproduces it first
  • Working on code with tricky edge cases (parsers, formatters)

When TDD is less useful

  • Exploratory code where the interface isn't known yet
  • Pure UI or visual work with no clear assertion
  • Prototyping where speed matters more than robustness

Bug-fix workflow

# A user reports: divide(1, 0) crashes with ZeroDivisionError

# 1. Write a test that reproduces the bug (it will fail)
def test_divide_by_zero_raises_value_error():
    import pytest
    with pytest.raises(ValueError):
        divide(1, 0)

# 2. Fix the code until the test passes
def divide(a, b):
    if b == 0:
        raise ValueError("cannot divide by zero")
    return a / b

# 3. The test now guards against the bug returning

๐Ÿ—๏ธ Mini Project โ€” A Bank Account

Put everything together in one worked example

This small class models a bank account with deposit, withdraw, and balance tracking. The test suite below exercises it with fixtures, parametrisation, and exception checks.

account.py
class Account:
    def __init__(self, balance=0):
        if balance < 0:
            raise ValueError("balance cannot be negative")
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self.balance += amount
        return self.balance

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("withdrawal must be positive")
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount
        return self.balance
test_account.py
import pytest
from account import Account

@pytest.fixture
def account():
    return Account(balance=100)

def test_initial_balance(account):
    assert account.balance == 100

def test_negative_initial_balance_raises():
    with pytest.raises(ValueError):
        Account(balance=-1)

@pytest.mark.parametrize("amount, expected", [
    (50, 150),
    (100, 200),
    (1, 101),
])
def test_deposit_increases_balance(account, amount, expected):
    assert account.deposit(amount) == expected

def test_deposit_zero_raises(account):
    with pytest.raises(ValueError):
        account.deposit(0)

@pytest.mark.parametrize("amount, expected", [
    (30, 70),
    (100, 0),
    (1, 99),
])
def test_withdraw_decreases_balance(account, amount, expected):
    assert account.withdraw(amount) == expected

def test_withdraw_insufficient_funds_raises(account):
    with pytest.raises(ValueError, match="insufficient"):
        account.withdraw(150)

def test_withdraw_negative_raises(account):
    with pytest.raises(ValueError):
        account.withdraw(-10)
$ pytest -v test_account.py
test_account.py::test_initial_balance PASSED
test_account.py::test_negative_initial_balance_raises PASSED
test_account.py::test_deposit_increases_balance[50-150] PASSED
test_account.py::test_deposit_increases_balance[100-200] PASSED
test_account.py::test_deposit_increases_balance[1-101] PASSED
test_account.py::test_deposit_zero_raises PASSED
test_account.py::test_withdraw_decreases_balance[30-70] PASSED
test_account.py::test_withdraw_decreases_balance[100-0] PASSED
test_account.py::test_withdraw_decreases_balance[1-99] PASSED
test_account.py::test_withdraw_insufficient_funds_raises PASSED
test_account.py::test_withdraw_negative_raises PASSED
======================== 11 passed in 0.02s ========================
Notice what's not here. No mocking, no database, no network โ€” because the class has no external dependencies. That's the ideal shape for unit tests: pure logic with clear inputs and outputs. Mocking is a tool for when that's impossible, not a default.

โ“ Frequently Asked Questions

Common questions about pytest and testing

Use pytest. It requires less boilerplate, uses plain assert, has better failure output, and its fixture system is more flexible than unittest's setUp/tearDown. pytest can also run existing unittest tests, so you can migrate gradually.

The two common layouts are: tests alongside the code in each package, or all tests in a top-level tests/ directory. The tests/ directory is the most common for applications; colocating tests with modules works well for libraries. Either way, name files test_*.py so pytest finds them.

Use pytest --lf (last-failed) to rerun just the failures from the previous run. pytest --ff (failed-first) runs failures first, then the rest. These are huge time-savers on large suites.

A fixture participates in pytest's setup/teardown lifecycle and can be injected into tests by name. A helper function is just a regular function you call. Use fixtures when you need setup that should run before each test (and cleanup after); use helpers for pure utility code that doesn't need lifecycle management.

There's no universal number. 80% is a common floor for application code, but the useful question is whether the untested lines are ones you'd want a safety net for. Core business logic should be near 100%; generated code, defensive branches, and trivial getters can be lower. Chasing 100% often produces tests that exist only to satisfy the metric.

Install pytest-asyncio and mark async tests with @pytest.mark.asyncio. The plugin provides an event loop for each test. Alternatively, use anyio for a framework-agnostic approach. Never call asyncio.run inside a test โ€” let the plugin manage the loop.

Rarely. Mock at the boundary โ€” external services, the filesystem, the clock. Mocking your own functions makes tests brittle because refactoring internal code breaks tests that shouldn't care. If a function is hard to test without mocking, that's often a signal to refactor it into a purer, more testable form.

Install dependencies from your lockfile, then run pytest --cov=my_app --cov-fail-under=80. Use -x to stop at the first failure if you want fast feedback, or let it run all tests to see the full picture. Most CI systems (GitHub Actions, GitLab CI) have ready-made Python setups that make this a few lines of config.