Skip to content

Commit 818f2a7

Browse files
committed
Make sure just_run doesn't leak file descriptors of new loops.
1 parent 9a877a1 commit 818f2a7

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

nbclient/tests/test_util.py

+16
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import unittest.mock
23
from unittest.mock import MagicMock
34

45
import psutil
@@ -94,3 +95,18 @@ async def async_sleep():
9495
just_run(async_sleep())
9596
diff.append(proc.num_fds() - fds_count)
9697
assert diff == [0] * 10
98+
99+
100+
def test_just_run_clears_new_loop():
101+
async def async_sleep():
102+
await asyncio.sleep(0.1)
103+
104+
loop = asyncio.new_event_loop()
105+
loop.stop = MagicMock(wraps=loop.stop)
106+
loop.close = MagicMock(wraps=loop.close)
107+
108+
with unittest.mock.patch.object(asyncio, "new_event_loop", return_value=loop):
109+
just_run(async_sleep())
110+
111+
loop.stop.assert_called_once
112+
loop.close.assert_called_once

nbclient/util.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,11 @@ def just_run(coro: Awaitable) -> Any:
5757

5858
nest_asyncio.apply()
5959
check_patch_tornado()
60-
return loop.run_until_complete(coro)
60+
res = loop.run_until_complete(coro)
61+
if not had_running_loop:
62+
loop.stop()
63+
loop.close()
64+
return res
6165

6266

6367
T = TypeVar("T")

0 commit comments

Comments
 (0)