|
| 1 | +import functools |
| 2 | +import inspect |
| 3 | +import sys |
| 4 | +import unittest |
| 5 | + |
| 6 | +import trio.testing |
| 7 | + |
| 8 | + |
| 9 | +if sys.version_info[:2] < (3, 11): # pragma: no cover |
| 10 | + from exceptiongroup import BaseExceptionGroup |
| 11 | + |
| 12 | + |
| 13 | +class IsolatedTrioTestCase(unittest.TestCase): |
| 14 | + """ |
| 15 | + Wrap test coroutines with :func:`trio.testing.trio_test` automatically. |
| 16 | +
|
| 17 | + Create a nursery for each test, available in the :attr:`nursery` attribute. |
| 18 | +
|
| 19 | + :meth:`asyncSetUp` and :meth:`asyncTearDown` are supported, similar to |
| 20 | + :class:`unittest.IsolatedAsyncioTestCase`, but ``addAsyncCleanup`` isn't. |
| 21 | +
|
| 22 | + """ |
| 23 | + |
| 24 | + def __init_subclass__(cls, **kwargs): |
| 25 | + super().__init_subclass__(**kwargs) |
| 26 | + for name in unittest.defaultTestLoader.getTestCaseNames(cls): |
| 27 | + test = getattr(cls, name) |
| 28 | + if getattr(test, "converted_to_trio", False): |
| 29 | + return |
| 30 | + assert inspect.iscoroutinefunction(test) |
| 31 | + setattr(cls, name, cls.convert_to_trio(test)) |
| 32 | + |
| 33 | + @staticmethod |
| 34 | + def convert_to_trio(test): |
| 35 | + @trio.testing.trio_test |
| 36 | + @functools.wraps(test) |
| 37 | + async def new_test(self, *args, **kwargs): |
| 38 | + try: |
| 39 | + # Provide a nursery so it's easy to start tasks. |
| 40 | + async with trio.open_nursery() as self.nursery: |
| 41 | + await self.asyncSetUp() |
| 42 | + try: |
| 43 | + return await test(self, *args, **kwargs) |
| 44 | + finally: |
| 45 | + await self.asyncTearDown() |
| 46 | + except BaseExceptionGroup as exc: |
| 47 | + # Unwrap exceptions like unittest.SkipTest. Multiple exceptions |
| 48 | + # could occur is a test fails with multiple errors; this is OK; |
| 49 | + # raise the original exception group in that case. |
| 50 | + try: |
| 51 | + trio._util.raise_single_exception_from_group(exc) |
| 52 | + except trio._util.MultipleExceptionError: # pragma: no cover |
| 53 | + raise exc |
| 54 | + |
| 55 | + new_test.converted_to_trio = True |
| 56 | + return new_test |
| 57 | + |
| 58 | + async def asyncSetUp(self): |
| 59 | + pass |
| 60 | + |
| 61 | + async def asyncTearDown(self): |
| 62 | + pass |
0 commit comments