Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 8 of 15

pytest

Testing with pytest: plain functions and assert, automatic test discovery, running and reading results, fixtures, parametrised tests, testing exceptions with pytest.raises, and useful command-line options.

Beginner 12 min read·Lesson 286 of 306 in Python Programming

Learning objectives

  • Write pytest tests with plain asserts
  • Use fixtures and parametrisation
  • Run pytest and read its output

Definition

pytest is the most popular third-party testing framework for Python. Tests are plain functions whose names start with test_, using ordinary assert statements; pytest discovers them, runs them and reports detailed failure information.

Introduction

pytest removes the boilerplate of unittest: no classes, no special assert methods — just functions and assert, with excellent failure messages.

Why it matters

Most modern Python projects use pytest. Its fixtures and parametrisation make large test suites short and readable.

Detailed explanation

Install with python -m pip install pytest. Put tests in files named test_*.py, in functions named test_*.

Use plain assert statements. When one fails, pytest shows the values involved (assert 99.9 == 90.0).

Run python -m pytest from the project folder; it discovers and runs every test. -q is quieter, -k name selects tests by name, -x stops at the first failure, -v lists each test.

A fixture is a function decorated with @pytest.fixture that provides setup to tests: any test with a parameter of the same name receives its return value.

@pytest.mark.parametrize("a,b,expected", [...]) runs one test function for many input sets, each reported separately.

with pytest.raises(ValueError): checks that code raises an exception; match= checks the message.

Fixtures such as tmp_path (a temporary folder) and capsys (captured output) are built in.

Because tests are ordinary functions, you can call them yourself — handy for understanding them, as the first example shows.

Syntax

Python
# test_pricing.py
import pytest
from pricing import final_price
@pytest.mark.parametrize("price,pct,expected", [(100, 10, 90), (80, 50, 40)])
def test_final_price(price, pct, expected):
assert final_price(price, pct) == expected
def test_rejects_negative():
with pytest.raises(ValueError):
final_price(-1, 10)
  • Plain functions and assert.
  • parametrize for many cases.
  • pytest.raises for exceptions.

Code examples

pytest-style tests are plain functions

Python
def slugify(text):
return "-".join(text.lower().split())
def test_basic():
assert slugify("Hello World") == "hello-world"
def test_extra_spaces():
assert slugify(" Learn Python ") == "learn-python"
# pytest would discover these automatically; here we call them ourselves
for name, fn in list(globals().items()):
if name.startswith("test_") and callable(fn):
fn()
print("passed", name)
Output
passed test_basic
passed test_extra_spaces

Running pytest

Terminal
python -m pip install pytest
python -m pytest # run every test
python -m pytest -q # compact output
python -m pytest -k slug # only tests whose names contain 'slug'
python -m pytest -x # stop at the first failure

More examples

Fixtures, parametrize and raises

Python
import json
import pytest
def load_settings(path):
data = json.loads(path.read_text(encoding="utf-8"))
if "theme" not in data:
raise ValueError("theme missing")
return data
@pytest.fixture
def settings_file(tmp_path):
path = tmp_path / "settings.json"
path.write_text('{"theme": "dark", "size": 14}', encoding="utf-8")
return path
def test_loads_theme(settings_file):
assert load_settings(settings_file)["theme"] == "dark"
@pytest.mark.parametrize("text", ['{}', '{"size": 12}'])
def test_missing_theme(tmp_path, text):
path = tmp_path / "bad.json"
path.write_text(text, encoding="utf-8")
with pytest.raises(ValueError, match="theme"):
load_settings(path)

Save as test_settings.py and run python -m pytest -q: pytest reports 3 passed (one fixture test plus two parametrised cases).

Step-by-step explanation

  • settings_file is a fixture: pytest creates a temporary file and passes its path to any test that asks for it.
  • tmp_path is a built-in fixture giving each test its own empty folder.
  • parametrize turns one test function into two test cases, each checking that a missing theme raises ValueError.

Expected output

This example works with files or other programs, so its exact result depends on your computer. The comments in the code describe what you should see.

Practical applications

  • Open-source projects such as requests and FastAPI use pytest.
  • CI pipelines running python -m pytest on every pull request.

Best practices

  • Use fixtures instead of repeated setup code.
  • Parametrise similar cases.
  • Keep tests next to the code in a tests/ folder.

Common mistakes

Test files pytest can't find

Avoid

checks.py with function check_price()

Prefer

test_pricing.py with function test_price()

pytest only collects files and functions with the test_ prefix by default.

Important notes

  • Plugins extend pytest: pytest-cov for coverage reports, pytest-xdist for running tests in parallel.

Key takeaways

  • pytest tests are test_* functions with plain asserts.
  • Fixtures provide setup; parametrize multiplies cases.
  • Run with python -m pytest.

Try it yourself

  1. 1
    Convert three unittest tests from the previous lesson into pytest tests.
  2. 2
    Write a parametrised test for a grade function covering every boundary.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedHow does pytest find tests by default?
Practise this topic