Cursor rule for pytest suites covering scoped fixtures, conftest, parametrize ids, registered markers, boundary mocking, pytest.raises(match) and coverage.
.cursor/rules/python-testing-with-pytest.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for pytest suites covering scoped fixtures, conftest, parametrize ids, registered markers, boundary mocking, pytest.raises(match) and coverage."
globs: "**/*"
alwaysApply: false
---
# Python Testing with pytest
Applies to: test code under `tests/` that runs with pytest, including shared fixtures in `conftest.py`.
Version baseline: checked against the pytest stable documentation (pytest 8+/9). Read `[tool.pytest.ini_options]` (or `pytest.ini`) and the installed plugins (`pytest-asyncio`, `pytest-cov`, `pytest-django`, `hypothesis`) before using plugin features.
## Test layout and naming
- Put tests in `tests/`, mirroring the package (`tests/billing/test_invoices.py`). Name files `test_*.py` and functions `test_<behaviour>`, for example `test_total_includes_tax`.
- One behaviour per test, with a clear arrange / act / assert flow. Assert on observable results, not on private attributes.
## Fixtures
```python
import pytest
@pytest.fixture
def invoice_repo(tmp_path):
repo = InvoiceRepo(tmp_path / "invoices.db") # project class
yield repo
repo.close() # teardown runs even if the test fails
```
- Give fixtures the narrowest scope that works (`function` by default). Use `scope="session"` only for expensive, read-only resources. Shared mutable state between tests causes order-dependent failures.
- Put fixtures used by several modules in the nearest `conftest.py`. pytest discovers them automatically, so do not import `conftest`.
- Use the built-in fixtures: `tmp_path` for files, `monkeypatch` for environment variables and attributes, `capsys`/`caplog` for output and logs.
## Parametrize
```python
@pytest.mark.parametrize(
("amount", "rate", "expected"),
[
(100, 0.2, 120),
(0, 0.2, 0),
pytest.param(100, -1, None, marks=pytest.mark.xfail(raises=ValueError), id="negative-rate"),
],
)
def test_total_with_tax(amount, rate, expected):
assert total_with_tax(amount, rate) == expected
```
Use `ids=` or `pytest.param(..., id=...)` so failures name the case.
## Markers
- Register custom markers so typos fail instead of silently creating new markers:
```toml
[tool.pytest.ini_options]
addopts = "--strict-markers"
markers = [
"slow: long-running tests (deselect with -m 'not slow')",
"integration: needs external services",
]
```
- Select with `pytest -m "not slow"`. Use `skipif` with a reason for platform or dependency limits, and `xfail(strict=True)` for known bugs, so an unexpected pass is reported.
## Mocking external dependencies
- Unit tests make no real network, email or payment calls. Replace them at the boundary with `monkeypatch.setattr(...)` or `unittest.mock.patch("module.where.used.name")`. Patch the name where it is looked up, not where it is defined.
- Prefer small fakes (an in-memory repository) over deep mock chains. Use `autospec=True` with `mock.patch` so call signatures are checked.
## Exceptions
```python
def test_rejects_negative_rate():
with pytest.raises(ValueError, match=r"rate must be >= 0"):
total_with_tax(100, -1)
```
`match` is a regular expression searched in `str(exc)`. Escape special characters with `re.escape` when you match literal text.
## Property-based tests (optional)
If the project uses Hypothesis, add `@given(...)` tests for invariants such as round trips (`parse(format(x)) == x`) and ordering. Keep a regular example test next to each property test.
## Async tests
pytest does not run `async def` tests on its own. Use the plugin the project has: `pytest-asyncio` (`@pytest.mark.asyncio` or `asyncio_mode = "auto"`) or AnyIO's pytest plugin (`@pytest.mark.anyio`).
## Coverage
Measure coverage with `pytest-cov` (`pytest --cov=my_package --cov-report=term-missing`) and read the missing lines for the code you changed. Use the project's configured threshold, if any; do not invent one.
## Verify before finishing
- Run the changed tests, then the full suite: `pytest -q` (add `-x` while iterating and `-p no:randomly` only to debug order-dependence).
- Make each new test fail first, by breaking the code or asserting the opposite once, to prove it can fail.
- Confirm no test depends on network access, the current time (inject a clock) or run order.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
testing
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A developer asks Cursor to write or extend pytest tests for a module that talks to a database and an external payment API.
Write tests for billing/tax.py total_with_tax(amount, rate), which raises ValueError('rate must be >= 0') for negative rates, and for billing/charge.py charge(invoice), which calls payments.client.create_charge. Plugins: pytest-cov. Markers are not registered yet.Illustrative; not a recorded model run. tests/billing/test_tax.py with a parametrized test that has named ids (including a negative-rate case) and a pytest.raises(ValueError, match=...) test. tests/billing/test_charge.py patches billing.charge.create_charge (where it is used) with autospec, with a fixture in conftest.py if shared. pyproject gains --strict-markers and registered markers. The answer includes the pytest -q and pytest --cov=billing --cov-report=term-missing commands, with no invented coverage threshold.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/python-testing-with-pytest.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Python Testing with Pytest: Fixtures, Parametrize, Markers, Mocks and Coverage project conventions"
globs: "**/*"
alwaysApply: false
---
# Python Testing with pytest
Applies to: test code under `tests/` that runs with pytest, including shared fixtures in `conftest.py`.
Version baseline: checked against the pytest stable documentation (pytest 8+/9). Read `[tool.pytest.ini_options]` (or `pytest.ini`) and the installed plugins (`pytest-asyncio`, `pytest-cov`, `pytest-django`, `hypothesis`) before using plugin features.
## Test layout and naming
- Put tests in `tests/`, mirroring the package (`tests/billing/test_invoices.py`). Name files `test_*.py` and functions `test_<behaviour>`, for example `test_total_includes_tax`.
- One behaviour per test, with a clear arrange / act / assert flow. Assert on observable results, not on private attributes.
## Fixtures
```python
import pytest
@pytest.fixture
def invoice_repo(tmp_path):
repo = InvoiceRepo(tmp_path / "invoices.db") # project class
yield repo
repo.close() # teardown runs even if the test fails
```
- Give fixtures the narrowest scope that works (`function` by default). Use `scope="session"` only for expensive, read-only resources. Shared mutable state between tests causes order-dependent failures.
- Put fixtures used by several modules in the nearest `conftest.py`. pytest discovers them automatically, so do not import `conftest`.
- Use the built-in fixtures: `tmp_path` for files, `monkeypatch` for environment variables and attributes, `capsys`/`caplog` for output and logs.
## Parametrize
```python
@pytest.mark.parametrize(
("amount", "rate", "expected"),
[
(100, 0.2, 120),
(0, 0.2, 0),
pytest.param(100, -1, None, marks=pytest.mark.xfail(raises=ValueError), id="negative-rate"),
],
)
def test_total_with_tax(amount, rate, expected):
assert total_with_tax(amount, rate) == expected
```
Use `ids=` or `pytest.param(..., id=...)` so failures name the case.
## Markers
- Register custom markers so typos fail instead of silently creating new markers:
```toml
[tool.pytest.ini_options]
addopts = "--strict-markers"
markers = [
"slow: long-running tests (deselect with -m 'not slow')",
"integration: needs external services",
]
```
- Select with `pytest -m "not slow"`. Use `skipif` with a reason for platform or dependency limits, and `xfail(strict=True)` for known bugs, so an unexpected pass is reported.
## Mocking external dependencies
- Unit tests make no real network, email or payment calls. Replace them at the boundary with `monkeypatch.setattr(...)` or `unittest.mock.patch("module.where.used.name")`. Patch the name where it is looked up, not where it is defined.
- Prefer small fakes (an in-memory repository) over deep mock chains. Use `autospec=True` with `mock.patch` so call signatures are checked.
## Exceptions
```python
def test_rejects_negative_rate():
with pytest.raises(ValueError, match=r"rate must be >= 0"):
total_with_tax(100, -1)
```
`match` is a regular expression searched in `str(exc)`. Escape special characters with `re.escape` when you match literal text.
## Property-based tests (optional)
If the project uses Hypothesis, add `@given(...)` tests for invariants such as round trips (`parse(format(x)) == x`) and ordering. Keep a regular example test next to each property test.
## Async tests
pytest does not run `async def` tests on its own. Use the plugin the project has: `pytest-asyncio` (`@pytest.mark.asyncio` or `asyncio_mode = "auto"`) or AnyIO's pytest plugin (`@pytest.mark.anyio`).
## Coverage
Measure coverage with `pytest-cov` (`pytest --cov=my_package --cov-report=term-missing`) and read the missing lines for the code you changed. Use the project's configured threshold, if any; do not invent one.
## Verify before finishing
- Run the changed tests, then the full suite: `pytest -q` (add `-x` while iterating and `-p no:randomly` only to debug order-dependence).
- Make each new test fail first, by breaking the code or asserting the opposite once, to prove it can fail.
- Confirm no test depends on network access, the current time (inject a clock) or run order.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.