Sub topic 3
Controlling a Growing pytest Suite
Assume you can write Python functions, import modules, use a terminal and virtual environment, and understand exceptions. This chapter focuses on selecting tests, isolating dependencies, and keeping a suite maintainable.
Select Tests with Markers
Markers label tests so you can select or control them. Built-in markers include skip and xfail. A skipped test does not run. An expected-failure test reports success when it fails.
import pytest
@pytest.mark.skip(reason="feature is not implemented")
def test_future_feature():
assert False
@pytest.mark.xfail(reason="known bug")
def test_known_bug():
assert 1 == 2
@pytest.mark.slow
def test_large_import():
assert TrueRun selected tests with pytest -m slow, or exclude them with pytest -m "not slow". Register custom markers in pyproject.toml to avoid warnings.
Use Built-in Fixtures
Fixtures provide test resources. tmp_path gives each test a temporary directory. monkeypatch safely changes environment variables or attributes and restores them afterward. capsys captures text written to standard output.
def test_report(tmp_path, monkeypatch, capsys):
output = tmp_path / "report.txt"
monkeypatch.setenv("REPORT_MODE", "test")
print("created", output.name)
captured = capsys.readouterr()
assert "created report.txt" in captured.outReplace Dependencies with Mocks
A mock is a test double that records calls without contacting a real service.
from unittest.mock import Mock
def notify(client, address):
client.send(to=address, body="Hello")
def test_notify():
client = Mock()
notify(client, "[email protected]")
client.send.assert_called_once_with(
to="[email protected]", body="Hello"
)Configure and Measure
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra"
markers = ["slow: tests that take extra time"]Install pytest-cov, then run pytest --cov=src --cov-report=term-missing. Coverage shows which lines tests execute. It does not prove that the tests check meaningful behavior.
Organize for Maintenance
Keep production code in src/ and tests in tests/. Mirror the production module structure. Put shared fixtures in the nearest suitable conftest.py. Prefer small tests with one clear reason to fail. Avoid unnecessary mocks, shared mutable state, and tests that depend on execution order.
Exercise
Which command runs every test except tests marked slow?
Show answer
pytest -m "not slow"