Test Python code with pytest
8 steps · about 3 h 50 min · Intermediate
- Write and run the first test (tutorial, pytest documentation, 25 min)
One small assertion establishes discovery, execution and failure output.
- Make failures explain the mismatch (guide, pytest documentation, 25 min)
Useful assertions shorten the path from a failing test to the broken behaviour.
- Choose a maintainable test layout (guide, pytest documentation, 30 min)
Import mode, package layout and naming decisions prevent fragile discovery problems.
- Set up repeatable test context with fixtures (guide, pytest documentation, 35 min)
Fixtures make dependencies explicit and remove duplicated setup.
- Test several cases with parametrization (guide, pytest documentation, 30 min)
A compact table of cases exposes boundaries without copying the test body.
- Control external state with monkeypatch (guide, pytest documentation, 35 min)
Replacing environment, paths or calls keeps a unit test deterministic and local.
- Verify command output deliberately (guide, pytest documentation, 25 min)
Captured streams let command-line behaviour be checked without manual inspection.
- Read and control failure behaviour (guide, pytest documentation, 25 min)
Traceback and stop options help isolate the first useful signal in a larger suite.