Debian Codegraph @

tests/trio/utils.py

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