pytest Cheat Sheet: Selectors, Fixtures & Markers
pytest selection, fixtures, and markers in one quick reference.
Run, select, and parametrize tests with pytest.
Run & select
| Command | Does |
|---|---|
| pytest | Run all tests |
| pytest path/test.py::test_fn | Run one test |
| pytest -k "expr" | Filter by name expression |
| pytest -m marker | Run tests with a marker |
| pytest -x | Stop on first failure |
| pytest --lf | Re-run last failures |
| pytest -q / -v | Quiet / verbose |
| pytest -n auto | Parallel (pytest-xdist) |
Fixtures & markers
| Construct | Use |
|---|---|
| @pytest.fixture | Reusable setup/teardown |
| scope="session" | Share across the run |
| @pytest.mark.skip | Skip a test |
| @pytest.mark.skipif(cond) | Conditional skip |
| @pytest.mark.xfail | Expected failure |
| conftest.py | Shared fixtures/config |
Parametrize & assert
test_example.py
import pytest
@pytest.mark.parametrize("n,expected", [(2, 4), (3, 9)])
def test_square(n, expected):
assert n * n == expected
def test_raises():
with pytest.raises(ValueError):
int("x")Key takeaways
- -k filters by name; -m filters by marker.
- --lf re-runs only the last failures for fast iteration.
- conftest.py holds fixtures shared across a directory tree.
Related guides
Jest Cheat Sheet: Matchers, Mocks & CLI FlagsA Jest cheat sheet - matchers, mocks, hooks, async tests, snapshots, and the CLI flags you reach for locally…
Exit Codes Cheat Sheet: Shell Status Codes ExplainedAn exit codes cheat sheet - what 0, 1, 2, 126, 127, 130, and signal-derived codes mean, and how to read $? in…
GitHub Actions Cheat Sheet: Syntax, Contexts & CommandsA GitHub Actions cheat sheet - triggers, jobs, steps, contexts, expressions, caching, matrix, and the workflo…