pytest is Python's leading testing framework, built on plain assert statements with automatic introspection that shows exactly what failed and why. Unlike unittest's verbose class-based approach, pytest uses fixture dependency injection for clean test setup and a rich plugin ecosystem with 900+ extensions. The framework's key innovation is making the common case trivial—write def test_something(): assert result == expected—while providing advanced features like parametrization, markers, subtests, and parallel execution when complexity demands them. With pytest 9.0 (released 2025), the framework gained native subtests support, a new pytest.toml config file, and a comprehensive strict mode.
What This Cheat Sheet Covers
This topic spans 21 focused tables and 180 indexed concepts. Below is a complete table-by-table outline of this topic, spanning foundational concepts through advanced details.
Table 1: Core pytest Concepts
| Concept | Example | Description |
|---|---|---|
def test_addition(): assert 1 + 1 == 2 | • Test functions must start with test_• automatic discovery finds and executes them • no classes or inheritance required. | |
assert value == 42 | • Plain Python assert with automatic introspection—pytest rewrites assertions to show intermediate values on failure• no special methods needed. | |
test_*.py or *_test.py | Files must match these patterns for discovery—test_ prefix or _test.py suffix trigger collection. | |
class TestUserAuth: | • Optional classes group related tests—must start with Test (no __init__)• methods also need test_ prefix. |