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
- Install pytest:
pip install pytest. - Write test functions in
test_*.pyfiles. - 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 -vshows verbose output;pytest -k patternfilters tests by name.pytest --fixtureslists available fixtures.- Use
tmp_pathandcaplogbuilt-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.
assertmagic in pytest requires the test module to be imported normally, not run as a standalone script.