pytest-xdist is a pytest plugin that splits a test suite across several worker processes so the tests run in parallel, and the -n option sets how many workers it starts. This page runs the example above, explains its output and the distribution modes, and covers the problems that come up when a suite goes parallel: shared state, session fixtures and test collection that differs between workers.
Below is a sample code demonstrating how Pytest-xdist can be used to run tests concurrently on multiple CPU cores, which can significantly reduce test execution time for large test suites.
To run the tests in parallel using Pytest-xdist, you can specify the number of CPUs to use with the -n option. For example, to run tests on 2 CPUs in parallel, you can run:
Pytest-xdist will execute the test cases concurrently, utilizing the available CPU cores efficiently.
How pytest-xdist runs tests
When you pass -n, pytest becomes a controller. It starts that many worker processes, named gw0, gw1 and so on. Every worker collects the whole test suite on its own. The controller then hands out test IDs, and each worker reports its results back. Each worker is a separate Python process, so tests run in parallel even when the code is CPU-bound. The Global Interpreter Lock does not limit this the way it limits threads.
There is a trade-off. Starting workers and collecting tests in each one costs time. A suite that already finishes in a second or two can get slower with xdist. The plugin helps most with large suites, or with tests that wait on I/O, sleep, or do heavy computation.
Running the example step by step
- Create and activate a virtual environment:
python -m venv .venv && source .venv/bin/activate. - Install the packages:
pip install pytest pytest-xdist. - Save the gist code as
tests/test_parallel_execution.py. It must be a.pyfile whose name starts withtest_, or pytest will not collect it. - Run it serially first so you have a baseline:
pytest. The three tests sleep for 1 second each, so this takes about 3 seconds. - Run it with two workers:
pytest -n 2. - Run it with one worker per test:
pytest -n 3. This takes about 1 second plus worker startup time.
$ pytest -n 2
============================= test session starts ==============================
platform linux -- Python 3.x, pytest-8.x, pluggy-1.x
rootdir: /home/user/project
plugins: xdist-3.x
created: 2/2 workers
2 workers [3 items]
... [100%]
============================== 3 passed in 2.4s ================================Code language: JavaScript (javascript)
The lines created: 2/2 workers and 2 workers [3 items] show that xdist is active. With 2 workers and 3 one-second tests, one worker has to run two tests. The best possible time is therefore about 2 seconds, not 1. Exact timings depend on your machine. Add -v to see which worker ran each test, for example [gw1] PASSED tests/test_parallel_execution.py::test_task_2.
Corrections to the original example
- The text says "you can run:" but no command follows it. The command is
pytest -n 2. It appears only as a comment at the end of the gist. -nsets the number of worker processes, not CPUs. You can start more workers than you have cores, and xdist does not pin workers to cores. Use-n autoto match the CPU count.- The gist file is named
gistfile1.txt. Save it astests/test_parallel_execution.py, or pytest will not discover it. assert True, "Task 1 completed successfully."can never fail. The message after the comma is printed only when an assertion fails, so it is not a success message. In real tests, assert on an actual result, for exampleassert result == expected.import pytestis not used in the example. It does no harm, but you only need it once you use fixtures or markers.
Choosing the number of workers
| Option | What it does |
|---|---|
-n 4 | Starts exactly 4 workers. |
-n auto | Starts one worker per CPU. If psutil is installed, it counts physical cores. |
-n logical | Starts one worker per logical CPU, which includes hyper-threads. Needs psutil for an accurate count. |
-n 0 | Turns off distribution. Tests run in the main process. |
-p no:xdist | Turns off the plugin entirely, for example when debugging. |
Note: In containers and CI runners, -n auto can detect more CPUs than the job is allowed to use, which leads to CPU contention. Set an explicit number such as -n 4, or set the PYTEST_XDIST_AUTO_NUM_WORKERS environment variable to cap auto.
To make parallel runs the default, add the option to your configuration. You can still override it with -n 0 on the command line.
# pytest.ini
[pytest]
addopts = -n auto
testpaths = testsCode language: PHP (php)
Distribution modes with –dist
The --dist option controls how tests are grouped and sent to workers. The default when -n is set is load.
| Mode | Behaviour | Use when |
|---|---|---|
load | Sends pending tests to whichever worker is free. | Tests are independent. This is the default. |
loadscope | Keeps tests from the same module, or the same class for methods, on one worker. | Module- or class-scoped fixtures are expensive to build. |
loadfile | Keeps all tests from the same file on one worker. | Tests in one file share state or setup. |
loadgroup | Keeps tests with the same xdist_group mark on one worker. | Only some tests must not run at the same time. |
worksteal | Splits tests evenly, then lets idle workers take work from busy ones. | Test durations vary a lot. |
import pytest
@pytest.mark.xdist_group(name="database")
def test_create_user():
...
@pytest.mark.xdist_group(name="database")
def test_delete_user():
...
# Run with: pytest -n 4 --dist loadgroupCode language: CSS (css)
Shared state and session fixtures
Tests that pass serially and fail under xdist almost always share something: a file path, a database, a port or a global variable. Each worker is its own process, so a scope="session" fixture runs once per worker, not once for the whole run. Use the worker_id fixture to give each worker its own resources. It returns gw0, gw1 and so on, or master when xdist is not distributing tests.
import pytest
@pytest.fixture(scope="session")
def db_name(worker_id):
# Each worker gets its own database: test_db_gw0, test_db_gw1, ...
return f"test_db_{worker_id}"Code language: PHP (php)
Sometimes expensive setup really must happen only once across all workers, such as building test data. Use a file lock in the shared temporary directory. This pattern needs pip install filelock.
import json
import pytest
from filelock import FileLock
def produce_expensive_data():
return {"users": ["alice", "bob"]}
@pytest.fixture(scope="session")
def session_data(tmp_path_factory, worker_id):
if worker_id == "master":
# Not running under xdist
return produce_expensive_data()
# Directory shared by all workers in this run
root_tmp_dir = tmp_path_factory.getbasetemp().parent
fn = root_tmp_dir / "data.json"
with FileLock(str(fn) + ".lock"):
if fn.is_file():
data = json.loads(fn.read_text())
else:
data = produce_expensive_data()
fn.write_text(json.dumps(data))
return dataCode language: PHP (php)
Code outside fixtures can read the environment variables PYTEST_XDIST_WORKER and PYTEST_XDIST_WORKER_COUNT for the same information.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
error: unrecognized arguments: -n | pytest-xdist is not installed in the active environment. | Run pip install pytest-xdist in the same virtual environment as pytest. |
Different tests were collected between gw0 and gw1 | Collection is not deterministic, for example parameters built from random, from sets, or from the current time. | Generate parameters in a fixed order, or seed the randomness so every worker collects the same list. |
Tests fail randomly only with -n | Tests share files, ports, databases or globals. | Use tmp_path, give each worker its own resources via worker_id, or group the tests with --dist loadgroup. |
print() output does not appear with -s | Worker output is not passed through to the terminal. | Use -n 0 while debugging, or use logging with --log-cli-level. |
| Parallel run is slower than serial | Worker startup costs more than the time saved, or there are too many workers for the CPUs. | Use fewer workers, or keep xdist for large suites only. |
Best practices
- Make every test independent and order-agnostic before you turn on xdist. Running the suite in random order with a plugin such as pytest-randomly helps find hidden dependencies.
- Use the built-in
tmp_pathfixture instead of fixed file paths. It is unique per test, so workers cannot collide. - Measure the effect: compare
pytest --durations=10againstpytest -n auto --durations=10. - pytest-cov supports xdist.
pytest -n auto --cov=myappcombines coverage from all workers. - Stopping options such as
-xand--maxfailwork, but other workers may finish the tests they already started before the run stops.
Frequently asked questions
How do I run pytest tests in parallel?
Install the plugin with pip install pytest-xdist, then run pytest -n auto to start one worker per CPU, or pytest -n 4 for a fixed number of workers.
Does pytest-xdist use threads or processes?
Processes. Each worker is a separate Python process that collects the suite on its own, so the GIL does not stop tests from running in parallel. The downside is that workers do not share memory.
Why does my session-scoped fixture run more than once with pytest-xdist?
Session scope applies to each worker process, so the fixture runs once per worker. If the work must happen only once in total, cache the result in a file in the shared temp directory and guard it with a FileLock.
How do I make some tests run on the same worker?
Mark them with @pytest.mark.xdist_group(name="...") and run with --dist loadgroup. You can also use --dist loadfile or --dist loadscope to keep a whole file, module or class together.
How do I temporarily disable pytest-xdist?
Pass -n 0 to run in a single process, or -p no:xdist to skip loading the plugin. Both override an -n set in addopts.
Related tutorials
- More Python tutorials
- TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-
- What is Django and use cases of Django?
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals