File tree Expand file tree Collapse file tree 2 files changed +36
-1
lines changed Expand file tree Collapse file tree 2 files changed +36
-1
lines changed Original file line number Diff line number Diff line change
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 ()
Original file line number Diff line number Diff line change @@ -18,7 +18,12 @@ def wrapped(*args, **kwargs):
18
18
import nest_asyncio # type: ignore
19
19
20
20
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
22
27
23
28
wrapped .__doc__ = coro .__doc__
24
29
return wrapped
You can’t perform that action at this time.
0 commit comments