How do I write and run tests with pytest?

· Category: Python Programming

Short answer

pytest is a powerful testing framework that uses plain assert statements, automatic test discovery, and a rich plugin ecosystem. Tests are functions prefixed with test_ in files named test_*.py.

Steps

  1. Install pytest: pip install pytest.
  2. Write test functions in test_*.py files.
  3. Run tests with pytest.
# test_math.py
def add(x, y):
    return x + y

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

def test_add_negative():
    assert add(-1, 1) == 0

# Parametrize
import pytest

@pytest.mark.parametrize("a,b,expected", [
    (2, 3, 5),
    (-1, 1, 0),
    (0, 0, 0),
])
def test_add_parametrized(a, b, expected):
    assert add(a, b) == expected

Tips

  • Use fixtures to set up and tear down test dependencies.
  • pytest -v shows verbose output; pytest -k pattern filters tests by name.
  • pytest --fixtures lists available fixtures.
  • Use tmp_path and caplog built-in fixtures for file and logging tests.
@pytest.fixture
def sample_data():
    return {"name": "Alice", "age": 30}

def test_name(sample_data):
    assert sample_data["name"] == "Alice"

Common issues

  • Naming a test file without the test_ prefix causes pytest to skip it.
  • Side effects from one test (like mutating a global) can leak into others; use fixtures to isolate state.
  • assert magic in pytest requires the test module to be imported normally, not run as a standalone script.