Skip to content

Instantly share code, notes, and snippets.

@alistair-broomhead
Last active February 23, 2018 15:48
Show Gist options
  • Save alistair-broomhead/8b4d0a7df5d5a50e2ecde13a5ae55ad5 to your computer and use it in GitHub Desktop.
Save alistair-broomhead/8b4d0a7df5d5a50e2ecde13a5ae55ad5 to your computer and use it in GitHub Desktop.
Minimal async testcase runner
import asyncio
import functools
import unittest
class AsyncTest(unittest.TestCase):
def __getattribute__(self, name):
""" Hack to run async tests in the AsyncIO event loop """
original = super().__getattribute__(name)
if name.startswith('test') and asyncio.iscoroutinefunction(original):
@functools.wraps(original)
def wrapped(*args, **kwargs):
return self._loop.run_until_complete(
original(*args, **kwargs)
)
setattr(self, name, wrapped)
return wrapped
return original
def setUp(self):
self._loop = asyncio.new_event_loop()
def tearDown(self):
if self._loop.is_running():
self._loop.stop()
if not self._loop.is_closed():
self._loop.close()
class TestExample(AsyncTest):
# Passes
def test_normal_tests_work(self):
pass
# Fails
def test_normal_tests_can_fail(self):
assert False
# Passes
async def test_async_tests_work(self):
pass
# Fails
async def test_async_tests_can_fail(self):
assert False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment