Python Pytest Cheat Sheet
Covers writing pytest test functions, fixtures with setup/teardown, parametrized tests, and the most useful command-line options.
1 PageIntermediateMar 28, 2026
Basic Test Functions
pytest discovers functions prefixed with test_.
python
# test_math.pydef add(a, b): return a + bdef test_add(): assert add(2, 3) == 5def test_add_raises(): import pytest with pytest.raises(TypeError): add("2", 3)# Run with: pytest# Run one file: pytest test_math.py# Run one test: pytest test_math.py::test_add# Verbose: pytest -v
Fixtures
Reusable setup/teardown for tests.
python
import pytest@pytest.fixturedef sample_data(): return {"id": 1, "name": "Alice"}def test_name(sample_data): assert sample_data["name"] == "Alice"@pytest.fixturedef db_connection(): conn = create_connection() yield conn # Provided to the test conn.close() # Teardown runs after the test@pytest.fixture(scope="session")def api_client(): return APIClient() # Created once per test session
Parametrized Tests
Run the same test body against many inputs.
python
import pytest@pytest.mark.parametrize("a,b,expected", [ (2, 3, 5), (0, 0, 0), (-1, 1, 0),])def test_add_parametrized(a, b, expected): assert add(a, b) == expected@pytest.mark.parametrize("value", [1, 2, 3])@pytest.mark.parametrize("multiplier", [10, 100])def test_stacked(value, multiplier): assert value * multiplier > 0 # Stacked marks -> 6 combinations
CLI Options & Markers
Common flags for running and filtering tests.
- pytest -k 'add'- Run only tests whose name matches a substring/expression
- pytest -m slow- Run only tests marked with @pytest.mark.slow
- pytest -x- Stop after the first failing test
- pytest --lf- Re-run only the tests that failed last time
- pytest -s- Show print() output (disable output capturing)
- pytest --cov=myapp- Report test coverage (requires the pytest-cov plugin)
- @pytest.mark.skip(reason=...)- Unconditionally skip a test
- @pytest.mark.xfail- Mark a test as expected to fail
Pro Tip
Put shared fixtures in a conftest.py file — pytest auto-discovers it without an import, making its fixtures available to every test in that directory and its subdirectories.
Was this cheat sheet helpful?
Explore Topics
#PythonPytest#PythonPytestCheatSheet#Programming#Intermediate#BasicTestFunctions#Fixtures#ParametrizedTests#CLIOptionsMarkers#Functions#Testing#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance