MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Python Test Runners – pytest -n

pytest -n runs your test suite in parallel across several worker processes. The -n option is not part of pytest itself; it comes from the pytest-xdist plugin. This page explains how the example above works, fixes its install step, and covers worker counts, distribution modes, writing tests that are safe to run in parallel, and the errors you are most likely to hit.


What pytest -n actually does

When you run pytest -n 2, pytest-xdist starts two worker processes. Each worker collects the same tests, and the controller process hands tests out to them. Because they are separate processes and not threads, CPU-bound tests get real parallelism, and slow I/O-bound tests (network calls, time.sleep, database round trips) overlap instead of running one after another.

The example above shows this well. It has five parametrized tests that each sleep for one second, plus one instant test. Run serially, the suite takes about 5 seconds. With two workers, the five slow tests are split roughly 3 and 2, so the run finishes in about 3 seconds plus a little startup time.

Note: Parallelism has a cost. Starting each worker means importing your code and collecting tests again. For a small suite of fast unit tests, -n can be slower than a plain pytest run. It pays off when the suite takes tens of seconds or more.

Corrected setup for the example

The example installs only pytest and then runs pytest -n 2. That fails with pytest: error: unrecognized arguments: -n 2, because plain pytest has no -n option. Install pytest-xdist as well:

python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install pytest pytest-xdist

# Optional: lets -n auto / -n logical detect CPU cores accurately
pip install "pytest-xdist[psutil]"

pytest --version
pytest --help | grep -- '-n numprocesses'Code language: PHP (php)

Here is a cleaned-up version of the test file. The assert True, "message" lines in the original always pass, and the message is shown only when an assertion fails, so it is never printed. The version below adds a real check and records which worker ran each test, so you can see the distribution:

# tests/test_parallel.py
import os
import time

import pytest


@pytest.mark.parametrize("task_id", range(1, 6))
def test_concurrent_task(task_id):
    """Simulate a slow task (1 second each)."""
    start = time.monotonic()
    time.sleep(1)
    elapsed = time.monotonic() - start
    worker = os.environ.get("PYTEST_XDIST_WORKER", "main")
    print(f"task {task_id} ran on {worker}")
    assert elapsed >= 1, f"Task {task_id} finished too early"


def test_non_concurrent_task():
    """A fast test."""
    assert sum([1, 2, 3]) == 6Code language: PHP (php)

Running it and reading the output

# Serial baseline
pytest tests/test_parallel.py

# Two workers
pytest -n 2 tests/test_parallel.py

# Two workers, verbose, showing which worker ran each test
pytest -n 2 -v tests/test_parallel.pyCode language: PHP (php)

The output looks roughly like this (version numbers and exact timings will differ):

============================= test session starts ==============================
plugins: xdist-3.x.x
created: 2/2 workers
2 workers [6 items]

......                                                                   [100%]
============================== 6 passed in 3.4s ===============================

created: 2/2 workers confirms xdist is active. With -v, each result line is prefixed with a worker ID such as [gw0] or [gw1]. Compare the total time with the serial run, which should be a little over 5 seconds.

Note: Output from print() on workers is not streamed to your terminal, and -s does not change that under xdist. Captured output still appears in the report for failing tests. To debug a single test interactively, run without -n or with -n 0.

Choosing the number of workers

ValueBehaviour
-n 4Exactly four worker processes.
-n autoOne worker per CPU core. Uses physical cores when psutil is installed, otherwise the logical core count.
-n logicalOne worker per logical core (hyperthreads included). Needs psutil; falls back to auto without it.
-n 0Disables distribution; tests run in the main process. Handy for debugging.
--maxprocesses=NCaps the worker count, for example -n auto --maxprocesses=4 on large CI machines.

For I/O-heavy suites you can go above the core count, because workers spend most of their time waiting. For CPU-heavy suites, more workers than cores usually makes things slower.

Distribution modes with –dist

--dist controls how tests are handed to workers. When you pass -n, the default is load.

ModeHow tests are assignedUse when
loadAny pending test goes to any free workerTests are independent (the default)
loadscopeTests in the same module or class stay on one workerExpensive module- or class-scoped fixtures should be set up once
loadfileAll tests in a file stay on one workerTests in a file share state or setup
loadgroupTests with the same xdist_group mark stay on one workerOnly a few tests must not run concurrently
workstealLike load, but idle workers take queued tests from busy onesTest durations vary a lot
import pytest

# Run with: pytest -n 4 --dist loadgroup
@pytest.mark.xdist_group(name="database")
def test_create_user():
    ...

@pytest.mark.xdist_group(name="database")
def test_delete_user():
    ...Code language: PHP (php)

Writing tests that are safe to run in parallel

Most problems with -n are not xdist bugs. They are hidden dependencies between tests that serial execution happened to hide. Check for these:

  • Order dependence. A test that relies on another test running first will fail at random. Every test should create its own preconditions.
  • Shared files. Use the built-in tmp_path fixture instead of fixed paths such as /tmp/output.json.
  • Shared databases or ports. Give each worker its own resource, using the worker_id fixture or the PYTEST_XDIST_WORKER environment variable (values like gw0, gw1).
  • Session-scoped fixtures run once per worker, not once per run. With -n 4, a session fixture that seeds a database runs four times.
  • Global state such as module-level caches or monkeypatched settings is per process, so it is not shared across workers.
# conftest.py
import pytest

@pytest.fixture(scope="session")
def db_name(worker_id):
    # worker_id is "master" when xdist is not active, else "gw0", "gw1", ...
    if worker_id == "master":
        return "test_db"
    return f"test_db_{worker_id}"Code language: CSS (css)

Making it the default and using it in CI

Add the option to your pytest configuration so that developers and CI behave the same way:

# pyproject.toml
[tool.pytest.ini_options]
addopts = "-n auto --dist loadscope"
testpaths = ["tests"]Code language: PHP (php)

Add pytest-xdist to your dev or test requirements so CI installs it. To run serially for one invocation despite addopts, override it with pytest -n 0. Disabling the plugin with -p no:xdist also removes the -n option, so that only works when -n is not in addopts.

Common errors and fixes

SymptomCauseFix
error: unrecognized arguments: -npytest-xdist is not installed in the active environmentpip install pytest-xdist; check with python -m pytest --version
Different tests were collected between gw0 and gw1Test IDs are generated in a non-deterministic order (sets, random values in parametrize)Make parametrize inputs deterministic, for example sorted(...)
Tests pass serially but fail with -nShared files, databases or test-order dependenceIsolate resources per worker; use --dist loadfile or loadgroup as a stopgap
No speed-up, or slowerSuite is too small, or tests are CPU-bound with too many workersMeasure with --durations=10; reduce -n or run serially
print() output missingWorker output is capturedRun with -n 0 -s while debugging

Frequently asked questions

Is pytest -n built into pytest?

No. The -n option comes from the pytest-xdist plugin. Install it with pip install pytest-xdist; without it, pytest reports unrecognized arguments: -n.

What does pytest -n auto do?

It starts one worker per CPU core. With psutil installed it counts physical cores; otherwise it uses the logical core count reported by the OS.

Does pytest -n use threads or processes?

Processes. Each worker is a separate Python interpreter, so tests do not share memory, and CPU-bound tests are not limited by the GIL.

Why do my session-scoped fixtures run more than once with pytest -n?

Each worker is its own pytest session, so session fixtures run once per worker. Use the worker_id fixture to give each worker separate resources, or use a file lock if a step must run only once.

How do I stop certain tests from running at the same time?

Mark them with @pytest.mark.xdist_group(name="...") and run with --dist loadgroup. Tests in the same group then run one after another on a single worker.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Python Test Runners – multiprocessing-testrunner

Python tests can run in several processes at once so that a suite of slow, independent tests finishes faster on a multi-core machine. This page explains the…

Read More

Python Test Runners – gevent-testrunner

This page shows how to run Python unittest tests concurrently with gevent greenlets, so that I/O-bound tests overlap instead of running one after another. Below the original…

Read More

Python Test Runners – Pytest-asyncio

pytest-asyncio is a pytest plugin that runs async def test functions and async fixtures inside an asyncio event loop, so you can await coroutines directly in your…

Read More

Complete Guide to Pytest: From Basics to Advanced

Pytest is the most widely used Python testing framework. You write tests as plain functions that use the assert keyword, and pytest adds fixtures, parametrization, markers and…

Read More

Ensuring Quality in Front-end Development

In the fast-paced world of web development, ensuring a seamless user experience is paramount. Front-end testing and quality assurance (QA) play a crucial role in achieving this…

Read More

Comprehensive Unit Test Framework for Python

Rajesh Kumar 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…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x