Skip to content

Commit 5b57015

Browse files
author
Steven Silvester
authored
Merge pull request #697 from shingo78/fix/run_sync-clean-up-pending-task
Clean up the pending task
2 parents 5b2a485 + f84c8b4 commit 5b57015

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

jupyter_client/tests/test_utils.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import asyncio
2+
from unittest import mock
3+
4+
import pytest
5+
6+
from jupyter_client.utils import run_sync
7+
8+
9+
@pytest.fixture
10+
def loop():
11+
loop = asyncio.new_event_loop()
12+
asyncio.set_event_loop(loop)
13+
return loop
14+
15+
16+
def test_run_sync_clean_up_task(loop):
17+
async def coro_never_called():
18+
pytest.fail("The call to this coroutine is not expected")
19+
20+
# Ensure that run_sync cancels the pending task
21+
with mock.patch.object(loop, "run_until_complete") as patched_loop:
22+
patched_loop.side_effect = KeyboardInterrupt
23+
with mock.patch("asyncio.ensure_future") as patched_ensure_future:
24+
mock_future = mock.Mock()
25+
patched_ensure_future.return_value = mock_future
26+
with pytest.raises(KeyboardInterrupt):
27+
run_sync(coro_never_called)()
28+
mock_future.cancel.assert_called_once()
29+
# Suppress 'coroutine ... was never awaited' warning
30+
patched_ensure_future.call_args[0][0].close()

jupyter_client/utils.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,12 @@ def wrapped(*args, **kwargs):
1818
import nest_asyncio # type: ignore
1919

2020
nest_asyncio.apply(loop)
21-
return loop.run_until_complete(coro(*args, **kwargs))
21+
future = asyncio.ensure_future(coro(*args, **kwargs))
22+
try:
23+
return loop.run_until_complete(future)
24+
except BaseException as e:
25+
future.cancel()
26+
raise e
2227

2328
wrapped.__doc__ = coro.__doc__
2429
return wrapped

0 commit comments

Comments
 (0)