Testing Workflow with pytest, Fixtures, and Coverage
Write and run Python tests with pytest, using fixtures for setup, parametrize for data-driven tests, and coverage for reporting.
Prerequisites
- -Python 3.8+ installed
- -A Python project with virtual environment
Steps
Install pytest and coverage
Install the pytest framework, coverage plugin for code coverage reports, and xdist for parallel test execution.
pytest-xdist lets you run tests in parallel with -n auto, dramatically reducing test suite times on multi-core machines.
Write and run a basic test
Run all tests in the tests/ directory with verbose output showing each test name and result. pytest auto-discovers files matching test_*.py or *_test.py.
Run tests matching a keyword
Run only tests whose names match the given keyword expression. Useful for running a subset of tests during development.
Run tests with coverage report
Run the full test suite and generate a coverage report showing which lines in the src/ directory are not covered by tests.
Add --cov-fail-under=80 to fail the test run if coverage drops below 80 percent.
Run tests in parallel
Execute tests across all available CPU cores using pytest-xdist. This can cut test runtime by 50-80 percent on large suites.
Parallel tests must be independent. Tests that share global state, databases, or files may fail or produce flaky results when parallelized.
Run only failed tests from the last run
Re-run only the tests that failed in the previous execution. This is the fastest way to iterate on fixing broken tests.
Full Script
FAQ
Discussion
Loading comments...