|
1 | 1 | "A trio-enabled variant of unittest.TestCase"
|
2 | 2 | import trio
|
3 | 3 | import unittest
|
| 4 | +import contextlib |
4 | 5 | import functools
|
| 6 | +import sys |
5 | 7 | import types
|
| 8 | +import warnings |
6 | 9 | from trio._core._run import Nursery
|
7 | 10 | from rsyscall import local_process, Process
|
8 | 11 |
|
| 12 | +@contextlib.contextmanager |
| 13 | +def raise_unraisables(): |
| 14 | + unraisables = [] |
| 15 | + try: |
| 16 | + orig_unraisablehook, sys.unraisablehook = sys.unraisablehook, unraisables.append |
| 17 | + yield |
| 18 | + finally: |
| 19 | + sys.unraisablehook = orig_unraisablehook |
| 20 | + if unraisables: |
| 21 | + raise trio.MultiError([unr.exc_value for unr in unraisables]) |
| 22 | + |
9 | 23 | class TrioTestCase(unittest.TestCase):
|
10 | 24 | "A trio-enabled variant of unittest.TestCase"
|
11 | 25 | nursery: Nursery
|
@@ -43,7 +57,21 @@ async def test_with_setup() -> None:
|
43 | 57 | nursery.cancel_scope.cancel()
|
44 | 58 | @functools.wraps(test_with_setup)
|
45 | 59 | def sync_test_with_setup(self) -> None:
|
46 |
| - trio.run(test_with_setup) |
| 60 | + # Throw an exception if there were any "coroutine was never awaited" warnings, to fail the test. |
| 61 | + # See https://github.com/python-trio/pytest-trio/issues/86 |
| 62 | + # We also need raise_unraisables, otherwise the exception is suppressed, since it's in __del__ |
| 63 | + with raise_unraisables(): |
| 64 | + # Restore the old warning filter after the test. |
| 65 | + with warnings.catch_warnings(): |
| 66 | + warnings.filterwarnings('error', message='.*was never awaited', category=RuntimeWarning) |
| 67 | + trio.run(test_with_setup) |
47 | 68 | setattr(self, methodName, types.MethodType(sync_test_with_setup, self))
|
48 | 69 | super().__init__(methodName)
|
49 | 70 |
|
| 71 | +class Test(unittest.TestCase): |
| 72 | + def test_coro_warning(self) -> None: |
| 73 | + class Test(TrioTestCase): |
| 74 | + async def test(self): |
| 75 | + trio.sleep(0) |
| 76 | + with self.assertRaises(RuntimeWarning): |
| 77 | + Test('test').test() |
0 commit comments