Every developer tests their code. The difference is whether they test it once, by hand, before shipping — or whether a test suite re-tests it on every change, forever, for free. pytest is how Python developers build that suite without drowning in boilerplate: no classes required, no special assertion methods, just plain functions and plain assert.

This guide builds a small but complete test suite for a pricing module — the kind of code where a bug costs real money — and covers the four pytest features you will use daily: plain tests, parametrize, raises, and fixtures. Every test below was run before publication; the suite passes 8 out of 8.

1. Setup and Naming Rules

Install pytest into your project’s environment:

pip install pytest

pytest discovers tests by convention, so names are not decoration — they are the mechanism:

Here is the code under test, a small pricing module:

# pricing.py

def apply_discount(price, percent):
    """Return price reduced by percent (0-100), rounded to 2 decimals."""
    if percent < 0 or percent > 100:
        raise ValueError("percent must be between 0 and 100")
    return round(price * (1 - percent / 100), 2)


def cart_total(items):
    """items: list of {'price': float, 'qty': int}. Returns the cart total."""
    return round(sum(item["price"] * item["qty"] for item in items), 2)

2. Your First Tests: Plain Functions, Plain Asserts

A pytest test is just a function that asserts. If the assertion fails, the test fails — and pytest shows you the actual values involved, which is why it needs no assertEqual-style helpers:

# test_pricing.py
from pricing import apply_discount, cart_total


def test_full_price_when_no_discount():
    assert apply_discount(1000, 0) == 1000


def test_apply_discount():
    assert apply_discount(1000, 10) == 900.0

Note the test names: they read as sentences describing behaviour. Six months from now, a failing line that says test_full_price_when_no_discount tells you what broke before you open the file.

3. Parametrize: Many Cases, One Function

Discount logic lives and dies at its edges: 0%, 100%, and everything between. Instead of writing a function per case, @pytest.mark.parametrize feeds a table of inputs and expected outputs into one test:

import pytest


@pytest.mark.parametrize("price,percent,expected", [
    (200, 50, 100.0),
    (499, 100, 0.0),
    (250, 20, 200.0),
])
def test_discount_cases(price, percent, expected):
    assert apply_discount(price, percent) == expected

Each row runs as its own test case, reported separately — so three rows means three tests, and a failure names the exact row that broke.

4. Testing That Errors Happen: pytest.raises

Good code refuses bad input. apply_discount raises ValueError for a 150% discount — and that refusal deserves a test too, because “it crashes” and “it crashes correctly” are different things:

def test_invalid_discount_rejected():
    with pytest.raises(ValueError):
        apply_discount(1000, 150)

If no exception is raised, the test fails. You can also match on the exception message with pytest.raises(ValueError, match="between 0 and 100") when the message itself matters.

5. Fixtures: Shared Setup Without Copy-Paste

Several tests need the same starting data. A fixture builds it once and injects it into any test that asks for it by name:

@pytest.fixture
def sample_cart():
    return [
        {"price": 1500, "qty": 1},
        {"price": 250, "qty": 4},
    ]


def test_cart_total(sample_cart):
    assert cart_total(sample_cart) == 2500


def test_empty_cart():
    assert cart_total([]) == 0

The fixture’s name becomes the test’s parameter — that is the entire trick. Fixtures can build far more than data: database sessions, temporary files (pytest’s built-in tmp_path), or a test client for a web API, and they can clean up after themselves with yield. The empty-cart test matters as much as the happy path: edge cases are where production bugs actually live.

6. Running the Suite

With all the pieces in place, the full run looks like this — this is the real output of the suite built in this tutorial:

$ pytest -q
........                                                                 [100%]
8 passed in 0.01s

Eight dots, eight tests: two basic, three parametrized, one exception, two cart tests. Useful variations: pytest -v lists each test by name, pytest test_pricing.py runs one file, pytest -k discount runs only tests whose names contain “discount”, and pytest -x stops at the first failure. The final step is making the suite run itself: adding pytest to your CI pipeline (for example the GitHub Actions setup in our CI/CD guide) means no change merges with a red suite.

7. Habits That Make Tests Worth Having

Three habits separate suites that protect a project from suites that get deleted in frustration. One behaviour per test — a test that checks five things reports one failure and four mysteries. Test behaviour, not implementation — assert on results, not on which internal functions were called, so refactors do not break tests that should still pass. And start where bugs are expensive: pricing, permissions, payments, and data loss first; cosmetic helpers last, if ever. A suite covering the dangerous 20% of your code beats a fragile suite aiming at 100%.

Frequently Asked Questions (FAQ)

Q: pytest or unittest — which should I choose?

For new projects, pytest. It reads unittest suites fine, needs far less boilerplate, and its fixtures and parametrize are genuinely better tools. unittest remains reasonable when you cannot add dependencies.

Q: Do my tests need to live in classes?

No. Plain functions are the pytest way. Classes (class TestDiscount:) are available purely as an organisation tool when a file grows large.

Q: How many tests is enough?

Enough that the behaviours you fear breaking are covered. There is no magic number or percentage; a suite that tests pricing, auth, and data writes thoroughly is worth more than a larger suite testing trivia.

Q: Can pytest test a web API, not just functions?

Yes. Framework test clients (for example FastAPI’s TestClient) plug into fixtures, so a test can call real endpoints against a test database. Our FastAPI guide builds the kind of API you would test this way.

Conclusion

pytest’s real feature is not parametrize or fixtures — it is that writing a test takes about as long as checking the behaviour by hand, and the test keeps working after you have forgotten the details. Start with the function whose bug would cost you the most, write the eight tests, and let the suite grow with the code.

💡 Engineering Key Takeaway

Plain functions, plain asserts, named like sentences. Parametrize the edges, fixture the setup, and put the suite in CI — then let it guard every change from here on.

DI

DevInsights Editorial Team

Developer Education Publication

DevInsights is the developer-education publication of NovaSonic Global (Private) Limited, a software company based in Bahawalpur, Pakistan. Every tutorial is written and reviewed by working engineers, and all code is tested before publication.