{"id":41519,"date":"2026-11-25T22:08:18","date_gmt":"2026-11-25T22:08:18","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=41519"},"modified":"2026-11-25T22:08:18","modified_gmt":"2026-11-25T22:08:18","slug":"python-test-runners-pytest-n","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/python-test-runners-pytest-n\/","title":{"rendered":"Python Test Runners &#8211; pytest -n"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><code>pytest -n<\/code> runs your test suite in parallel across several worker processes. The <code>-n<\/code> option is not part of pytest itself; it comes from the <strong>pytest-xdist<\/strong> 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.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/f0471da2b38fe844a7bf13bdbc0c34ac.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What pytest -n actually does<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">When you run <code>pytest -n 2<\/code>, 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, <code>time.sleep<\/code>, database round trips) overlap instead of running one after another.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Parallelism has a cost. Starting each worker means importing your code and collecting tests again. For a small suite of fast unit tests, <code>-n<\/code> can be slower than a plain <code>pytest<\/code> run. It pays off when the suite takes tens of seconds or more.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Corrected setup for the example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The example installs only <code>pytest<\/code> and then runs <code>pytest -n 2<\/code>. That fails with <code>pytest: error: unrecognized arguments: -n 2<\/code>, because plain pytest has no <code>-n<\/code> option. Install pytest-xdist as well:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">python -m venv .venv\nsource .venv\/bin\/activate        <span class=\"hljs-comment\"># Windows: .venv\\Scripts\\activate<\/span>\npip install pytest pytest-xdist\n\n<span class=\"hljs-comment\"># Optional: lets -n auto \/ -n logical detect CPU cores accurately<\/span>\npip install <span class=\"hljs-string\">\"pytest-xdist&#91;psutil]\"<\/span>\n\npytest --version\npytest --help | grep -- <span class=\"hljs-string\">'-n numprocesses'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Here is a cleaned-up version of the test file. The <code>assert True, &quot;message&quot;<\/code> 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:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># tests\/test_parallel.py<\/span>\nimport os\nimport time\n\nimport pytest\n\n\n@pytest.mark.parametrize(<span class=\"hljs-string\">\"task_id\"<\/span>, range(<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">6<\/span>))\ndef test_concurrent_task(task_id):\n    <span class=\"hljs-string\">\"\"<\/span><span class=\"hljs-string\">\"Simulate a slow task (1 second each).\"<\/span><span class=\"hljs-string\">\"\"<\/span>\n    start = time.monotonic()\n    time.sleep(<span class=\"hljs-number\">1<\/span>)\n    elapsed = time.monotonic() - start\n    worker = os.environ.get(<span class=\"hljs-string\">\"PYTEST_XDIST_WORKER\"<\/span>, <span class=\"hljs-string\">\"main\"<\/span>)\n    <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"task {task_id} ran on {worker}\"<\/span>)\n    assert elapsed &gt;= <span class=\"hljs-number\">1<\/span>, f<span class=\"hljs-string\">\"Task {task_id} finished too early\"<\/span>\n\n\ndef test_non_concurrent_task():\n    <span class=\"hljs-string\">\"\"<\/span><span class=\"hljs-string\">\"A fast test.\"<\/span><span class=\"hljs-string\">\"\"<\/span>\n    assert sum(&#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">3<\/span>]) == <span class=\"hljs-number\">6<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Running it and reading the output<\/h2>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># Serial baseline<\/span>\npytest tests\/test_parallel.py\n\n<span class=\"hljs-comment\"># Two workers<\/span>\npytest -n <span class=\"hljs-number\">2<\/span> tests\/test_parallel.py\n\n<span class=\"hljs-comment\"># Two workers, verbose, showing which worker ran each test<\/span>\npytest -n <span class=\"hljs-number\">2<\/span> -v tests\/test_parallel.py<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The output looks roughly like this (version numbers and exact timings will differ):<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">============================= test session starts ==============================\nplugins: xdist-3.x.x\ncreated: 2\/2 workers\n2 workers &#91;6 items]\n\n......                                                                   &#91;100%]\n============================== 6 passed in 3.4s ===============================<\/code><\/span><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><code>created: 2\/2 workers<\/code> confirms xdist is active. With <code>-v<\/code>, each result line is prefixed with a worker ID such as <code>[gw0]<\/code> or <code>[gw1]<\/code>. Compare the total time with the serial run, which should be a little over 5 seconds.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Output from <code>print()<\/code> on workers is not streamed to your terminal, and <code>-s<\/code> does not change that under xdist. Captured output still appears in the report for failing tests. To debug a single test interactively, run without <code>-n<\/code> or with <code>-n 0<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Choosing the number of workers<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Value<\/th><th>Behaviour<\/th><\/tr><\/thead><tbody><tr><td><code>-n 4<\/code><\/td><td>Exactly four worker processes.<\/td><\/tr><tr><td><code>-n auto<\/code><\/td><td>One worker per CPU core. Uses physical cores when psutil is installed, otherwise the logical core count.<\/td><\/tr><tr><td><code>-n logical<\/code><\/td><td>One worker per logical core (hyperthreads included). Needs psutil; falls back to <code>auto<\/code> without it.<\/td><\/tr><tr><td><code>-n 0<\/code><\/td><td>Disables distribution; tests run in the main process. Handy for debugging.<\/td><\/tr><tr><td><code>--maxprocesses=N<\/code><\/td><td>Caps the worker count, for example <code>-n auto --maxprocesses=4<\/code> on large CI machines.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Distribution modes with &#8211;dist<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>--dist<\/code> controls how tests are handed to workers. When you pass <code>-n<\/code>, the default is <code>load<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Mode<\/th><th>How tests are assigned<\/th><th>Use when<\/th><\/tr><\/thead><tbody><tr><td><code>load<\/code><\/td><td>Any pending test goes to any free worker<\/td><td>Tests are independent (the default)<\/td><\/tr><tr><td><code>loadscope<\/code><\/td><td>Tests in the same module or class stay on one worker<\/td><td>Expensive module- or class-scoped fixtures should be set up once<\/td><\/tr><tr><td><code>loadfile<\/code><\/td><td>All tests in a file stay on one worker<\/td><td>Tests in a file share state or setup<\/td><\/tr><tr><td><code>loadgroup<\/code><\/td><td>Tests with the same <code>xdist_group<\/code> mark stay on one worker<\/td><td>Only a few tests must not run concurrently<\/td><\/tr><tr><td><code>worksteal<\/code><\/td><td>Like <code>load<\/code>, but idle workers take queued tests from busy ones<\/td><td>Test durations vary a lot<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import pytest\n\n<span class=\"hljs-comment\"># Run with: pytest -n 4 --dist loadgroup<\/span>\n@pytest.mark.xdist_group(name=<span class=\"hljs-string\">\"database\"<\/span>)\ndef test_create_user():\n    ...\n\n@pytest.mark.xdist_group(name=<span class=\"hljs-string\">\"database\"<\/span>)\ndef test_delete_user():\n    ...<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Writing tests that are safe to run in parallel<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Most problems with <code>-n<\/code> are not xdist bugs. They are hidden dependencies between tests that serial execution happened to hide. Check for these:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Order dependence.<\/strong> A test that relies on another test running first will fail at random. Every test should create its own preconditions.<\/li>\n\n\n<li><strong>Shared files.<\/strong> Use the built-in <code>tmp_path<\/code> fixture instead of fixed paths such as <code>\/tmp\/output.json<\/code>.<\/li>\n\n\n<li><strong>Shared databases or ports.<\/strong> Give each worker its own resource, using the <code>worker_id<\/code> fixture or the <code>PYTEST_XDIST_WORKER<\/code> environment variable (values like <code>gw0<\/code>, <code>gw1<\/code>).<\/li>\n\n\n<li><strong>Session-scoped fixtures run once per worker<\/strong>, not once per run. With <code>-n 4<\/code>, a session fixture that seeds a database runs four times.<\/li>\n\n\n<li><strong>Global state<\/strong> such as module-level caches or monkeypatched settings is per process, so it is not shared across workers.<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\"># <span class=\"hljs-selector-tag\">conftest<\/span><span class=\"hljs-selector-class\">.py<\/span>\n<span class=\"hljs-selector-tag\">import<\/span> <span class=\"hljs-selector-tag\">pytest<\/span>\n\n<span class=\"hljs-keyword\">@pytest<\/span>.fixture(scope=\"session\")\ndef db_name(worker_id):\n    # worker_id is <span class=\"hljs-string\">\"master\"<\/span> when xdist is <span class=\"hljs-keyword\">not<\/span> active, else <span class=\"hljs-string\">\"gw0\"<\/span>, <span class=\"hljs-string\">\"gw1\"<\/span>, ...\n    if worker_id == <span class=\"hljs-string\">\"master\"<\/span>:\n        return <span class=\"hljs-string\">\"test_db\"<\/span>\n    return f<span class=\"hljs-string\">\"test_db_{worker_id}\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Making it the default and using it in CI<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Add the option to your pytest configuration so that developers and CI behave the same way:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># pyproject.toml<\/span>\n&#91;tool.pytest.ini_options]\naddopts = <span class=\"hljs-string\">\"-n auto --dist loadscope\"<\/span>\ntestpaths = &#91;<span class=\"hljs-string\">\"tests\"<\/span>]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Add <code>pytest-xdist<\/code> to your dev or test requirements so CI installs it. To run serially for one invocation despite <code>addopts<\/code>, override it with <code>pytest -n 0<\/code>. Disabling the plugin with <code>-p no:xdist<\/code> also removes the <code>-n<\/code> option, so that only works when <code>-n<\/code> is not in <code>addopts<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>error: unrecognized arguments: -n<\/code><\/td><td>pytest-xdist is not installed in the active environment<\/td><td><code>pip install pytest-xdist<\/code>; check with <code>python -m pytest --version<\/code><\/td><\/tr><tr><td><code>Different tests were collected between gw0 and gw1<\/code><\/td><td>Test IDs are generated in a non-deterministic order (sets, random values in <code>parametrize<\/code>)<\/td><td>Make parametrize inputs deterministic, for example <code>sorted(...)<\/code><\/td><\/tr><tr><td>Tests pass serially but fail with <code>-n<\/code><\/td><td>Shared files, databases or test-order dependence<\/td><td>Isolate resources per worker; use <code>--dist loadfile<\/code> or <code>loadgroup<\/code> as a stopgap<\/td><\/tr><tr><td>No speed-up, or slower<\/td><td>Suite is too small, or tests are CPU-bound with too many workers<\/td><td>Measure with <code>--durations=10<\/code>; reduce <code>-n<\/code> or run serially<\/td><\/tr><tr><td><code>print()<\/code> output missing<\/td><td>Worker output is captured<\/td><td>Run with <code>-n 0 -s<\/code> while debugging<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Is pytest -n built into pytest?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. The <code>-n<\/code> option comes from the pytest-xdist plugin. Install it with <code>pip install pytest-xdist<\/code>; without it, pytest reports <code>unrecognized arguments: -n<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What does pytest -n auto do?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does pytest -n use threads or processes?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Processes. Each worker is a separate Python interpreter, so tests do not share memory, and CPU-bound tests are not limited by the GIL.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why do my session-scoped fixtures run more than once with pytest -n?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each worker is its own pytest session, so session fixtures run once per worker. Use the <code>worker_id<\/code> fixture to give each worker separate resources, or use a file lock if a step must run only once.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I stop certain tests from running at the same time?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Mark them with <code>@pytest.mark.xdist_group(name=&quot;...&quot;)<\/code> and run with <code>--dist loadgroup<\/code>. Tests in the same group then run one after another on a single worker.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/programming\/python-programming-scripting-languages\/\">More Python tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-100-interview-questions-for-python\/\">TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/what-is-django-and-use-cases-of-django\/\">What is Django and use cases of Django?<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230;. <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[499],"tags":[4803,7504],"class_list":["post-41519","post","type-post","status-publish","format-standard","hentry","category-python-programming-scripting-languages","tag-test-automation","tag-unit-testing"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41519","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=41519"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41519\/revisions"}],"predecessor-version":[{"id":80237,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41519\/revisions\/80237"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=41519"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=41519"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=41519"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}