pytest-xdist

3.8.0 · active · verified Sat Mar 28

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.

Warnings

Install

Imports

Quickstart

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}")

view raw JSON →