Testing with pytest

Topic 2 of 4 in Tools and projects7 min readBeginnerFree course

Overview

How do you know your code works? You run it and check the output. How do you know it still works after you change something? You’d have to check everything again, by hand, every time. Automated tests do that checking for you, in seconds. They’re the safety net that lets you improve code without fear, and every professional Python project has them.

pytest is the most popular testing tool for Python. Install it into your project’s environment:

Terminal
python -m pip install pytest      # or: uv add --dev pytest

Your first tests

Suppose cart.py contains:

Python
def total(items):
    """Return the total price of (price, quantity) pairs."""
    return sum(price for price, quantity in items)

Tests go in a separate file whose name starts with test_:

Python
# test_cart.py
from cart import total

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

def test_quantity():
    assert total([(10, 3)]) == 30

Run pytest in the project folder:

Testing with pytest. test_cart.py imports total from cart and defines test_empty_cart, which asserts total([]) == 0, and test_quantity, which asserts total([(10, 3)]) == 30. Running pytest shows test_cart.py .F — FAILED test_quantity: assert 10 == 30, where 10 = total([(10, 3)]) — 1 failed, 1 passed. Files are named test_.py, functions test_; tests use plain assert and pytest explains failures; a dot means pass, F fail, E error.

Text
$ pytest
...
test_cart.py .F                                         [100%]

========================== FAILURES ==========================
_______________________ test_quantity ________________________

    def test_quantity():
>       assert total([(10, 3)]) == 30
E       assert 10 == 30
E        +  where 10 = total([(10, 3)])

test_cart.py:7: AssertionError
================== short test summary info ===================
FAILED test_cart.py::test_quantity - assert 10 == 30
================ 1 failed, 1 passed in 0.02s =================

pytest found the file and both functions automatically. One dot (.) per passing test, F per failure. For the failure, it shows exactly what was compared: total([(10, 3)]) returned 10, not 30. The bug: total ignores the quantity. Fix it —

Python
return sum(price * quantity for price, quantity in items)

— rerun, and you get 2 passed. That loop — write a test, see it fail, fix, see it pass — is the heart of testing.

How pytest finds tests

  • files named test_*.py (or *_test.py), in the current folder and subfolders;
  • functions named test_* in those files (and methods in classes named Test*).

Useful options:

Terminal
pytest -v                   # verbose: one line per test
pytest -q                   # quiet
pytest test_cart.py         # one file
pytest -k quantity          # tests whose names match "quantity"
pytest -x                   # stop at the first failure
pytest --lf                 # rerun only the tests that failed last time

If pytest can’t import your module (ModuleNotFoundError), run it as python -m pytest, which adds the current folder to the import path — or add pythonpath = ["."] under [tool.pytest.ini_options] in pyproject.toml.

Plain assert

Tests are just functions that assert things. No special methods to learn:

Python
assert result == 42
assert "error" not in message
assert len(items) == 3
assert user is None
assert math.isclose(average, 0.3)      # floats: never compare exactly

pytest rewrites assert statements so that failures show the actual values — you rarely need custom messages.

Testing exceptions

Check that bad input raises the right error with pytest.raises:

Python
import pytest

def test_negative_amount_rejected():
    with pytest.raises(ValueError):
        withdraw(100, -5)

def test_message_mentions_amount():
    with pytest.raises(ValueError, match="must be positive"):
        withdraw(100, -5)

The test fails if no exception (or a different one) is raised. match checks the message with a regular expression.

Parametrize: one test, many inputs

Python
@pytest.mark.parametrize(
    "celsius, fahrenheit",
    [(0, 32), (100, 212), (-40, -40), (37, 98.6)],
)
def test_conversion(celsius, fahrenheit):
    assert math.isclose(celsius_to_fahrenheit(celsius), fahrenheit)

pytest runs the test once per pair and reports each separately — far better than a loop inside one test, which stops at the first failure.

Fixtures

Fixtures provide things tests need. pytest supplies some built in — just name them as parameters:

Python
def test_save_and_load(tmp_path):            # a fresh temporary folder
    path = tmp_path / "data.json"
    save({"a": 1}, path)
    assert load(path) == {"a": 1}

def test_greeting_output(capsys):            # captures printed output
    greet("Asha")
    assert capsys.readouterr().out == "Hello, Asha!\n"

You can write your own fixtures for shared setup:

Python
@pytest.fixture
def sample_cart():
    return [(10, 3), (2.5, 2)]

def test_total(sample_cart):
    assert total(sample_cart) == 35

What to test

For each function, think about:

  • Normal cases — typical inputs and their expected results.
  • Edge cases — empty lists, zero, one item, negative numbers, very large values, unusual text (spaces, accents, emoji).
  • Error cases — invalid input raises the right exception.

Test behaviour (what a function returns or does), not implementation details (which variables it uses inside), so you can rewrite the inside freely while the tests keep you honest.

Good tests are short, independent (they don’t rely on each other’s order) and have names that describe the expectation: test_empty_cart_total_is_zero.

Making testing a habit

  • Write a test for every bug you fix — before fixing it, so you see it fail.
  • Keep functions pure where possible (Return values and scope); they’re trivial to test.
  • Run tests often — many editors have a testing panel with a “run all” button.
  • Some developers write the test first, then the code to make it pass: test-driven development. Try it on your next small function.

Remember: test_*.py files, test_* functions, plain assert. Run pytest after every change, and let failures tell you exactly what broke.

Exercise

Test a password checker

The starter contains password_strength(pw), which returns "weak", "medium" or "strong", and raises TypeError for anything that isn’t a string. Write tests in the same file (save it as test_passwords.py) and run them with pytest -v: (1) a test that an empty string is weak; (2) a parametrized test with at least four passwords and their expected strength; (3) a test that password_strength(None) raises TypeError, using pytest.raises; (4) a test that uses the tmp_path fixture to write three passwords to a file, read them back and check that exactly one is strong. All tests should pass.

Python
# test_passwords.py
import pytest


def password_strength(pw):
    if not isinstance(pw, str):
        raise TypeError("password must be a string")
    score = 0
    score += len(pw) >= 12
    score += any(ch.isdigit() for ch in pw)
    score += any(ch.isupper() for ch in pw)
    score += any(not ch.isalnum() for ch in pw)
    if score >= 4:
        return "strong"
    if score >= 2:
        return "medium"
    return "weak"


# Your tests here

Summary

  • Install pytest in your environment; it finds files named test_*.py and runs functions named test_*.
  • Tests use plain assert; when one fails, pytest shows the values involved.
  • pytest.raises(SomeError) checks that code raises the right exception.
  • @pytest.mark.parametrize runs one test with many inputs; fixtures such as tmp_path provide ready-made resources.
  • Test behaviour, not implementation: normal cases, edge cases (empty, zero, huge) and error cases.