{"id":41515,"date":"2026-11-26T22:04:55","date_gmt":"2026-11-26T22:04:55","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=41515"},"modified":"2026-11-26T22:04:55","modified_gmt":"2026-11-26T22:04:55","slug":"python-test-runners-multiprocessing-testrunner","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/python-test-runners-multiprocessing-testrunner\/","title":{"rendered":"Python Test Runners &#8211; multiprocessing-testrunner"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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 unittest example above, shows the commands it leaves out, and covers runners that are maintained and well documented: unittest-parallel, pytest-xdist, nose2&#039;s mp plugin, and a short script that uses only the standard library. It also covers the isolation problems that show up when tests run in parallel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To use\u00a0<code>multiprocessing-testrunner<\/code>\u00a0for parallel test execution across multiple processes, you first need to install\u00a0<code>multiprocessing-testrunner<\/code>. Below is a sample code demonstrating how to use it for concurrent test execution, leveraging multiple processes for improved test execution speed.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/9bc9b5c93aef83a93f34edda79d65ba7.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 the example above does and what it leaves out<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The example above defines one <code>unittest.TestCase<\/code> class with three test methods. Each one sleeps for 1 second. Run one after another, the suite takes about 3 seconds. Run in three worker processes, it should take about 1 second plus the time needed to start the workers. That makes it a good way to check that parallel execution is actually working.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The example never shows how to start the runner. The line <code># multiprocessing-testrunner tests<\/code> is a comment, not a working command, and <code>multiprocessing-testrunner<\/code> is not a widely used or well-documented runner. Before you build a CI pipeline on it, check its PyPI page and repository to confirm that it exists and is maintained. For most projects, the runners below are a safer choice and run the same test file without changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> <code>time.sleep()<\/code> keeps tests waiting, not computing, so this example measures parallelism in general. Separate processes matter most for CPU-bound tests, because each process has its own interpreter and its own GIL.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Project layout and prerequisites<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You need Python 3 and a virtual environment. Put the test file in a <code>tests<\/code> package and add an empty <code>__init__.py<\/code>, so that test discovery and import-by-name both work from the project root.<\/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\">project\/\n\u251c\u2500\u2500 tests\/\n\u2502   \u251c\u2500\u2500 __init__.py\n\u2502   \u2514\u2500\u2500 test_multiprocessing_execution.py\n\u2514\u2500\u2500 run_parallel.py        <span class=\"hljs-comment\"># only for the stdlib option below<\/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<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\">python3 -m venv .venv\nsource .venv\/bin\/activate        <span class=\"hljs-comment\"># Windows: .venv\\Scripts\\activate<\/span>\ntouch tests\/__init__.py\n\n<span class=\"hljs-comment\"># Baseline: serial run with the standard library<\/span>\npython -m unittest discover -s tests -t . -v<\/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<p class=\"wp-block-paragraph\">The serial run should report <code>Ran 3 tests in 3.0XXs<\/code> and <code>OK<\/code>. Note this time, because you will compare the parallel runs against it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Run unittest tests in parallel with unittest-parallel<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>unittest-parallel<\/code> works like <code>python -m unittest discover<\/code>, but spreads the tests across several processes. By default it parallelises at <strong>module<\/strong> level. The example has only one module, so the default would give you no speed-up. Use <code>--level test<\/code> so that each test method can go to a different process.<\/p>\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\">pip install unittest-parallel\n\n<span class=\"hljs-comment\"># One process per CPU core, split at individual test methods<\/span>\nunittest-parallel -s tests -t . --level test -v\n\n<span class=\"hljs-comment\"># Limit the number of worker processes<\/span>\nunittest-parallel -s tests -t . --level test -j <span class=\"hljs-number\">3<\/span><\/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\"><code>-s<\/code> sets the start directory, <code>-t<\/code> sets the top-level directory used for imports, and <code>-j<\/code> sets the number of processes. On a machine with at least three cores, the run time should drop to a little over 1 second.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Alternatives: pytest-xdist and nose2<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">pytest runs <code>unittest.TestCase<\/code> classes as they are. With the <code>pytest-xdist<\/code> plugin it sends individual tests to worker processes, which makes it the most common choice for parallel testing in Python.<\/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\">pip install pytest pytest-xdist\n\n<span class=\"hljs-comment\"># One worker per CPU core<\/span>\npytest -n auto tests\/\n\n<span class=\"hljs-comment\"># Exactly 3 workers, with verbose output<\/span>\npytest -n <span class=\"hljs-number\">3<\/span> -v tests\/<\/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\">If your project already uses nose2, its built-in multiprocessing plugin does the same job:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">pip install nose2\nnose2 --plugin=nose2.plugins.mp -N 3 -s . tests<\/code><\/span><\/pre>\n\n\n<h2 class=\"wp-block-heading\">A standard-library-only parallel runner<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If you cannot install packages, <code>multiprocessing.Pool<\/code> can run each discovered test in a worker process. The script below finds the tests, sends their IDs to a pool, and collects the pass and fail results. Save it as <code>run_parallel.py<\/code> in the project root.<\/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 sys\nimport unittest\nfrom multiprocessing import Pool\n\n\ndef iter_test_ids(suite):\n    <span class=\"hljs-string\">\"\"<\/span><span class=\"hljs-string\">\"Flatten nested TestSuites into individual test IDs.\"<\/span><span class=\"hljs-string\">\"\"<\/span>\n    <span class=\"hljs-keyword\">for<\/span> item in suite:\n        <span class=\"hljs-keyword\">if<\/span> isinstance(item, unittest.TestSuite):\n            <span class=\"hljs-keyword\">yield<\/span> from iter_test_ids(item)\n        <span class=\"hljs-keyword\">else<\/span>:\n            <span class=\"hljs-keyword\">yield<\/span> item.id()\n\n\ndef run_one(test_id):\n    <span class=\"hljs-string\">\"\"<\/span><span class=\"hljs-string\">\"Runs inside a worker process.\"<\/span><span class=\"hljs-string\">\"\"<\/span>\n    suite = unittest.defaultTestLoader.loadTestsFromName(test_id)\n    result = unittest.TestResult()\n    suite.run(result)\n    tracebacks = &#91;tb <span class=\"hljs-keyword\">for<\/span> _, tb in result.failures + result.errors]\n    <span class=\"hljs-keyword\">return<\/span> test_id, result.wasSuccessful(), tracebacks\n\n\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">\"__main__\"<\/span>:\n    suite = unittest.defaultTestLoader.discover(<span class=\"hljs-string\">\"tests\"<\/span>, top_level_dir=<span class=\"hljs-string\">\".\"<\/span>)\n    test_ids = <span class=\"hljs-keyword\">list<\/span>(iter_test_ids(suite))\n\n    with Pool() <span class=\"hljs-keyword\">as<\/span> pool:  <span class=\"hljs-comment\"># defaults to os.cpu_count() workers<\/span>\n        results = pool.map(run_one, test_ids)\n\n    failed = <span class=\"hljs-number\">0<\/span>\n    <span class=\"hljs-keyword\">for<\/span> test_id, ok, tracebacks in results:\n        <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"{'ok  ' if ok else 'FAIL'} {test_id}\"<\/span>)\n        <span class=\"hljs-keyword\">for<\/span> tb in tracebacks:\n            <span class=\"hljs-keyword\">print<\/span>(tb)\n        failed += not ok\n\n    <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"\\n{len(results)} tests, {failed} failed\"<\/span>)\n    sys.<span class=\"hljs-keyword\">exit<\/span>(<span class=\"hljs-number\">1<\/span> <span class=\"hljs-keyword\">if<\/span> failed <span class=\"hljs-keyword\">else<\/span> <span class=\"hljs-number\">0<\/span>)<\/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<pre class=\"wp-block-code\"><span><code class=\"hljs\">$ time python run_parallel.py\nok   tests.test_multiprocessing_execution.TestMultiprocessingExecution.test_task_1\nok   tests.test_multiprocessing_execution.TestMultiprocessingExecution.test_task_2\nok   tests.test_multiprocessing_execution.TestMultiprocessingExecution.test_task_3\n\n3 tests, 0 failed<\/code><\/span><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The <code>if __name__ == &quot;__main__&quot;:<\/code> guard is required. On Windows and macOS, <code>multiprocessing<\/code> starts workers with the *spawn* method, which re-imports the main script in each worker. Without the guard, every worker would try to start its own pool. The non-zero exit code on failure lets CI systems detect a failing run. Because this script runs <code>setUpClass<\/code> once per test, use a dedicated runner for anything larger than a small suite.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A corrected, more meaningful test file<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>self.assertTrue(True, &quot;...&quot;)<\/code> always passes. The message appears only when an assertion fails, so here it never appears. A useful parallel test should check a real result. This version keeps the 1-second delay and checks values that the code under test returns:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\"># tests\/test_multiprocessing_execution.py\nimport os\nimport time\nimport unittest\n\n\ndef slow_square(n):\n    time.sleep(1)  # simulate slow work\n    return n * n\n\n\nclass TestMultiprocessingExecution(unittest.TestCase):\n    def test_task_1(self):\n        self.assertEqual(slow_square(2), 4)\n\n    def test_task_2(self):\n        self.assertEqual(slow_square(3), 9)\n\n    def test_task_3(self):\n        self.assertEqual(slow_square(4), 16)\n\n    def test_runs_in_some_process(self):\n        # Prints the worker PID so you can confirm tests ran in different processes\n        print(f\"{self.id()} ran in PID {os.getpid()}\")\n        self.assertGreater(os.getpid(), 0)<\/code><\/span><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> With pytest, add <code>-s<\/code> to see the <code>print<\/code> output. Each worker reports a different PID, which confirms that the tests ran in separate processes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common problems when tests run in separate processes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Likely cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td>Tests pass serially but fail in parallel<\/td><td>Tests share files, database rows, ports or environment variables<\/td><td>Give each test its own temp directory (<code>tempfile.TemporaryDirectory<\/code>), its own database or schema, and port 0 for servers<\/td><\/tr><tr><td>No speed-up at all<\/td><td>The runner parallelises by module and you have one module, or only one CPU is available<\/td><td>Use <code>--level test<\/code> with unittest-parallel, or <code>-n auto<\/code> with pytest-xdist. Check <code>os.cpu_count()<\/code> in CI<\/td><\/tr><tr><td><code>setUpClass<\/code> or expensive fixtures run many times<\/td><td>Each worker process runs its own class-level setup<\/td><td>Accept the cost, group tests by class (<code>--level class<\/code> or pytest <code>--dist loadscope<\/code>), or move setup into a shared external service<\/td><\/tr><tr><td><code>ImportError: Start directory is not importable<\/code><\/td><td><code>tests\/<\/code> has no <code>__init__.py<\/code>, or <code>-t<\/code> points to the wrong directory<\/td><td>Add <code>tests\/__init__.py<\/code> and run from the project root with <code>-t .<\/code><\/td><\/tr><tr><td>Errors about pickling or the main module on Windows or macOS<\/td><td>Worker processes are started with spawn, so code at module level runs again in each worker<\/td><td>Keep the pool code under <code>if __name__ == &quot;__main__&quot;:<\/code> and pass only picklable data to workers<\/td><\/tr><tr><td>Parallel run is slower than serial<\/td><td>Process start-up costs more than the time saved on very fast tests<\/td><td>Use parallel runs only for slow suites, and use fewer workers<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Choosing a runner<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Runner<\/th><th>Install<\/th><th>Parallel command<\/th><th>Best for<\/th><\/tr><\/thead><tbody><tr><td>unittest-parallel<\/td><td><code>pip install unittest-parallel<\/code><\/td><td><code>unittest-parallel -s tests -t . --level test<\/code><\/td><td>Pure unittest projects that want a drop-in replacement<\/td><\/tr><tr><td>pytest-xdist<\/td><td><code>pip install pytest pytest-xdist<\/code><\/td><td><code>pytest -n auto<\/code><\/td><td>Most projects. Runs both unittest and pytest-style tests<\/td><\/tr><tr><td>nose2 mp plugin<\/td><td><code>pip install nose2<\/code><\/td><td><code>nose2 --plugin=nose2.plugins.mp -N 4<\/code><\/td><td>Projects that already use nose2<\/td><\/tr><tr><td>Custom <code>multiprocessing.Pool<\/code> script<\/td><td>Nothing to install<\/td><td><code>python run_parallel.py<\/code><\/td><td>Locked-down environments or learning how parallel runners work<\/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\">How do I run Python unittest tests in parallel?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Install <code>unittest-parallel<\/code> and run <code>unittest-parallel -s tests -t . --level test<\/code>, or install <code>pytest-xdist<\/code> and run <code>pytest -n auto<\/code>. pytest-xdist runs unittest TestCase classes without any changes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does the standard unittest module support parallel execution?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. <code>python -m unittest<\/code> runs tests one after another in a single process. Parallel runs need a third-party runner or a custom script built on <code>multiprocessing<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why is my parallel test run not faster?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The usual causes are a runner that splits work by module when you have only one module, a CI machine with a single CPU, or tests so fast that process start-up costs more than it saves. Very slow per-worker setup such as <code>setUpClass<\/code> can also cancel out the gain.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use processes or threads for parallel tests?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Processes isolate tests from each other and avoid the GIL, so CPU-bound tests really do run at the same time. Threads start faster, but tests in the same process share memory and global state, which makes them fragile. All the common Python parallel runners use processes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can parallel tests share a database?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Only if each test uses its own data and never depends on rows written by another test. A safer approach is a separate database, schema or transaction for each worker. pytest-xdist exposes the worker ID so you can name these per 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>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&#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-41515","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\/41515","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=41515"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41515\/revisions"}],"predecessor-version":[{"id":80309,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41515\/revisions\/80309"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=41515"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=41515"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=41515"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}