pytest is an open-source testing framework for Python that discovers and runs test functions written with the plain assert statement, and enriches them with fixtures, parametrization and plugins. In software testing within programming, it is the de facto standard runner for Python unit tests and integration tests, and it also executes tests written for the standard library module unittest.
Its design favors minimal boilerplate: a test is an ordinary function whose name starts with test_, and pytest rewrites assertions so that a failure reports the actual compared values without special assertion methods. This combination makes small tests quick to write and large test suites manageable.
How pytest discovers and runs tests
pytest works in three phases: collection, execution and reporting. During collection it walks the configured directories, imports files that match test_*.py or *_test.py, and gathers functions prefixed with test_ and classes prefixed with Test that have no __init__ method.
Before importing test modules, pytest applies assertion rewriting, an import hook that transforms each assert into code that records intermediate values. When assert result == expected fails, the report shows both values and, for lists, dictionaries or strings, a detailed difference.
Each test ends with one of several outcomes, and the summary line reports how many tests fell into each category.
| Outcome | Meaning | Typical cause |
|---|---|---|
| Passed | Test body completed without error | Behavior matches expectations |
| Failed | An assertion or exception occurred in the test | Regression or incorrect expectation |
| Error | A fixture failed during setup or teardown | Broken environment or fixture code |
| Skipped | Test was deliberately not run | Platform or dependency condition |
| Xfail | Test failed as expected | Known bug marked with xfail |
| Xpass | Test marked xfail passed unexpectedly | Bug fixed or marker outdated |
Fixtures, parametrization and markers
Fixtures are the core mechanism of pytest for preparing test preconditions. A fixture is a function decorated with @pytest.fixture; a test requests it simply by naming it as a parameter, and pytest performs dependency injection at run time. Code after a yield statement inside the fixture runs as teardown.
The fixture scope controls how often a fixture is created and therefore balances isolation against speed.
| Scope | Created once per | Good fit | Risk |
|---|---|---|---|
| function | Test function (default) | Mutable objects, temporary data | Slower for expensive setup |
| class | Test class | Grouped tests sharing state | Order dependence inside the class |
| module | Test file | Database schema, loaded models | State leaks between tests in a file |
| package | Test package | Shared services for a subsystem | Harder to reason about lifetime |
| session | Entire test run | Containers, compiled assets | Hidden coupling across the suite |
Fixtures placed in a conftest.py file become available to every test in that directory and below, without imports. Built-in fixtures cover common needs: tmp_path for temporary directories, monkeypatch for patching attributes and environment variables, and capsys for capturing standard output.
Parametrization with @pytest.mark.parametrize runs one test function against many input sets, each reported as a separate test with its own identifier. Markers such as skip, skipif and xfail, or custom markers like slow, label tests so that the -m option can select or exclude them.
pytest compared with other test runners
pytest differs from xUnit-style frameworks mainly in how it handles setup and assertions. The following table compares it with the standard library and with JUnit, the reference framework of the xUnit family.
| Aspect | pytest | Standard unittest | JUnit |
|---|---|---|---|
| Language | Python | Python (standard library) | Java and JVM languages |
| Test form | Plain functions or classes | Subclasses of TestCase | Annotated methods |
| Assertions | Plain assert with rewriting | assertEqual and related methods | Assertion library calls |
| Setup model | Injected fixtures with scopes | setUp and tearDown methods | Lifecycle annotations |
| Parametrization | Built-in decorator | Manual loops or subTest | Parameterized test extension |
| Extensibility | Hook-based plugins | Limited | Extension model |
Because pytest can run existing unittest suites unchanged, teams typically migrate gradually: new tests use fixtures and plain asserts, while legacy TestCase classes keep working.
Plugins and configuration
pytest exposes hook functions at every stage of collection and execution, and plugins implement those hooks. More than a thousand community plugins exist, and several are standard in professional projects.
- pytest-cov measures test coverage through the coverage library and can fail the run below a threshold.
- pytest-xdist distributes tests across CPU cores or machines with the
-noption. - pytest-mock provides a
mockerfixture around the standard mocking library with automatic cleanup. - pytest-asyncio runs coroutine tests inside an event loop.
- Hypothesis integrates property-based testing, generating many inputs from declared strategies.
Configuration lives in pyproject.toml, pytest.ini or tox.ini. Common settings include testpaths, registered markers, default options in addopts and `–strict-markers`, which turns typos in marker names into errors instead of silently creating new markers.
Common pitfalls in pytest suites
Most problems in large pytest suites come from shared state and implicit fixture behavior, not from the framework itself. The table links frequent symptoms to causes and fixes.
| Symptom | Likely cause | Fix |
|---|---|---|
| Tests pass alone but fail together | Broad fixture scope or global state | Narrow the scope or reset state |
| Flaky test under parallel runs | Shared files, ports or database rows | Use tmp_path and unique resources |
| Test silently never runs | Name lacks the test_ prefix | Rename or adjust collection settings |
| Slow suite despite small tests | Expensive function-scoped setup | Cache data in a wider-scoped fixture |
| Fixture origin unclear | Deeply nested conftest.py files | Inspect with --fixtures and simplify |
Excessive autouse fixtures, which apply to tests without being requested, deserve particular caution: they make test behavior depend on code that is not visible in the test itself.
Put simply
pytest is a tool that automatically checks Python code. A developer writes short statements such as “this function should return 5”, and pytest runs all of them and reports which ones hold and which do not.
It also prepares whatever each check needs, such as a temporary folder or sample data, much like a kitchen assistant who lays out ingredients before each recipe. The main benefit is fast, repeatable confidence that code still works after every change.
In practice
A data engineering team maintains a Python library that cleans customer records before loading them into a warehouse. The suite holds about 1,800 pytest tests: a session-scoped fixture starts a PostgreSQL container once, and function-scoped fixtures wrap each test in a transaction that is rolled back afterward.
A single parametrized test checks forty malformed phone number formats in about twenty lines of code. With pytest-xdist on eight cores, the full run drops from eleven minutes to under two minutes, and pytest-cov blocks merges when coverage falls below 85 percent. When a refactoring breaks date parsing, the rewritten assertion shows the exact mismatched values, and the developer fixes the defect within minutes.