Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up the pending task #697

Merged
merged 3 commits into from
Sep 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions jupyter_client/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import asyncio
from unittest import mock

import pytest

from jupyter_client.utils import run_sync


@pytest.fixture
def loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop


def test_run_sync_clean_up_task(loop):
async def coro_never_called():
pytest.fail("The call to this coroutine is not expected")

# Ensure that run_sync cancels the pending task
with mock.patch.object(loop, "run_until_complete") as patched_loop:
patched_loop.side_effect = KeyboardInterrupt
with mock.patch("asyncio.ensure_future") as patched_ensure_future:
mock_future = mock.Mock()
patched_ensure_future.return_value = mock_future
with pytest.raises(KeyboardInterrupt):
run_sync(coro_never_called)()
mock_future.cancel.assert_called_once()
# Suppress 'coroutine ... was never awaited' warning
patched_ensure_future.call_args[0][0].close()
7 changes: 6 additions & 1 deletion jupyter_client/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ def wrapped(*args, **kwargs):
import nest_asyncio # type: ignore

nest_asyncio.apply(loop)
return loop.run_until_complete(coro(*args, **kwargs))
future = asyncio.ensure_future(coro(*args, **kwargs))
try:
return loop.run_until_complete(future)
except BaseException as e:
future.cancel()
raise e

wrapped.__doc__ = coro.__doc__
return wrapped
Expand Down