Registry / testing / pytest-xdist

pytest-xdist

JSON →
library3.8.0pypypi✓ verified 27d ago

The pytest-xdist plugin extends pytest with new test execution modes, primarily designed for distributing tests across multiple CPUs or hosts to significantly speed up test execution. It also offers features like running tests in a Python subprocess and formerly supported remote SSH execution and `--looponfail` mode. Currently at version 3.8.0, the library is actively maintained with regular feature updates and bug fixes.

pip install pytest-xdist
INSTALL
IMPORT
SIG · PYTEST-XDIST
P
pytest-xdist
testingpythonv3.8.0
Install
3.0s avg
Import
Disk
31MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.8.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.000s · 32.5MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 3.0s · import 0.000s · 33MB
31MB installed
● package 31MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

pytest-xdist
pytest -n auto
pytest-xdist is a pytest plugin and primarily exposes its functionality via command-line arguments to the 'pytest' executable. Direct Python imports of its core functionality by users are generally not required for standard usage.

After installation, `pytest-xdist` is typically used directly from the command line by adding the `-n` or `--numprocesses` option to your `pytest` command. The most common use is `pytest -n auto` to automatically detect and utilize all available physical CPU cores, or `pytest -n <NUM>` to specify a fixed number of worker processes. This example demonstrates how you would invoke it programmatically via `subprocess`, though direct command-line execution is the primary quickstart.

# Assuming you have pytest and pytest-xdist installed and tests in a 'tests/' directory # Create a simple test file, e.g., tests/test_example.py # import time # def test_fast(): # assert True # def test_medium(): # time.sleep(0.5) # assert True # def test_slow(): # time.sleep(1) # assert True import os import subprocess def run_pytest_xdist(num_processes): cmd = ['pytest', '-n', str(num_processes)] print(f"Running: {' '.join(cmd)}") result = subprocess.run(cmd, capture_output=True, text=True) print(result.stdout) if result.stderr: print("STDERR:", result.stderr) return result.returncode # Example usage: run tests on all available CPU cores # A real-world scenario would just be `pytest -n auto` from the command line if __name__ == '__main__': # Ensure pytest is installed for this example to run locally in a script try: import pytest except ImportError: print("pytest is not installed. Please install with 'pip install pytest'.") exit(1) print("\n--- Running tests with pytest -n auto ---") # In a real shell, you would simply type: pytest -n auto # For programmatic execution, we demonstrate the subprocess call exit_code = run_pytest_xdist('auto') if exit_code == 0: print("Tests passed successfully with -n auto.") else: print(f"Tests failed with -n auto. Exit code: {exit_code}") print("\n--- Running tests with pytest -n 2 ---") # In a real shell, you would simply type: pytest -n 2 exit_code = run_pytest_xdist(2) if exit_code == 0: print("Tests passed successfully with -n 2.") else: print(f"Tests failed with -n 2. Exit code: {exit_code}")
pytest --version
Debug
Known issues
gotchaThe `-s` or `--capture=no` option for disabling pytest's output capture does not work with `pytest-xdist`. This means you will not see real-time stdout/stderr output from workers, and debugging with tools like `PDB` is generally not supported for tests running in parallel workers.
fix
For debugging, run tests without `-n` (i.e., sequentially). For inspecting output, rely on logging or `--capture=fd` (file descriptor capture) where available and aggregated at the end of the run.
affects: All versions
gotchaTests using `pytest.mark.parametrize` with unordered iterables (e.g., `set`) can lead to inconsistent test collection order across workers, causing `pytest-xdist` to fail.
fix
Ensure parameterized values have a consistent order by converting them to lists or sorting them (e.g., `list({'a', 'b'})` or `sorted({'a', 'b'})`).
affects: All versions
deprecatedThe `--looponfail` and `--rsyncdir` command-line arguments and their corresponding configuration variables (`looponfailroots`, `rsyncdirs`) are deprecated. They are scheduled for removal in `pytest-xdist 4.0`.
fix
Migrate away from using `--looponfail` (which is already deprecated). For `--rsyncdir`, consider alternative methods for syncing code to remote environments, as modern CI/CD practices often handle this differently. The `--boxed` argument was also deprecated and removed in 3.0.0, use `pytest-forked` and `--forked` instead.
affects: 3.0.0 onwards
gotchapytest's `scope='session'` fixtures are executed once per *worker process*, not once for the entire `pytest-xdist` run across all workers. This can lead to unexpected resource setup/teardown behavior and state issues if not managed carefully.
fix
For fixtures that truly need to run once per entire test session across all workers, explicit inter-process communication or shared storage (e.g., temporary files) is required, often with a 'first worker initializes, others wait' pattern. Consider using plugins like `pytest-shared-session-scope`.
affects: All versions
breakingUsers have reported that `--exitfirst` (`-x`) (which stops the test session on the first failure) does not function as expected with `pytest-xdist` versions 3.4.0 and higher. Tests might continue running in other workers despite a failure.
fix
If strict `--exitfirst` behavior is critical for your workflow, you might need to pin `pytest-xdist` to version `3.3.1` or earlier. Alternatively, check the latest `pytest-xdist` documentation or issue tracker for updates or workarounds regarding this behavior.
affects: >=3.4.0
gotchaA test run resulted in a 'TIMEOUT'. This can be caused by various factors, including an individual test hanging indefinitely (e.g., due to an infinite loop, a deadlock, or waiting for an unresponsive external resource), or the overall test suite exceeding the configured maximum execution time in the CI environment.
fix
Investigate logs for the specific tests running at the time of the timeout to identify the hanging test or process. Consider adding more granular timeouts at the test or fixture level (e.g., using `pytest-timeout`) if a specific test is the culprit. Review system resource utilization during the test run if the entire environment becomes unresponsive. Ensure external services or resources accessed by tests are stable and responsive.
affects: All versions
Upgrade
Version history
3.8.0latest on PyPI · released Jul 1, 2025
Audit
Dependencies
pytestrequiredpytest-xdist is a plugin for pytest and requires it to function.
psutiloptionalOptional dependency to accurately detect the number of logical CPU cores for the '-n logical' option.
Agent activity
13 hits · last 30 days
node
10
Resources
pytest-xdist — pip install pytest-xdist · libregistry