pytest -n (xdist): Parallel Tests Command Reference
Run the test suite in parallel across multiple CPUs.
The pytest-xdist plugin adds -n, which splits tests across worker processes. On a multi-core runner this can cut wall-clock test time substantially.
Common flags / usage
- -n auto -- use one worker per available CPU
- -n 4 -- use a fixed number of workers
- --dist loadscope -- group tests by module/class per worker
- --dist loadgroup -- keep @pytest.mark.xdist_group tests together
- requires: pip install pytest-xdist
Example
shell
- run: pip install pytest pytest-xdist
- run: python -m pytest -n auto --dist loadscope -qIn CI
Tests that share global state, files, or a database can interfere when parallelized. Isolate fixtures per worker (xdist sets PYTEST_XDIST_WORKER) or use --dist loadscope to keep related tests on one worker. On a fast managed runner with more cores, -n auto scales the speedup automatically.
Key takeaways
- pytest -n (xdist) distributes tests across worker processes.
- -n auto matches workers to available CPUs for easy scaling.
- Guard shared state, or use --dist loadscope, to keep parallel runs correct.
Related guides
pytest: Run Tests Command Reference for CIReference for pytest in CI: running the suite, useful flags, why python -m pytest fixes import errors, and a…
pytest --cov: Coverage Command Reference for CIReference for pytest --cov from pytest-cov in CI: measuring coverage, enforcing a threshold with --cov-fail-u…
pytest -x and --maxfail: Fail-Fast Command ReferenceReference for pytest fail-fast flags in CI: -x to stop on the first failure and --maxfail=N to stop after N,…