Scrapy, a fast high-level web crawling & scraping framework for Python.
Fail leaked aiohttp sessions in place, close subprocess on failed expect (#8194)
Adrianebec11a6e969
diff --git a/conftest.py b/conftest.pyindex cd0fd6fce..0c76d86cc 100644--- a/conftest.py+++ b/conftest.py@@ -3,7 +3,8 @@ from __future__ import annotationsimport osfrom importlib.util import find_specfrom pathlib import Path-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Any+from weakref import WeakSetimport pytestfrom twisted.web.http import H2_ENABLED@@ -15,8 +16,13 @@ from tests.keys import generate_keysfrom tests.mockserver.http import MockServerfrom tests.mockserver.mitm_proxy import MitmProxy, mitmdump_cmd+try:+ import aiohttp+except ImportError:+ aiohttp = None+if TYPE_CHECKING:- from collections.abc import Generator+ from collections.abc import Generator, Iteratordef _py_files(folder):@@ -81,6 +87,55 @@ def fast_engine_heartbeat(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(ExecutionEngine, "_SLOT_HEARTBEAT_INTERVAL", 0.1)+_aiohttp_sessions: WeakSet[aiohttp.ClientSession] = WeakSet()++[email protected](autouse=True, scope="session")+def _track_aiohttp_sessions() -> Iterator[None]:+ if aiohttp is None:+ yield+ return+ original_init = aiohttp.ClientSession.__init__++ def init(self: aiohttp.ClientSession, *args: Any, **kwargs: Any) -> None:+ original_init(self, *args, **kwargs)+ _aiohttp_sessions.add(self)++ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(aiohttp.ClientSession, "__init__", init)+ yield++[email protected](autouse=True)+def _fail_on_unclosed_aiohttp_session(+ caplog: pytest.LogCaptureFixture,+) -> Iterator[None]:+ """Fail the test that leaks an aiohttp ``ClientSession`` instead of a+ later, unrelated one.++ A leaked session usually sits in a reference cycle with its crawler, so it+ is still alive at teardown and can be checked directly. One that was+ already collected during the test reported itself through+ ``ClientSession.__del__()``, which logs to the asyncio logger rather than+ through the warnings module. Under the ``none`` reactor, any test that+ downloads over HTTP or HTTPS can end up going through+ :class:`~scrapy.core.downloader.handlers._aiohttp.AiohttpDownloadHandler`,+ not only the tests that target it directly, so this runs for every test+ rather than a single module.+ """+ yield+ unclosed = [session for session in _aiohttp_sessions if not session.closed]+ _aiohttp_sessions.clear()+ reported = [+ record.message+ for when in ("setup", "call", "teardown")+ for record in caplog.get_records(when)+ if record.name == "asyncio" and "Unclosed" in record.message+ ]+ assert not unclosed+ assert not reported++@pytest.fixture(scope="session")def mockserver() -> Generator[MockServer]:with MockServer() as mockserver:diff --git a/tests/test_crawler_subprocess.py b/tests/test_crawler_subprocess.pyindex 78cfc8465..1ff4de66a 100644--- a/tests/test_crawler_subprocess.py+++ b/tests/test_crawler_subprocess.py@@ -257,20 +257,22 @@ class TestCrawlerProcessSubprocessBase(ScriptRunnerMixin):sig = signal.SIGINT if sys.platform != "win32" else signal.SIGBREAK # type: ignore[attr-defined,unused-ignore]args = self.get_script_args(script, "10")p = PopenSpawn(args, timeout=SCRIPT_TIMEOUT, env=get_script_run_env())- p.expect_exact("Spider opened")- p.expect_exact("Crawled (200)")- p.kill(sig)- p.expect_exact("shutting down gracefully")- # Sending a new signal too fast often causes problems, e.g. on- # Windows, where signal delivery is slower and more variable than on- # POSIX.- await sleep(0.1)- p.kill(sig)- p.expect_exact("dropping downloader requests")- await sleep(0.1)- p.kill(sig)- p.expect_exact("forcing unclean shutdown", timeout=20)- stop_spawn(p)+ try:+ p.expect_exact("Spider opened")+ p.expect_exact("Crawled (200)")+ p.kill(sig)+ p.expect_exact("shutting down gracefully")+ # Sending a new signal too fast often causes problems, e.g. on+ # Windows, where signal delivery is slower and more variable than+ # on POSIX.+ await sleep(0.1)+ p.kill(sig)+ p.expect_exact("dropping downloader requests")+ await sleep(0.1)+ p.kill(sig)+ p.expect_exact("forcing unclean shutdown", timeout=20)+ finally:+ stop_spawn(p)@coroutine_testasync def test_shutdown_forced(self) -> None: