| name | testing |
| description | Python test-writing best practices covering test structure, fixtures, parametrization, and mocking with pytest. Use when writing, reviewing, or refactoring tests, adding test coverage, or working in tests directories and conftest.py. |
| paths | ["tests/**","**/test_*.py","**/*_test.py","**/conftest.py"] |
Python Testing
A collection of test-writing best practices for pytest. Designed for AI agents and LLMs to write readable, maintainable, and trustworthy tests.
Categories
Mocking [CRITICAL]
Mock external boundaries only, and keep mocks faithful to real interfaces.
Test Structure [HIGH]
Structure tests so failures are easy to diagnose.
Fixtures [HIGH]
Share setup without hiding it.
Parametrization [MEDIUM]
Eliminate duplicated tests without hiding cases.
Quick Reference
Structure Patterns
def test_expired_token_is_rejected() -> None:
token = make_token(expires_at=YESTERDAY)
result = validate(token)
assert result.valid is False
Fixture Patterns
@pytest.fixture
def user() -> User:
return User(name="alice", email="alice@example.com")
@pytest.fixture
def make_user() -> Callable[..., User]:
def _make(name: str = "alice", active: bool = True) -> User:
return User(name=name, email=f"{name}@example.com", active=active)
return _make
Parametrize Patterns
@pytest.mark.parametrize(
("email", "valid"),
[
pytest.param("a@example.com", True, id="simple-address"),
pytest.param("a@sub.example.com", True, id="subdomain"),
pytest.param("no-at-sign", False, id="missing-at"),
pytest.param("", False, id="empty-string"),
],
)
def test_email_validation(email: str, valid: bool) -> None:
assert is_valid_email(email) is valid
Mocking Patterns
def test_notifies_on_signup(mocker: MockerFixture) -> None:
send = mocker.patch("app.signup.email_client.send", autospec=True)
signup(email="alice@example.com")
send.assert_called_once_with(to="alice@example.com", template="welcome")
def test_reads_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("API_KEY", "test-key")
assert load_config().api_key == "test-key"
See Also