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 – unittest-parallel

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 valueUnit sent to a workerWhen to use it
module (default)Every test in one test fileMany test files; safest when tests in a module share state
classEvery test in one TestCase classLarge files with several independent classes
testA single test methodA 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

OptionPurpose
-s STARTDirectory where discovery starts (default .)
-p PATTERNFile name pattern for test files (default test*.py)
-t TOPTop-level directory of the project, used for imports
-j COUNT, --jobs COUNTNumber of worker processes (defaults to the CPU count)
--level {module,class,test}How finely tests are split across workers
-k PATTERNRun only tests whose names match the pattern
-v / -qMore or less output
-f, --failfastStop on the first failure
-b, --bufferHide stdout/stderr from passing tests
--coverageCollect 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.json overwrite each other. Use tempfile.TemporaryDirectory() or tempfile.mkstemp().
  • Fixed network ports: bind to port 0 and 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

SymptomCauseFix
error: unrecognized arguments: discoverCommand copied from python -m unittest discoverRemove discover; discovery is automatic
error: unrecognized arguments: -wWrong option name for worker countUse -j N or --jobs N
No speed-up with several workersDefault --level module keeps a single file in one processAdd --level class or --level test
unittest-parallel: command not foundInstalled in a different environment, or scripts directory not on PATHActivate the virtual environment that contains the package and reinstall there
Ran 0 testsWrong -s directory or -p pattern, or test methods not prefixed testCheck paths, pattern and method names; compare with python -m unittest discover -s tests
ModuleNotFoundError for your own packageProject root not importable from the workersSet -t to the project root, or install the project with pip install -e .
Flaky failures only in parallelTests share files, ports, databases or orderingIsolate resources as described above

unittest-parallel compared with the alternatives

RunnerParallelNotes
python -m unittestNoStandard library, runs serially
unittest-parallelYes, multiprocessSame CLI style as unittest, no test changes needed, built-in coverage
pytest + pytest-xdistYes, pytest -n autoAlso 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

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

Read More

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-xdist

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…

Read More

Python Test Runners – pytest-trio

pytest-trio is a pytest plugin that runs async def tests and fixtures inside a Trio event loop, so you can test Trio code without calling trio.run() yourself….

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
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x