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

Switch to ThreadedChildWatcher and test (#5877) #5919

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
1 change: 1 addition & 0 deletions CHANGES/5877.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Uses :py:class:`~asyncio.ThreadedChildWatcher` under POSIX to allow setting up test loop in non-main thread.
2 changes: 1 addition & 1 deletion aiohttp/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ def setup_test_loop(
# * https://stackoverflow.com/a/58614689/595220
# * https://bugs.python.org/issue35621
# * https://github.com/python/cpython/pull/14344
watcher = asyncio.MultiLoopChildWatcher()
watcher = asyncio.ThreadedChildWatcher()
except AttributeError: # Python < 3.8
watcher = asyncio.SafeChildWatcher()
watcher.attach_loop(loop)
Expand Down
26 changes: 24 additions & 2 deletions tests/test_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
import pytest

from aiohttp import web
from aiohttp.test_utils import AioHTTPTestCase
from aiohttp.helpers import PY_38
from aiohttp.test_utils import AioHTTPTestCase, loop_context


@pytest.mark.skipif(
platform.system() == "Windows", reason="the test is not valid for Windows"
)
async def test_subprocess_co(loop) -> None:
assert isinstance(threading.current_thread(), threading._MainThread)
assert PY_38 or isinstance(threading.current_thread(), threading._MainThread)
proc = await asyncio.create_subprocess_shell(
"exit 0",
stdin=asyncio.subprocess.DEVNULL,
Expand Down Expand Up @@ -40,3 +41,24 @@ def test_default_loop(self) -> None:

def test_default_loop(loop) -> None:
assert asyncio.get_event_loop_policy().get_event_loop() is loop


@pytest.mark.xfail(not PY_38, reason="ThreadedChildWatcher is only available in 3.8+")
def test_setup_loop_non_main_thread() -> None:
child_exc = None

def target() -> None:
try:
with loop_context() as loop:
assert asyncio.get_event_loop_policy().get_event_loop() is loop
loop.run_until_complete(test_subprocess_co(loop))
except Exception as exc:
nonlocal child_exc
child_exc = exc

# Ensures setup_test_loop can be called by pytest-xdist in non-main thread.
t = threading.Thread(target=target)
t.start()
t.join()

assert child_exc is None