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 – 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 unittest example above, shows the commands it leaves out, and covers runners that are maintained and well documented: unittest-parallel, pytest-xdist, nose2'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.

To useย multiprocessing-testrunnerย for parallel test execution across multiple processes, you first need to installย multiprocessing-testrunner. Below is a sample code demonstrating how to use it for concurrent test execution, leveraging multiple processes for improved test execution speed.


What the example above does and what it leaves out

The example above defines one unittest.TestCase 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.

The example never shows how to start the runner. The line # multiprocessing-testrunner tests is a comment, not a working command, and multiprocessing-testrunner 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.

Note: time.sleep() 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.

Project layout and prerequisites

You need Python 3 and a virtual environment. Put the test file in a tests package and add an empty __init__.py, so that test discovery and import-by-name both work from the project root.

project/
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ””โ”€โ”€ test_multiprocessing_execution.py
โ””โ”€โ”€ run_parallel.py        # only for the stdlib option belowCode language: PHP (php)
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
touch tests/__init__.py

# Baseline: serial run with the standard library
python -m unittest discover -s tests -t . -vCode language: PHP (php)

The serial run should report Ran 3 tests in 3.0XXs and OK. Note this time, because you will compare the parallel runs against it.

Run unittest tests in parallel with unittest-parallel

unittest-parallel works like python -m unittest discover, but spreads the tests across several processes. By default it parallelises at module level. The example has only one module, so the default would give you no speed-up. Use --level test so that each test method can go to a different process.

pip install unittest-parallel

# One process per CPU core, split at individual test methods
unittest-parallel -s tests -t . --level test -v

# Limit the number of worker processes
unittest-parallel -s tests -t . --level test -j 3Code language: PHP (php)

-s sets the start directory, -t sets the top-level directory used for imports, and -j sets the number of processes. On a machine with at least three cores, the run time should drop to a little over 1 second.

Alternatives: pytest-xdist and nose2

pytest runs unittest.TestCase classes as they are. With the pytest-xdist plugin it sends individual tests to worker processes, which makes it the most common choice for parallel testing in Python.

pip install pytest pytest-xdist

# One worker per CPU core
pytest -n auto tests/

# Exactly 3 workers, with verbose output
pytest -n 3 -v tests/Code language: PHP (php)

If your project already uses nose2, its built-in multiprocessing plugin does the same job:

pip install nose2
nose2 --plugin=nose2.plugins.mp -N 3 -s . tests

A standard-library-only parallel runner

If you cannot install packages, multiprocessing.Pool 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 run_parallel.py in the project root.

import sys
import unittest
from multiprocessing import Pool


def iter_test_ids(suite):
    """Flatten nested TestSuites into individual test IDs."""
    for item in suite:
        if isinstance(item, unittest.TestSuite):
            yield from iter_test_ids(item)
        else:
            yield item.id()


def run_one(test_id):
    """Runs inside a worker process."""
    suite = unittest.defaultTestLoader.loadTestsFromName(test_id)
    result = unittest.TestResult()
    suite.run(result)
    tracebacks = [tb for _, tb in result.failures + result.errors]
    return test_id, result.wasSuccessful(), tracebacks


if __name__ == "__main__":
    suite = unittest.defaultTestLoader.discover("tests", top_level_dir=".")
    test_ids = list(iter_test_ids(suite))

    with Pool() as pool:  # defaults to os.cpu_count() workers
        results = pool.map(run_one, test_ids)

    failed = 0
    for test_id, ok, tracebacks in results:
        print(f"{'ok  ' if ok else 'FAIL'} {test_id}")
        for tb in tracebacks:
            print(tb)
        failed += not ok

    print(f"\n{len(results)} tests, {failed} failed")
    sys.exit(1 if failed else 0)Code language: PHP (php)
$ time python run_parallel.py
ok   tests.test_multiprocessing_execution.TestMultiprocessingExecution.test_task_1
ok   tests.test_multiprocessing_execution.TestMultiprocessingExecution.test_task_2
ok   tests.test_multiprocessing_execution.TestMultiprocessingExecution.test_task_3

3 tests, 0 failed

The if __name__ == "__main__": guard is required. On Windows and macOS, multiprocessing 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 setUpClass once per test, use a dedicated runner for anything larger than a small suite.

A corrected, more meaningful test file

self.assertTrue(True, "...") 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:

# tests/test_multiprocessing_execution.py
import os
import time
import unittest


def slow_square(n):
    time.sleep(1)  # simulate slow work
    return n * n


class TestMultiprocessingExecution(unittest.TestCase):
    def test_task_1(self):
        self.assertEqual(slow_square(2), 4)

    def test_task_2(self):
        self.assertEqual(slow_square(3), 9)

    def test_task_3(self):
        self.assertEqual(slow_square(4), 16)

    def test_runs_in_some_process(self):
        # Prints the worker PID so you can confirm tests ran in different processes
        print(f"{self.id()} ran in PID {os.getpid()}")
        self.assertGreater(os.getpid(), 0)

Note: With pytest, add -s to see the print output. Each worker reports a different PID, which confirms that the tests ran in separate processes.

Common problems when tests run in separate processes

SymptomLikely causeFix
Tests pass serially but fail in parallelTests share files, database rows, ports or environment variablesGive each test its own temp directory (tempfile.TemporaryDirectory), its own database or schema, and port 0 for servers
No speed-up at allThe runner parallelises by module and you have one module, or only one CPU is availableUse --level test with unittest-parallel, or -n auto with pytest-xdist. Check os.cpu_count() in CI
setUpClass or expensive fixtures run many timesEach worker process runs its own class-level setupAccept the cost, group tests by class (--level class or pytest --dist loadscope), or move setup into a shared external service
ImportError: Start directory is not importabletests/ has no __init__.py, or -t points to the wrong directoryAdd tests/__init__.py and run from the project root with -t .
Errors about pickling or the main module on Windows or macOSWorker processes are started with spawn, so code at module level runs again in each workerKeep the pool code under if __name__ == "__main__": and pass only picklable data to workers
Parallel run is slower than serialProcess start-up costs more than the time saved on very fast testsUse parallel runs only for slow suites, and use fewer workers

Choosing a runner

RunnerInstallParallel commandBest for
unittest-parallelpip install unittest-parallelunittest-parallel -s tests -t . --level testPure unittest projects that want a drop-in replacement
pytest-xdistpip install pytest pytest-xdistpytest -n autoMost projects. Runs both unittest and pytest-style tests
nose2 mp pluginpip install nose2nose2 --plugin=nose2.plugins.mp -N 4Projects that already use nose2
Custom multiprocessing.Pool scriptNothing to installpython run_parallel.pyLocked-down environments or learning how parallel runners work

Frequently asked questions

How do I run Python unittest tests in parallel?

Install unittest-parallel and run unittest-parallel -s tests -t . --level test, or install pytest-xdist and run pytest -n auto. pytest-xdist runs unittest TestCase classes without any changes.

Does the standard unittest module support parallel execution?

No. python -m unittest runs tests one after another in a single process. Parallel runs need a third-party runner or a custom script built on multiprocessing.

Why is my parallel test run not faster?

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 setUpClass can also cancel out the gain.

Should I use processes or threads for parallel tests?

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.

Can parallel tests share a database?

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.

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 – 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 -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….

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