Created
December 30, 2017 23:49
-
-
Save jessedhillon/f178946b241ae0b678cf13ad0a6ed45a to your computer and use it in GitHub Desktop.
Python3 unittest.TestCase with asyncio support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import unittest | |
def immediately(coro): | |
f = lambda self, *args, **kwargs: self.loop.run_until_complete(coro(self, *args, **kwargs)) | |
f.__name__ = coro.__name__ | |
return f | |
class AsyncTestCase(type): | |
def __new__(cls, name, bases, defs): | |
defs.update({ | |
k: immediately(f) | |
for k, f in defs.items() | |
if asyncio.coroutines.iscoroutinefunction(f) | |
}) | |
return type.__new__(cls, name, bases, defs) | |
class BaseTestCase(unittest.TestCase, metaclass=AsyncTestCase): | |
def setUp(self): | |
self.loop = asyncio.get_event_loop() | |
class EventTestCase(BaseTestCase): | |
def setUp(self): | |
self.event = asyncio.Event() | |
super(EventTestCase, self).setUp() | |
# this is a coroutine function, and will be replaced with a function | |
# which immediately runs it in self.loop | |
async def test_event(self): | |
self.loop.call_later(1, lambda: self.event.set()) | |
await self.event.wait() | |
self.assertTrue(self.event.is_set()) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment