{"id":41513,"date":"2026-11-26T22:04:54","date_gmt":"2026-11-26T22:04:54","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=41513"},"modified":"2026-11-26T22:04:54","modified_gmt":"2026-11-26T22:04:54","slug":"python-test-runners-gevent-testrunner","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/python-test-runners-gevent-testrunner\/","title":{"rendered":"Python Test Runners &#8211; gevent-testrunner"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To use\u00a0<code>gevent-testrunner<\/code>\u00a0for parallel test execution leveraging Gevent&#8217;s asynchronous capabilities, you first need to install\u00a0<code>gevent-testrunner<\/code>. Below is a sample code demonstrating how to use it for concurrent test execution.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/1b0397e4c72f161247332e751dd5ea15.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What the example above does and does not do<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The test class above is valid unittest code, but the tests in it do not run concurrently by themselves. <code>gevent.sleep(1)<\/code> hands control to *other greenlets*. A standard runner such as <code>python -m unittest<\/code> or <code>pytest<\/code> 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code># gevent-testrunner tests<\/code> is a comment, not a working command.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Check that a package exists before you depend on it. <code>gevent-testrunner<\/code> is not a widely documented tool, and gevent&#039;s own <code>gevent.testing<\/code> package is built for testing gevent itself. Run <code>pip index versions gevent-testrunner<\/code> to see what PyPI offers. The runner below needs only gevent and the standard library.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Python 3 with a virtual environment<\/li>\n\n\n<li>gevent installed with <code>pip install gevent<\/code><\/li>\n\n\n<li>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.<\/li>\n\n\n<li>Tests that are independent of each other, because they will run in an interleaved order<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">python3 -m venv .venv\nsource .venv\/bin\/activate\npip install gevent\nmkdir -p tests<\/code><\/span><\/pre>\n\n\n<h2 class=\"wp-block-heading\">A corrected test module<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>threading<\/code>, <code>socket<\/code> and often <code>ssl<\/code>, 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.<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\"># tests\/test_gevent_execution.py\nimport time\nimport unittest\n\nimport gevent\n\n\nclass TestGeventExecution(unittest.TestCase):\n    def _simulated_io(self, value):\n        gevent.sleep(1)          # yields to other greenlets while \"waiting\"\n        return value * 2\n\n    def test_task_1(self):\n        self.assertEqual(self._simulated_io(1), 2)\n\n    def test_task_2(self):\n        self.assertEqual(self._simulated_io(2), 4)\n\n    def test_task_3(self):\n        # time.sleep is cooperative only because the runner monkey-patched it\n        time.sleep(1)\n        self.assertEqual(self._simulated_io(3), 6)<\/code><\/span><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><code>test_task_3<\/code> deliberately uses plain <code>time.sleep<\/code>. With monkey-patching active, it yields like <code>gevent.sleep<\/code>. Without patching, it blocks the whole process. This makes it a quick check that patching actually worked.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Run the tests concurrently with a gevent runner<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The script below finds tests the same way <code>python -m unittest discover<\/code> 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 <code>tests<\/code> directory.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># run_tests_gevent.py<\/span>\nfrom gevent import monkey\nmonkey.patch_all()  <span class=\"hljs-comment\"># must run before anything else is imported<\/span>\n\nimport sys\nimport time\nimport unittest\n\nfrom gevent.pool import Pool\n\n\ndef iter_tests(suite):\n    <span class=\"hljs-string\">\"\"<\/span><span class=\"hljs-string\">\"Flatten nested TestSuites into individual TestCase instances.\"<\/span><span class=\"hljs-string\">\"\"<\/span>\n    <span class=\"hljs-keyword\">for<\/span> item in suite:\n        <span class=\"hljs-keyword\">if<\/span> isinstance(item, unittest.TestSuite):\n            <span class=\"hljs-keyword\">yield<\/span> from iter_tests(item)\n        <span class=\"hljs-keyword\">else<\/span>:\n            <span class=\"hljs-keyword\">yield<\/span> item\n\n\ndef main(start_dir=<span class=\"hljs-string\">\"tests\"<\/span>, concurrency=<span class=\"hljs-number\">10<\/span>):\n    suite = unittest.defaultTestLoader.discover(start_dir)\n    tests = <span class=\"hljs-keyword\">list<\/span>(iter_tests(suite))\n\n    result = unittest.TestResult()\n    pool = Pool(concurrency)          <span class=\"hljs-comment\"># caps how many tests run at once<\/span>\n\n    started = time.perf_counter()\n    <span class=\"hljs-keyword\">for<\/span> test in tests:\n        pool.spawn(test, result)      <span class=\"hljs-comment\"># calling a TestCase runs it into result<\/span>\n    pool.join()\n    elapsed = time.perf_counter() - started\n\n    <span class=\"hljs-keyword\">for<\/span> test, tb in result.failures + result.errors:\n        <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"FAILED: {test.id()}\\n{tb}\"<\/span>)\n\n    <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"Ran {result.testsRun} tests in {elapsed:.2f}s - \"<\/span>\n          f<span class=\"hljs-string\">\"failures={len(result.failures)} errors={len(result.errors)} \"<\/span>\n          f<span class=\"hljs-string\">\"skipped={len(result.skipped)}\"<\/span>)\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">0<\/span> <span class=\"hljs-keyword\">if<\/span> result.wasSuccessful() <span class=\"hljs-keyword\">else<\/span> <span class=\"hljs-number\">1<\/span>\n\n\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">\"__main__\"<\/span>:\n    sys.<span class=\"hljs-keyword\">exit<\/span>(main())<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ol class=\"wp-block-list\">\n<li>Run the standard runner first to get a baseline: <code>python -m unittest discover -s tests -v<\/code>. It reports about 4 seconds, because <code>test_task_3<\/code> waits twice.<\/li>\n\n\n<li>Run the gevent runner: <code>python run_tests_gevent.py<\/code>.<\/li>\n\n\n<li>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.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">$ python run_tests_gevent.py\nRan 3 tests in 2.01s - failures=0 errors=0 skipped=0<\/code><\/span><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The exit code is 0 when all tests pass and 1 otherwise, so the script works as a CI step. Change <code>concurrency<\/code> to limit load on shared services such as a test database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> This runner calls each test case directly, so class-level and module-level fixtures (<code>setUpClass<\/code>, <code>setUpModule<\/code>) are not run. <code>setUp<\/code> and <code>tearDown<\/code> still run. If you rely on class fixtures, move them into <code>setUp<\/code> or use a process-based runner instead.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported<\/code><\/td><td><code>patch_all()<\/code> ran after another module imported <code>ssl<\/code> (often <code>requests<\/code> or <code>urllib3<\/code>)<\/td><td>Call <code>monkey.patch_all()<\/code> on the first lines of the entry script, before any other import<\/td><\/tr><tr><td>Total time equals the sum of all tests<\/td><td>Tests run under a normal runner, or the code blocks without yielding<\/td><td>Start tests through the gevent runner and confirm patching took effect<\/td><\/tr><tr><td>Suite hangs or runs serially despite patching<\/td><td>A C extension or database driver does blocking I\/O that gevent cannot patch<\/td><td>Use a gevent-compatible driver, or run that code with <code>gevent.threadpool<\/code><\/td><\/tr><tr><td>Random failures that pass when run alone<\/td><td>Tests share global state, files, ports or database rows<\/td><td>Isolate data per test (unique names, temp dirs, transactions)<\/td><\/tr><tr><td>No speed-up for heavy computation<\/td><td>Greenlets share one OS thread, so CPU-bound work cannot overlap<\/td><td>Use process parallelism, for example pytest-xdist<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Choosing a concurrency approach for tests<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Approach<\/th><th>Model<\/th><th>Best for<\/th><th>Caveat<\/th><\/tr><\/thead><tbody><tr><td>Gevent greenlet runner (above)<\/td><td>Cooperative, single process<\/td><td>Many I\/O-bound tests, code that already uses gevent<\/td><td>Needs monkey-patching; shared memory between tests<\/td><\/tr><tr><td>pytest-xdist (<code>pytest -n auto<\/code>)<\/td><td>Multiple worker processes<\/td><td>General test suites, CPU-bound tests<\/td><td>Higher memory use; fixtures run once per worker<\/td><\/tr><tr><td><code>unittest.IsolatedAsyncioTestCase<\/code><\/td><td>asyncio event loop per test<\/td><td>Testing asyncio code<\/td><td>Tests in a class still run one after another<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Patch once, in the entry point. Remove <code>monkey.patch_all()<\/code> from test modules.<\/li>\n\n\n<li>Keep tests independent so their order and interleaving do not matter.<\/li>\n\n\n<li>Set a sensible pool size. Unbounded concurrency can exhaust connection limits on test services.<\/li>\n\n\n<li>Add timeouts to network calls, for example with <code>gevent.Timeout<\/code>, so a single hung test cannot block the suite.<\/li>\n\n\n<li>Use concurrent runs for speed, but also run the suite serially now and then in CI to catch hidden ordering dependencies.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Does gevent.sleep make unittest tests run in parallel?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. <code>gevent.sleep<\/code> only yields to other greenlets that are already running. A standard runner such as <code>python -m unittest<\/code> runs one test at a time, so the tests still run sequentially unless a runner starts a separate greenlet for each test.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Where should monkey.patch_all() be called when testing with gevent?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Will gevent speed up CPU-bound tests?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I use pytest instead of unittest with gevent?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/programming\/python-programming-scripting-languages\/\">More Python tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/how-to-send-a-post-request-with-python\/\">How to Send a POST Request with Python<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-50-python-interview-questions-and-answers\/\">Top 50 Python Interview Questions and Answers<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[499],"tags":[4803,7504],"class_list":["post-41513","post","type-post","status-publish","format-standard","hentry","category-python-programming-scripting-languages","tag-test-automation","tag-unit-testing"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41513","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=41513"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41513\/revisions"}],"predecessor-version":[{"id":80308,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/41513\/revisions\/80308"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=41513"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=41513"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=41513"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}