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
| Symptom | Likely cause | Fix |
|---|---|---|
| Tests pass serially but fail in parallel | Tests share files, database rows, ports or environment variables | Give each test its own temp directory (tempfile.TemporaryDirectory), its own database or schema, and port 0 for servers |
| No speed-up at all | The runner parallelises by module and you have one module, or only one CPU is available | Use --level test with unittest-parallel, or -n auto with pytest-xdist. Check os.cpu_count() in CI |
setUpClass or expensive fixtures run many times | Each worker process runs its own class-level setup | Accept 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 importable | tests/ has no __init__.py, or -t points to the wrong directory | Add tests/__init__.py and run from the project root with -t . |
| Errors about pickling or the main module on Windows or macOS | Worker processes are started with spawn, so code at module level runs again in each worker | Keep the pool code under if __name__ == "__main__": and pass only picklable data to workers |
| Parallel run is slower than serial | Process start-up costs more than the time saved on very fast tests | Use parallel runs only for slow suites, and use fewer workers |
Choosing a runner
| Runner | Install | Parallel command | Best for |
|---|---|---|---|
| unittest-parallel | pip install unittest-parallel | unittest-parallel -s tests -t . --level test | Pure unittest projects that want a drop-in replacement |
| pytest-xdist | pip install pytest pytest-xdist | pytest -n auto | Most projects. Runs both unittest and pytest-style tests |
| nose2 mp plugin | pip install nose2 | nose2 --plugin=nose2.plugins.mp -N 4 | Projects that already use nose2 |
Custom multiprocessing.Pool script | Nothing to install | python run_parallel.py | Locked-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
- More Python tutorials
- TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-
- What is Django and use cases of Django?
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.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals