Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Commit

Permalink
Fail test cases if they fail to await all awaitables (#8690)
Browse files Browse the repository at this point in the history
  • Loading branch information
clokep authored Oct 30, 2020
1 parent 46f4be9 commit fd7c743
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog.d/8690.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fail tests if they do not await coroutines.
34 changes: 33 additions & 1 deletion tests/test_utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
"""
Utilities for running the unit tests
"""
import sys
import warnings
from asyncio import Future
from typing import Any, Awaitable, TypeVar
from typing import Any, Awaitable, Callable, TypeVar

TV = TypeVar("TV")

Expand Down Expand Up @@ -48,3 +50,33 @@ def make_awaitable(result: Any) -> Awaitable[Any]:
future = Future() # type: ignore
future.set_result(result)
return future


def setup_awaitable_errors() -> Callable[[], None]:
"""
Convert warnings from a non-awaited coroutines into errors.
"""
warnings.simplefilter("error", RuntimeWarning)

# unraisablehook was added in Python 3.8.
if not hasattr(sys, "unraisablehook"):
return lambda: None

# State shared between unraisablehook and check_for_unraisable_exceptions.
unraisable_exceptions = []
orig_unraisablehook = sys.unraisablehook # type: ignore

def unraisablehook(unraisable):
unraisable_exceptions.append(unraisable.exc_value)

def cleanup():
"""
A method to be used as a clean-up that fails a test-case if there are any new unraisable exceptions.
"""
sys.unraisablehook = orig_unraisablehook # type: ignore
if unraisable_exceptions:
raise unraisable_exceptions.pop()

sys.unraisablehook = unraisablehook # type: ignore

return cleanup
6 changes: 5 additions & 1 deletion tests/unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
render,
setup_test_homeserver,
)
from tests.test_utils import event_injection
from tests.test_utils import event_injection, setup_awaitable_errors
from tests.test_utils.logging_setup import setup_logging
from tests.utils import default_config, setupdb

Expand Down Expand Up @@ -119,6 +119,10 @@ def tearDown(orig):

logging.getLogger().setLevel(level)

# Trial messes with the warnings configuration, thus this has to be
# done in the context of an individual TestCase.
self.addCleanup(setup_awaitable_errors())

return orig()

@around(self)
Expand Down

0 comments on commit fd7c743

Please sign in to comment.