Skip to content
Latchkey

pytest Cheat Sheet: Selectors, Fixtures & Markers

pytest selection, fixtures, and markers in one quick reference.

Run, select, and parametrize tests with pytest.

Run & select

CommandDoes
pytestRun all tests
pytest path/test.py::test_fnRun one test
pytest -k "expr"Filter by name expression
pytest -m markerRun tests with a marker
pytest -xStop on first failure
pytest --lfRe-run last failures
pytest -q / -vQuiet / verbose
pytest -n autoParallel (pytest-xdist)

Fixtures & markers

ConstructUse
@pytest.fixtureReusable setup/teardown
scope="session"Share across the run
@pytest.mark.skipSkip a test
@pytest.mark.skipif(cond)Conditional skip
@pytest.mark.xfailExpected failure
conftest.pyShared 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →