{"id":41523,"date":"2026-11-25T22:08:20","date_gmt":"2026-11-25T22:08:20","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=41523"},"modified":"2026-11-25T22:08:20","modified_gmt":"2026-11-25T22:08:20","slug":"python-test-runners-pytest-xdist","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/python-test-runners-pytest-xdist\/","title":{"rendered":"Python Test Runners &#8211; Pytest-xdist"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">pytest-xdist is a pytest plugin that splits a test suite across several worker processes so the tests run in parallel, and the <code>-n<\/code> 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To run the tests in parallel using Pytest-xdist, you can specify the number of CPUs to use with the&nbsp;<code>-n<\/code>&nbsp;option. For example, to run tests on 2 CPUs in parallel, you can run:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Pytest-xdist will execute the test cases concurrently, utilizing the available CPU cores efficiently.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/dc94ac7919972cabe5e10f612ec5a6a2.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How pytest-xdist runs tests<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">When you pass <code>-n<\/code>, pytest becomes a controller. It starts that many worker processes, named <code>gw0<\/code>, <code>gw1<\/code> 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Running the example step by step<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create and activate a virtual environment: <code>python -m venv .venv &amp;&amp; source .venv\/bin\/activate<\/code>.<\/li>\n\n\n<li>Install the packages: <code>pip install pytest pytest-xdist<\/code>.<\/li>\n\n\n<li>Save the gist code as <code>tests\/test_parallel_execution.py<\/code>. It must be a <code>.py<\/code> file whose name starts with <code>test_<\/code>, or pytest will not collect it.<\/li>\n\n\n<li>Run it serially first so you have a baseline: <code>pytest<\/code>. The three tests sleep for 1 second each, so this takes about 3 seconds.<\/li>\n\n\n<li>Run it with two workers: <code>pytest -n 2<\/code>.<\/li>\n\n\n<li>Run it with one worker per test: <code>pytest -n 3<\/code>. This takes about 1 second plus worker startup time.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">$ pytest -n <span class=\"hljs-number\">2<\/span>\n============================= test session starts ==============================\nplatform linux -- Python <span class=\"hljs-number\">3.<\/span>x, pytest<span class=\"hljs-number\">-8.<\/span>x, pluggy<span class=\"hljs-number\">-1.<\/span>x\n<span class=\"hljs-attr\">rootdir<\/span>: <span class=\"hljs-regexp\">\/home\/u<\/span>ser\/project\n<span class=\"hljs-attr\">plugins<\/span>: xdist<span class=\"hljs-number\">-3.<\/span>x\n<span class=\"hljs-attr\">created<\/span>: <span class=\"hljs-number\">2<\/span>\/<span class=\"hljs-number\">2<\/span> workers\n<span class=\"hljs-number\">2<\/span> workers &#91;<span class=\"hljs-number\">3<\/span> items]\n...                                                                      &#91;<span class=\"hljs-number\">100<\/span>%]\n============================== <span class=\"hljs-number\">3<\/span> passed <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-number\">2.4<\/span>s ================================<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The lines <code>created: 2\/2 workers<\/code> and <code>2 workers [3 items]<\/code> 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 <code>-v<\/code> to see which worker ran each test, for example <code>[gw1] PASSED tests\/test_parallel_execution.py::test_task_2<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Corrections to the original example<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The text says &quot;you can run:&quot; but no command follows it. The command is <code>pytest -n 2<\/code>. It appears only as a comment at the end of the gist.<\/li>\n\n\n<li><code>-n<\/code> sets the number of <strong>worker processes<\/strong>, not CPUs. You can start more workers than you have cores, and xdist does not pin workers to cores. Use <code>-n auto<\/code> to match the CPU count.<\/li>\n\n\n<li>The gist file is named <code>gistfile1.txt<\/code>. Save it as <code>tests\/test_parallel_execution.py<\/code>, or pytest will not discover it.<\/li>\n\n\n<li><code>assert True, &quot;Task 1 completed successfully.&quot;<\/code> can never fail. The message after the comma is printed only when an assertion <strong>fails<\/strong>, so it is not a success message. In real tests, assert on an actual result, for example <code>assert result == expected<\/code>.<\/li>\n\n\n<li><code>import pytest<\/code> is not used in the example. It does no harm, but you only need it once you use fixtures or markers.<\/li>\n<\/ul>\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>Option<\/th><th>What it does<\/th><\/tr><\/thead><tbody><tr><td><code>-n 4<\/code><\/td><td>Starts exactly 4 workers.<\/td><\/tr><tr><td><code>-n auto<\/code><\/td><td>Starts one worker per CPU. If <code>psutil<\/code> is installed, it counts physical cores.<\/td><\/tr><tr><td><code>-n logical<\/code><\/td><td>Starts one worker per logical CPU, which includes hyper-threads. Needs <code>psutil<\/code> for an accurate count.<\/td><\/tr><tr><td><code>-n 0<\/code><\/td><td>Turns off distribution. Tests run in the main process.<\/td><\/tr><tr><td><code>-p no:xdist<\/code><\/td><td>Turns off the plugin entirely, for example when debugging.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> In containers and CI runners, <code>-n auto<\/code> can detect more CPUs than the job is allowed to use, which leads to CPU contention. Set an explicit number such as <code>-n 4<\/code>, or set the <code>PYTEST_XDIST_AUTO_NUM_WORKERS<\/code> environment variable to cap <code>auto<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To make parallel runs the default, add the option to your configuration. You can still override it with <code>-n 0<\/code> on the command line.<\/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\"># pytest.ini<\/span>\n&#91;pytest]\naddopts = -n auto\ntestpaths = tests<\/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\">Distribution modes with &#8211;dist<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>--dist<\/code> option controls how tests are grouped and sent to workers. The default when <code>-n<\/code> is set is <code>load<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Mode<\/th><th>Behaviour<\/th><th>Use when<\/th><\/tr><\/thead><tbody><tr><td><code>load<\/code><\/td><td>Sends pending tests to whichever worker is free.<\/td><td>Tests are independent. This is the default.<\/td><\/tr><tr><td><code>loadscope<\/code><\/td><td>Keeps tests from the same module, or the same class for methods, on one worker.<\/td><td>Module- or class-scoped fixtures are expensive to build.<\/td><\/tr><tr><td><code>loadfile<\/code><\/td><td>Keeps all tests from the same file on one worker.<\/td><td>Tests in one file share state or setup.<\/td><\/tr><tr><td><code>loadgroup<\/code><\/td><td>Keeps tests with the same <code>xdist_group<\/code> mark on one worker.<\/td><td>Only some tests must not run at the same time.<\/td><\/tr><tr><td><code>worksteal<\/code><\/td><td>Splits tests evenly, then lets idle workers take work 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-3\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\"><span class=\"hljs-selector-tag\">import<\/span> <span class=\"hljs-selector-tag\">pytest<\/span>\n\n<span class=\"hljs-keyword\">@pytest<\/span>.mark.xdist_group(name=\"database\")\ndef test_create_user():\n    ...\n\n@pytest.mark.xdist_group(name=<span class=\"hljs-string\">\"database\"<\/span>)\ndef test_delete_user():\n    ...\n\n# Run <span class=\"hljs-attribute\">with:<\/span> pytest -n <span class=\"hljs-number\">4<\/span> --dist loadgroup<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><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\">Shared state and session fixtures<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>scope=&quot;session&quot;<\/code> fixture runs <strong>once per worker<\/strong>, not once for the whole run. Use the <code>worker_id<\/code> fixture to give each worker its own resources. It returns <code>gw0<\/code>, <code>gw1<\/code> and so on, or <code>master<\/code> when xdist is not distributing tests.<\/p>\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@pytest.fixture(scope=<span class=\"hljs-string\">\"session\"<\/span>)\ndef db_name(worker_id):\n    <span class=\"hljs-comment\"># Each worker gets its own database: test_db_gw0, test_db_gw1, ...<\/span>\n    <span class=\"hljs-keyword\">return<\/span> f<span class=\"hljs-string\">\"test_db_{worker_id}\"<\/span><\/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<p class=\"wp-block-paragraph\">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 <code>pip install filelock<\/code>.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import json\nimport pytest\nfrom filelock import FileLock\n\ndef produce_expensive_data():\n    <span class=\"hljs-keyword\">return<\/span> {<span class=\"hljs-string\">\"users\"<\/span>: &#91;<span class=\"hljs-string\">\"alice\"<\/span>, <span class=\"hljs-string\">\"bob\"<\/span>]}\n\n@pytest.fixture(scope=<span class=\"hljs-string\">\"session\"<\/span>)\ndef session_data(tmp_path_factory, worker_id):\n    <span class=\"hljs-keyword\">if<\/span> worker_id == <span class=\"hljs-string\">\"master\"<\/span>:\n        <span class=\"hljs-comment\"># Not running under xdist<\/span>\n        <span class=\"hljs-keyword\">return<\/span> produce_expensive_data()\n\n    <span class=\"hljs-comment\"># Directory shared by all workers in this run<\/span>\n    root_tmp_dir = tmp_path_factory.getbasetemp().<span class=\"hljs-keyword\">parent<\/span>\n    fn = root_tmp_dir \/ <span class=\"hljs-string\">\"data.json\"<\/span>\n    with FileLock(str(fn) + <span class=\"hljs-string\">\".lock\"<\/span>):\n        <span class=\"hljs-keyword\">if<\/span> fn.is_file():\n            data = json.loads(fn.read_text())\n        <span class=\"hljs-keyword\">else<\/span>:\n            data = produce_expensive_data()\n            fn.write_text(json.dumps(data))\n    <span class=\"hljs-keyword\">return<\/span> data<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><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\">Code outside fixtures can read the environment variables <code>PYTEST_XDIST_WORKER<\/code> and <code>PYTEST_XDIST_WORKER_COUNT<\/code> for the same information.<\/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>Run <code>pip install pytest-xdist<\/code> in the same virtual environment as pytest.<\/td><\/tr><tr><td><code>Different tests were collected between gw0 and gw1<\/code><\/td><td>Collection is not deterministic, for example parameters built from <code>random<\/code>, from sets, or from the current time.<\/td><td>Generate parameters in a fixed order, or seed the randomness so every worker collects the same list.<\/td><\/tr><tr><td>Tests fail randomly only with <code>-n<\/code><\/td><td>Tests share files, ports, databases or globals.<\/td><td>Use <code>tmp_path<\/code>, give each worker its own resources via <code>worker_id<\/code>, or group the tests with <code>--dist loadgroup<\/code>.<\/td><\/tr><tr><td><code>print()<\/code> output does not appear with <code>-s<\/code><\/td><td>Worker output is not passed through to the terminal.<\/td><td>Use <code>-n 0<\/code> while debugging, or use logging with <code>--log-cli-level<\/code>.<\/td><\/tr><tr><td>Parallel run is slower than serial<\/td><td>Worker startup costs more than the time saved, or there are too many workers for the CPUs.<\/td><td>Use fewer workers, or keep xdist for large suites only.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>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.<\/li>\n\n\n<li>Use the built-in <code>tmp_path<\/code> fixture instead of fixed file paths. It is unique per test, so workers cannot collide.<\/li>\n\n\n<li>Measure the effect: compare <code>pytest --durations=10<\/code> against <code>pytest -n auto --durations=10<\/code>.<\/li>\n\n\n<li>pytest-cov supports xdist. <code>pytest -n auto --cov=myapp<\/code> combines coverage from all workers.<\/li>\n\n\n<li>Stopping options such as <code>-x<\/code> and <code>--maxfail<\/code> work, but other workers may finish the tests they already started before the run stops.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">How do I run pytest tests in parallel?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Install the plugin with <code>pip install pytest-xdist<\/code>, then run <code>pytest -n auto<\/code> to start one worker per CPU, or <code>pytest -n 4<\/code> for a fixed number of workers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does pytest-xdist use threads or processes?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why does my session-scoped fixture run more than once with pytest-xdist?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>FileLock<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I make some tests run on the same worker?<\/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>. You can also use <code>--dist loadfile<\/code> or <code>--dist loadscope<\/code> to keep a whole file, module or class together.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I temporarily disable pytest-xdist?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Pass <code>-n 0<\/code> to run in a single process, or <code>-p no:xdist<\/code> to skip loading the plugin. Both override an <code>-n<\/code> set in <code>addopts<\/code>.<\/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-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&#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":[7504],"class_list":["post-41523","post","type-post","status-publish","format-standard","hentry","category-python-programming-scripting-languages","tag-unit-testing"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41523","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=41523"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41523\/revisions"}],"predecessor-version":[{"id":80239,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41523\/revisions\/80239"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=41523"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=41523"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=41523"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}