Skip to content
Latchkey

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 -q

In 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →