unittest-parallel is a third-party runner that discovers standard Python unittest tests and runs them across several worker processes, so a slow suite finishes in less wall-clock time without any changes to your test code. This page explains the example above, fixes its run command (the tool has no discover subcommand and no -w option), and covers parallelism levels, coverage, CI use and the problems you are likely to hit.
Unittest, Python’s built-in testing framework, does not natively support parallel test execution. To achieve parallel test execution with unittest, you can use third-party libraries likeย unittest-parallel. Below is an example of how you can useย unittest-parallelย to enable parallel execution of test cases with unittest.
Corrected command for the example above
The last line of the example above uses unittest-parallel discover ... -w 2. That syntax is borrowed from python -m unittest discover, but unittest-parallel always runs discovery, so it takes no discover subcommand. The worker count is set with -j / --jobs, not -w. Run as written, argparse rejects the command with an unrecognized arguments error.
There is a second, quieter problem. By default unittest-parallel splits work by module. All three tests in the example live in one module, so the default setting puts them in a single process and they run one after another, about 3 seconds in total. To spread individual test methods across workers, add --level test.
# Install into the active virtual environment
pip install unittest-parallel
# Run the example tests at test-method level using 2 worker processes
unittest-parallel -s tests -p 'test_parallel_execution.py' -j 2 --level test -vCode language: PHP (php)
Expected result: with 2 workers, two tests run at the same time and the third runs afterwards, so the suite takes about 2 seconds instead of 3. With -j 3 it drops to about 1 second. The output looks similar to this:
Running 3 test suites (3 total tests) across 2 processes
...
----------------------------------------------------------------------
Ran 3 tests in 2.0xxs
OKCode language: CSS (css)
Note: On Windows cmd.exe, single quotes are not stripped. Use -p "test_parallel_execution.py" or leave the quotes off.
How unittest-parallel works
The runner uses the standard unittest discovery machinery to find tests, groups them into suites at the level you choose, and sends those suites to a pool of worker processes. Each worker runs its suites with the normal unittest runner, and the parent process combines the results into one summary and one exit code. It uses processes rather than threads, so CPU-bound tests also speed up and are not limited by the GIL.
| –level value | Unit sent to a worker | When to use it |
|---|---|---|
module (default) | Every test in one test file | Many test files; safest when tests in a module share state |
class | Every test in one TestCase class | Large files with several independent classes |
test | A single test method | A few large classes with slow, independent methods |
A finer level spreads the load more evenly, but class and module fixtures (setUpClass, setUpModule) may run once in every process that receives tests from that class or module. If those fixtures are expensive, for example starting a container or loading a large dataset, --level test can end up slower.
Most useful options
| Option | Purpose |
|---|---|
-s START | Directory where discovery starts (default .) |
-p PATTERN | File name pattern for test files (default test*.py) |
-t TOP | Top-level directory of the project, used for imports |
-j COUNT, --jobs COUNT | Number of worker processes (defaults to the CPU count) |
--level {module,class,test} | How finely tests are split across workers |
-k PATTERN | Run only tests whose names match the pattern |
-v / -q | More or less output |
-f, --failfast | Stop on the first failure |
-b, --buffer | Hide stdout/stderr from passing tests |
--coverage | Collect coverage across all worker processes |
Run unittest-parallel --help to see the full list for your installed version.
Collecting coverage across workers
Running coverage run on a multi-process runner normally only measures the parent process. unittest-parallel has built-in coverage options that measure each worker and combine the data for you:
unittest-parallel -s tests -j 4 \
--coverage --coverage-branch \
--coverage-source src \
--coverage-html htmlcov \
--coverage-xml coverage.xml \
--coverage-fail-under 80Code language: CSS (css)
--coverage-fail-under makes the command exit non-zero when total coverage falls below the threshold, which is useful as a CI quality gate. The XML report works with most CI coverage viewers.
Using it in CI
The command exits non-zero when any test fails or errors, so it works as a CI step without extra handling. Hosted runners usually have only a few vCPUs, so set -j explicitly to match the runner size rather than counting on the default.
# .github/workflows/tests.yml (excerpt)
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r requirements.txt unittest-parallel
- run: unittest-parallel -s tests -j 4 --level class -vCode language: PHP (php)
Writing tests that are safe to run in parallel
Parallel runs expose hidden dependencies between tests. A suite that passes serially but fails at random under unittest-parallel almost always has shared state. Check for these:
- Fixed file paths: two workers writing
/tmp/output.jsonoverwrite each other. Usetempfile.TemporaryDirectory()ortempfile.mkstemp(). - Fixed network ports: bind to port
0and read back the port the OS assigned. - Shared databases: give each worker its own database or schema, or wrap each test in a transaction that is rolled back.
- Order dependence: a test must never rely on another test having run first. Tests may be scheduled in any order and in different processes.
- Module-level globals and caches: each worker is a separate process, so in-memory changes made in one test are not visible elsewhere and cannot be used to pass data between tests.
Note: Use --level module while you hunt down shared-state problems, then switch to a finer level once tests are isolated.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
error: unrecognized arguments: discover | Command copied from python -m unittest discover | Remove discover; discovery is automatic |
error: unrecognized arguments: -w | Wrong option name for worker count | Use -j N or --jobs N |
| No speed-up with several workers | Default --level module keeps a single file in one process | Add --level class or --level test |
unittest-parallel: command not found | Installed in a different environment, or scripts directory not on PATH | Activate the virtual environment that contains the package and reinstall there |
Ran 0 tests | Wrong -s directory or -p pattern, or test methods not prefixed test | Check paths, pattern and method names; compare with python -m unittest discover -s tests |
ModuleNotFoundError for your own package | Project root not importable from the workers | Set -t to the project root, or install the project with pip install -e . |
| Flaky failures only in parallel | Tests share files, ports, databases or ordering | Isolate resources as described above |
unittest-parallel compared with the alternatives
| Runner | Parallel | Notes |
|---|---|---|
python -m unittest | No | Standard library, runs serially |
unittest-parallel | Yes, multiprocess | Same CLI style as unittest, no test changes needed, built-in coverage |
pytest + pytest-xdist | Yes, pytest -n auto | Also runs unittest.TestCase classes; worth considering if you are moving to pytest |
If the project already uses plain unittest and you only want shorter runs, unittest-parallel is the smaller change. If you also want pytest fixtures, plugins and richer reports, pytest-xdist is the more common choice.
Frequently asked questions
Does Python's built-in unittest support parallel execution?
No. python -m unittest runs tests one at a time in a single process. Running them in parallel needs a third-party runner such as unittest-parallel, or pytest with pytest-xdist.
Why is unittest-parallel not faster for my single test file?
The default --level module puts every test in a file into one worker process. Use --level class or --level test so that tests from the same file can run in different processes.
How many workers should I use with unittest-parallel?
The default is the number of CPUs, which suits CPU-bound tests. Tests that mostly wait on I/O or sleep can benefit from a higher -j value. Always measure, because expensive fixtures that repeat in each process can cancel out the gain.
Do I need to change my unittest code to use unittest-parallel?
No. It runs standard unittest.TestCase classes as they are. The tests do need to be independent of each other, with no shared files, ports or databases and no reliance on run order.
Can unittest-parallel measure code coverage?
Yes. Pass --coverage, plus options such as --coverage-html, --coverage-xml and --coverage-fail-under. It collects coverage from every worker process and combines the results into one report.
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