| 1 |
import asyncio |
| 2 |
import functools |
| 3 |
import inspect |
| 4 |
import unittest |
| 5 |
|
| 6 |
|
| 7 |
class AsyncioTestCase(unittest.TestCase): |
| 8 |
""" |
| 9 |
Base class for tests that sets up an isolated event loop for each test. |
| 10 |
|
| 11 |
IsolatedAsyncioTestCase was introduced in Python 3.8 for similar purposes |
| 12 |
but isn't a drop-in replacement. |
| 13 |
|
| 14 |
""" |
| 15 |
|
| 16 |
def __init_subclass__(cls, **kwargs): |
| 17 |
""" |
| 18 |
Convert test coroutines to test functions. |
| 19 |
|
| 20 |
This supports asynchronous tests transparently. |
| 21 |
|
| 22 |
""" |
| 23 |
super().__init_subclass__(**kwargs) |
| 24 |
for name in unittest.defaultTestLoader.getTestCaseNames(cls): |
| 25 |
test = getattr(cls, name) |
| 26 |
if inspect.iscoroutinefunction(test): |
| 27 |
setattr(cls, name, cls.convert_async_to_sync(test)) |
| 28 |
|
| 29 |
@staticmethod |
| 30 |
def convert_async_to_sync(test): |
| 31 |
""" |
| 32 |
Convert a test coroutine to a test function. |
| 33 |
|
| 34 |
""" |
| 35 |
|
| 36 |
@functools.wraps(test) |
| 37 |
def test_func(self, *args, **kwargs): |
| 38 |
return self.loop.run_until_complete(test(self, *args, **kwargs)) |
| 39 |
|
| 40 |
return test_func |
| 41 |
|
| 42 |
def setUp(self): |
| 43 |
super().setUp() |
| 44 |
self.loop = asyncio.new_event_loop() |
| 45 |
asyncio.set_event_loop(self.loop) |
| 46 |
|
| 47 |
def tearDown(self): |
| 48 |
self.loop.close() |
| 49 |
super().tearDown() |
| 50 |
|
| 51 |
def run_loop_once(self): |
| 52 |
# Process callbacks scheduled with call_soon by appending a callback |
| 53 |
# to stop the event loop then running it until it hits that callback. |
| 54 |
self.loop.call_soon(self.loop.stop) |
| 55 |
self.loop.run_forever() |
| 56 |
|
| 57 |
def assertDeprecationWarnings(self, recorded_warnings, expected_warnings): |
| 58 |
""" |
| 59 |
Check recorded deprecation warnings match a list of expected messages. |
| 60 |
|
| 61 |
""" |
| 62 |
for recorded in recorded_warnings: |
| 63 |
self.assertIs(type(recorded.message), DeprecationWarning) |
| 64 |
self.assertEqual( |
| 65 |
{str(recorded.message) for recorded in recorded_warnings}, |
| 66 |
set(expected_warnings), |
| 67 |
) |