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 example you will find a working runner script with its expected output, a corrected test module, and an explanation of why the example on its own still runs the tests one at a time.
To useย gevent-testrunnerย for parallel test execution leveraging Gevent’s asynchronous capabilities, you first need to installย gevent-testrunner. Below is a sample code demonstrating how to use it for concurrent test execution.
What the example above does and does not do
The test class above is valid unittest code, but the tests in it do not run concurrently by themselves. gevent.sleep(1) hands control to *other greenlets*. A standard runner such as python -m unittest or pytest runs each test method in turn on a single greenlet, so nothing else is waiting to run. Each test simply waits one second, and the suite takes about three seconds.
Concurrency only happens when something starts a separate greenlet for each test. That is the job of a gevent-aware runner. The example never shows the command that starts the tests either: the final line # gevent-testrunner tests is a comment, not a working command.
Note: Check that a package exists before you depend on it. gevent-testrunner is not a widely documented tool, and gevent's own gevent.testing package is built for testing gevent itself. Run pip index versions gevent-testrunner to see what PyPI offers. The runner below needs only gevent and the standard library.
Prerequisites
- Python 3 with a virtual environment
- gevent installed with
pip install gevent - Tests that spend their time on I/O (network calls, sockets, sleeps, database queries through gevent-compatible drivers). CPU-bound tests do not get faster with greenlets.
- Tests that are independent of each other, because they will run in an interleaved order
python3 -m venv .venv
source .venv/bin/activate
pip install gevent
mkdir -p tests
A corrected test module
Monkey-patching belongs in the entry point that starts first, not inside a test file. By the time a runner imports a test module, it has already imported threading, socket and often ssl, so patching at that stage is too late and can cause warnings or subtle bugs. The version below leaves patching to the runner and uses assertions that actually check something.
# tests/test_gevent_execution.py
import time
import unittest
import gevent
class TestGeventExecution(unittest.TestCase):
def _simulated_io(self, value):
gevent.sleep(1) # yields to other greenlets while "waiting"
return value * 2
def test_task_1(self):
self.assertEqual(self._simulated_io(1), 2)
def test_task_2(self):
self.assertEqual(self._simulated_io(2), 4)
def test_task_3(self):
# time.sleep is cooperative only because the runner monkey-patched it
time.sleep(1)
self.assertEqual(self._simulated_io(3), 6)
test_task_3 deliberately uses plain time.sleep. With monkey-patching active, it yields like gevent.sleep. Without patching, it blocks the whole process. This makes it a quick check that patching actually worked.
Run the tests concurrently with a gevent runner
The script below finds tests the same way python -m unittest discover does, starts each test in its own greenlet from a bounded pool, and prints a summary. Save it in the project root, next to the tests directory.
# run_tests_gevent.py
from gevent import monkey
monkey.patch_all() # must run before anything else is imported
import sys
import time
import unittest
from gevent.pool import Pool
def iter_tests(suite):
"""Flatten nested TestSuites into individual TestCase instances."""
for item in suite:
if isinstance(item, unittest.TestSuite):
yield from iter_tests(item)
else:
yield item
def main(start_dir="tests", concurrency=10):
suite = unittest.defaultTestLoader.discover(start_dir)
tests = list(iter_tests(suite))
result = unittest.TestResult()
pool = Pool(concurrency) # caps how many tests run at once
started = time.perf_counter()
for test in tests:
pool.spawn(test, result) # calling a TestCase runs it into result
pool.join()
elapsed = time.perf_counter() - started
for test, tb in result.failures + result.errors:
print(f"FAILED: {test.id()}\n{tb}")
print(f"Ran {result.testsRun} tests in {elapsed:.2f}s - "
f"failures={len(result.failures)} errors={len(result.errors)} "
f"skipped={len(result.skipped)}")
return 0 if result.wasSuccessful() else 1
if __name__ == "__main__":
sys.exit(main())Code language: PHP (php)
- Run the standard runner first to get a baseline:
python -m unittest discover -s tests -v. It reports about 4 seconds, becausetest_task_3waits twice. - Run the gevent runner:
python run_tests_gevent.py. - Compare the times. The three tests now overlap, so the total is roughly the time of the slowest test, not the sum of all of them.
$ python run_tests_gevent.py
Ran 3 tests in 2.01s - failures=0 errors=0 skipped=0
The exit code is 0 when all tests pass and 1 otherwise, so the script works as a CI step. Change concurrency to limit load on shared services such as a test database.
Note: This runner calls each test case directly, so class-level and module-level fixtures (setUpClass, setUpModule) are not run. setUp and tearDown still run. If you rely on class fixtures, move them into setUp or use a process-based runner instead.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported | patch_all() ran after another module imported ssl (often requests or urllib3) | Call monkey.patch_all() on the first lines of the entry script, before any other import |
| Total time equals the sum of all tests | Tests run under a normal runner, or the code blocks without yielding | Start tests through the gevent runner and confirm patching took effect |
| Suite hangs or runs serially despite patching | A C extension or database driver does blocking I/O that gevent cannot patch | Use a gevent-compatible driver, or run that code with gevent.threadpool |
| Random failures that pass when run alone | Tests share global state, files, ports or database rows | Isolate data per test (unique names, temp dirs, transactions) |
| No speed-up for heavy computation | Greenlets share one OS thread, so CPU-bound work cannot overlap | Use process parallelism, for example pytest-xdist |
Choosing a concurrency approach for tests
| Approach | Model | Best for | Caveat |
|---|---|---|---|
| Gevent greenlet runner (above) | Cooperative, single process | Many I/O-bound tests, code that already uses gevent | Needs monkey-patching; shared memory between tests |
pytest-xdist (pytest -n auto) | Multiple worker processes | General test suites, CPU-bound tests | Higher memory use; fixtures run once per worker |
unittest.IsolatedAsyncioTestCase | asyncio event loop per test | Testing asyncio code | Tests in a class still run one after another |
Do not mix gevent monkey-patching with asyncio-based test code in the same process unless you have tested the combination carefully. The two event models do not share a scheduler.
Best practices
- Patch once, in the entry point. Remove
monkey.patch_all()from test modules. - Keep tests independent so their order and interleaving do not matter.
- Set a sensible pool size. Unbounded concurrency can exhaust connection limits on test services.
- Add timeouts to network calls, for example with
gevent.Timeout, so a single hung test cannot block the suite. - Use concurrent runs for speed, but also run the suite serially now and then in CI to catch hidden ordering dependencies.
Frequently asked questions
Does gevent.sleep make unittest tests run in parallel?
No. gevent.sleep only yields to other greenlets that are already running. A standard runner such as python -m unittest runs one test at a time, so the tests still run sequentially unless a runner starts a separate greenlet for each test.
Where should monkey.patch_all() be called when testing with gevent?
Call it on the first lines of the script that starts the tests, before any other import. Patching inside a test module is too late, because the runner has already imported modules such as threading and ssl.
Will gevent speed up CPU-bound tests?
No. All greenlets share one OS thread, so only tests that wait on I/O overlap. For CPU-bound suites, use process-based parallelism such as pytest-xdist.
Can I use pytest instead of unittest with gevent?
pytest discovers and runs unittest-style classes, but it runs them sequentially. For parallel pytest runs, the common choice is pytest-xdist, which uses worker processes instead of greenlets.
Related tutorials
- More Python tutorials
- How to Send a POST Request with Python
- Top 50 Python Interview Questions and Answers
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