From 129ef25e0fe302d4ffbfae8f5ef3f2af05efeca2 Mon Sep 17 00:00:00 2001 From: Sam Bull Date: Mon, 20 Apr 2026 19:21:36 +0100 Subject: [PATCH] Backport more pytest-asyncio changes (#12402) --- aiohttp/pytest_plugin.py | 6 +- tests/conftest.py | 9 +- tests/test_client_proto.py | 89 +++-- tests/test_client_request.py | 327 ++++++----------- tests/test_client_response.py | 112 +++--- tests/test_client_session.py | 51 +-- tests/test_client_ws.py | 202 ++++------- tests/test_client_ws_functional.py | 9 +- tests/test_connector.py | 463 +++++++++++-------------- tests/test_helpers.py | 41 +-- tests/test_http_parser.py | 10 +- tests/test_http_writer.py | 452 ++++++++---------------- tests/test_proxy_functional.py | 11 +- tests/test_resolver.py | 39 +-- tests/test_streams.py | 2 +- tests/test_test_utils.py | 41 +-- tests/test_urldispatch.py | 9 +- tests/test_web_middleware.py | 31 +- tests/test_web_server.py | 36 +- tests/test_web_websocket.py | 45 +-- tests/test_web_websocket_functional.py | 179 +++------- tests/test_worker.py | 11 +- 22 files changed, 787 insertions(+), 1388 deletions(-) diff --git a/aiohttp/pytest_plugin.py b/aiohttp/pytest_plugin.py index 65f8dc8aa7f..98aff019bf0 100644 --- a/aiohttp/pytest_plugin.py +++ b/aiohttp/pytest_plugin.py @@ -199,8 +199,10 @@ def _passthrough_loop_context( else: # this shadows loop_context's standard behavior loop = setup_test_loop() - yield loop - teardown_test_loop(loop, fast=fast) + try: + yield loop + finally: + teardown_test_loop(loop, fast=fast) def pytest_pycollect_makeitem(collector, name, obj): # type: ignore[no-untyped-def] diff --git a/tests/conftest.py b/tests/conftest.py index 336c0e14d40..2a9fcaaaf44 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -37,7 +37,7 @@ from aiohttp.compression_utils import ZLibBackend, ZLibBackendProtocol, set_zlib_backend from aiohttp.helpers import TimerNoop from aiohttp.http import WS_KEY, HttpVersion11 -from aiohttp.test_utils import get_unused_port_socket, loop_context +from aiohttp.test_utils import REUSE_ADDRESS, loop_context def pytest_configure(config: pytest.Config) -> None: @@ -387,11 +387,8 @@ def unused_port_socket() -> Iterator[socket.socket]: race condition between checking if the port is in use and binding to it later in the test. """ - s = get_unused_port_socket("127.0.0.1") - try: + with socket.create_server(("127.0.0.1", 0), reuse_port=REUSE_ADDRESS) as s: yield s - finally: - s.close() @pytest.fixture(params=["zlib", "zlib_ng.zlib_ng", "isal.isal_zlib"]) @@ -433,7 +430,7 @@ def maker( session = ClientSession() sessions.append(session) default_args: ClientRequestArgs = { - "loop": loop, + "loop": asyncio.get_running_loop(), "params": {}, "headers": CIMultiDict[str](), "skip_auto_headers": None, diff --git a/tests/test_client_proto.py b/tests/test_client_proto.py index 0a26a211453..afabd9f86ed 100644 --- a/tests/test_client_proto.py +++ b/tests/test_client_proto.py @@ -13,19 +13,19 @@ from aiohttp.http_parser import HttpParser, RawResponseMessage -async def test_force_close(loop: asyncio.AbstractEventLoop) -> None: +async def test_force_close() -> None: """Ensure that the force_close method sets the should_close attribute to True. This is used externally in aiodocker https://github.com/aio-libs/aiodocker/issues/920 """ - proto = ResponseHandler(loop=loop) + proto = ResponseHandler(loop=asyncio.get_running_loop()) proto.force_close() assert proto.should_close -async def test_oserror(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +async def test_oserror() -> None: + proto = ResponseHandler(loop=asyncio.get_running_loop()) transport = mock.Mock() proto.connection_made(transport) proto.connection_lost(OSError()) @@ -34,9 +34,9 @@ async def test_oserror(loop: asyncio.AbstractEventLoop) -> None: assert isinstance(proto.exception(), ClientOSError) -async def test_pause_resume_on_error(loop: asyncio.AbstractEventLoop) -> None: +async def test_pause_resume_on_error() -> None: parser = mock.create_autospec(HttpParser, spec_set=True, instance=True) - proto = ResponseHandler(loop=loop) + proto = ResponseHandler(loop=asyncio.get_running_loop()) proto._parser = parser transport = mock.Mock() proto.connection_made(transport) @@ -48,8 +48,8 @@ async def test_pause_resume_on_error(loop: asyncio.AbstractEventLoop) -> None: assert not proto._reading_paused -async def test_client_proto_bad_message(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +async def test_client_proto_bad_message() -> None: + proto = ResponseHandler(loop=asyncio.get_running_loop()) transport = mock.Mock() proto.connection_made(transport) proto.set_response_params() @@ -60,8 +60,8 @@ async def test_client_proto_bad_message(loop: asyncio.AbstractEventLoop) -> None assert isinstance(proto.exception(), http.HttpProcessingError) -async def test_uncompleted_message(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +async def test_uncompleted_message() -> None: + proto = ResponseHandler(loop=asyncio.get_running_loop()) transport = mock.Mock() proto.connection_made(transport) proto.set_response_params(read_until_eof=True) @@ -78,8 +78,8 @@ async def test_uncompleted_message(loop: asyncio.AbstractEventLoop) -> None: assert dict(exc.message.headers) == {"Location": "http://python.org/"} -async def test_data_received_after_close(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +async def test_data_received_after_close() -> None: + proto = ResponseHandler(loop=asyncio.get_running_loop()) transport = mock.Mock() proto.connection_made(transport) proto.set_response_params(read_until_eof=True) @@ -92,9 +92,8 @@ async def test_data_received_after_close(loop: asyncio.AbstractEventLoop) -> Non assert isinstance(proto.exception(), http.HttpProcessingError) -async def test_multiple_responses_one_byte_at_a_time( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_multiple_responses_one_byte_at_a_time() -> None: + loop = asyncio.get_running_loop() proto = ResponseHandler(loop=loop) proto.connection_made(mock.Mock()) conn = mock.Mock(protocol=proto) @@ -128,9 +127,8 @@ async def test_multiple_responses_one_byte_at_a_time( await response.read() == payload -async def test_unexpected_exception_during_data_received( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_unexpected_exception_during_data_received() -> None: + loop = asyncio.get_running_loop() proto = ResponseHandler(loop=loop) class PatchableHttpResponseParser(http.HttpResponseParser): @@ -164,7 +162,8 @@ class PatchableHttpResponseParser(http.HttpResponseParser): assert isinstance(proto.exception(), http.HttpProcessingError) -async def test_client_protocol_readuntil_eof(loop: asyncio.AbstractEventLoop) -> None: +async def test_client_protocol_readuntil_eof() -> None: + loop = asyncio.get_running_loop() proto = ResponseHandler(loop=loop) transport = mock.Mock() proto.connection_made(transport) @@ -203,23 +202,23 @@ async def test_client_protocol_readuntil_eof(loop: asyncio.AbstractEventLoop) -> assert response.content.is_eof() -async def test_empty_data(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +async def test_empty_data() -> None: + proto = ResponseHandler(loop=asyncio.get_running_loop()) proto.data_received(b"") # do nothing -async def test_schedule_timeout(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +async def test_schedule_timeout() -> None: + proto = ResponseHandler(loop=asyncio.get_running_loop()) proto.set_response_params(read_timeout=1) assert proto._read_timeout_handle is None proto.start_timeout() assert proto._read_timeout_handle is not None -async def test_drop_timeout(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +async def test_drop_timeout() -> None: + proto = ResponseHandler(loop=asyncio.get_running_loop()) proto.set_response_params(read_timeout=1) proto.start_timeout() assert proto._read_timeout_handle is not None @@ -227,8 +226,8 @@ async def test_drop_timeout(loop: asyncio.AbstractEventLoop) -> None: assert proto._read_timeout_handle is None -async def test_reschedule_timeout(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +async def test_reschedule_timeout() -> None: + proto = ResponseHandler(loop=asyncio.get_running_loop()) proto.set_response_params(read_timeout=1) proto.start_timeout() assert proto._read_timeout_handle is not None @@ -238,8 +237,8 @@ async def test_reschedule_timeout(loop: asyncio.AbstractEventLoop) -> None: assert proto._read_timeout_handle is not h -async def test_eof_received(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +async def test_eof_received() -> None: + proto = ResponseHandler(loop=asyncio.get_running_loop()) proto.set_response_params(read_timeout=1) proto.start_timeout() assert proto._read_timeout_handle is not None @@ -247,14 +246,12 @@ async def test_eof_received(loop: asyncio.AbstractEventLoop) -> None: assert proto._read_timeout_handle is None -async def test_connection_lost_sets_transport_to_none( - loop: asyncio.AbstractEventLoop, mocker: MockerFixture -) -> None: +async def test_connection_lost_sets_transport_to_none(mocker: MockerFixture) -> None: """Ensure that the transport is set to None when the connection is lost. This ensures the writer knows that the connection is closed. """ - proto = ResponseHandler(loop=loop) + proto = ResponseHandler(loop=asyncio.get_running_loop()) proto.connection_made(mocker.Mock()) assert proto.transport is not None @@ -263,11 +260,9 @@ async def test_connection_lost_sets_transport_to_none( assert proto.transport is None -async def test_connection_lost_exception_is_marked_retrieved( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_connection_lost_exception_is_marked_retrieved() -> None: """Test that connection_lost properly handles exceptions without warnings.""" - proto = ResponseHandler(loop=loop) + proto = ResponseHandler(loop=asyncio.get_running_loop()) proto.connection_made(mock.Mock()) # Access closed property before connection_lost to ensure future is created @@ -286,11 +281,9 @@ async def test_connection_lost_exception_is_marked_retrieved( assert exc.__cause__ is ssl_error -async def test_closed_property_lazy_creation( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_closed_property_lazy_creation() -> None: """Test that closed future is created lazily.""" - proto = ResponseHandler(loop=loop) + proto = ResponseHandler(loop=asyncio.get_running_loop()) # Initially, the closed future should not be created assert proto._closed is None @@ -305,11 +298,9 @@ async def test_closed_property_lazy_creation( assert proto.closed is closed_future -async def test_closed_property_after_connection_lost( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_closed_property_after_connection_lost() -> None: """Test that closed property returns None after connection_lost if never accessed.""" - proto = ResponseHandler(loop=loop) + proto = ResponseHandler(loop=asyncio.get_running_loop()) proto.connection_made(mock.Mock()) # Don't access proto.closed before connection_lost @@ -319,9 +310,9 @@ async def test_closed_property_after_connection_lost( assert proto.closed is None -async def test_abort(loop: asyncio.AbstractEventLoop) -> None: +async def test_abort() -> None: """Test the abort() method.""" - proto = ResponseHandler(loop=loop) + proto = ResponseHandler(loop=asyncio.get_running_loop()) # Create a mock transport transport = mock.Mock() @@ -345,9 +336,9 @@ async def test_abort(loop: asyncio.AbstractEventLoop) -> None: mock_drop_timeout.assert_called_once() -async def test_abort_without_transport(loop: asyncio.AbstractEventLoop) -> None: +async def test_abort_without_transport() -> None: """Test abort() when transport is None.""" - proto = ResponseHandler(loop=loop) + proto = ResponseHandler(loop=asyncio.get_running_loop()) # Mock _drop_timeout method using patch.object with mock.patch.object(proto, "_drop_timeout") as mock_drop_timeout: diff --git a/tests/test_client_request.py b/tests/test_client_request.py index 7c7ce14fc2e..751deaa8f18 100644 --- a/tests/test_client_request.py +++ b/tests/test_client_request.py @@ -640,19 +640,16 @@ async def test_gen_netloc_no_port(make_client_request: _RequestMaker) -> None: ) -async def test_cookie_coded_value_preserved( - loop: asyncio.AbstractEventLoop, - make_client_request: _RequestMaker, -) -> None: +async def test_cookie_coded_value_preserved(make_client_request: _RequestMaker) -> None: """Verify the coded value of a cookie is preserved.""" # https://github.com/aio-libs/aiohttp/pull/1453 + loop = asyncio.get_running_loop() req = make_client_request("get", URL("http://python.org"), loop=loop) req._update_cookies(cookies=SimpleCookie('ip-cookie="second"; Domain=127.0.0.1;')) assert req.headers["COOKIE"] == 'ip-cookie="second"' async def test_update_cookies_with_special_chars_in_existing_header( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: """Test that update_cookies handles existing cookies with special characters.""" @@ -663,7 +660,7 @@ async def test_update_cookies_with_special_chars_in_existing_header( headers=CIMultiDict( {"Cookie": "ISAWPLB{A7F52349-3531-4DA9-8776-F74BC6F4F1BB}=value1"} ), - loop=loop, + loop=asyncio.get_running_loop(), ) # Update with another cookie @@ -677,7 +674,6 @@ async def test_update_cookies_with_special_chars_in_existing_header( async def test_update_cookies_with_quoted_existing_header( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: """Test that update_cookies handles existing cookies with quoted values.""" @@ -686,7 +682,7 @@ async def test_update_cookies_with_quoted_existing_header( "get", URL("http://python.org"), headers=CIMultiDict({"Cookie": 'session="value;with;semicolon"; token=abc123'}), - loop=loop, + loop=asyncio.get_running_loop(), ) # Update with another cookie @@ -701,10 +697,9 @@ async def test_update_cookies_with_quoted_existing_header( async def test_connection_header( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request("get", URL("http://python.org"), loop=loop) req.headers.clear() @@ -734,10 +729,9 @@ async def test_connection_header( async def test_no_content_length( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request("get", URL("http://python.org"), loop=loop) resp = await req._send(conn) assert req.headers.get("CONTENT-LENGTH") is None @@ -746,10 +740,9 @@ async def test_no_content_length( async def test_no_content_length_head( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request("head", URL("http://python.org"), loop=loop) resp = await req._send(conn) assert req.headers.get("CONTENT-LENGTH") is None @@ -758,10 +751,9 @@ async def test_no_content_length_head( async def test_content_type_auto_header_get( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request("get", URL("http://python.org"), loop=loop) resp = await req._send(conn) assert "CONTENT-TYPE" not in req.headers @@ -770,10 +762,9 @@ async def test_content_type_auto_header_get( async def test_content_type_auto_header_form( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request( "post", URL("http://python.org"), data={"hey": "you"}, loop=loop ) @@ -783,10 +774,9 @@ async def test_content_type_auto_header_form( async def test_content_type_auto_header_bytes( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request( "post", URL("http://python.org"), data=b"hey you", loop=loop ) @@ -796,16 +786,14 @@ async def test_content_type_auto_header_bytes( async def test_content_type_skip_auto_header_bytes( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: req = make_client_request( "post", URL("http://python.org"), data=b"hey you", skip_auto_headers={"Content-Type"}, - loop=loop, + loop=asyncio.get_running_loop(), ) assert req.skip_auto_headers == CIMultiDict({"CONTENT-TYPE": None}) resp = await req._send(conn) @@ -814,15 +802,13 @@ async def test_content_type_skip_auto_header_bytes( async def test_content_type_skip_auto_header_form( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: req = make_client_request( "post", URL("http://python.org"), data={"hey": "you"}, - loop=loop, + loop=asyncio.get_running_loop(), skip_auto_headers={"Content-Type"}, ) resp = await req._send(conn) @@ -831,9 +817,7 @@ async def test_content_type_skip_auto_header_form( async def test_content_type_auto_header_content_length_no_skip( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: with io.BytesIO(b"hey") as file_handle: req = make_client_request( @@ -841,7 +825,7 @@ async def test_content_type_auto_header_content_length_no_skip( URL("http://python.org"), data=file_handle, skip_auto_headers={"Content-Length"}, - loop=loop, + loop=asyncio.get_running_loop(), ) resp = await req._send(conn) assert req.headers.get("CONTENT-LENGTH") == "3" @@ -849,15 +833,13 @@ async def test_content_type_auto_header_content_length_no_skip( async def test_urlencoded_formdata_charset( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: req = make_client_request( "post", URL("http://python.org"), data=aiohttp.FormData({"hey": "you"}, charset="koi8-r"), - loop=loop, + loop=asyncio.get_running_loop(), ) async with await req._send(conn): await asyncio.sleep(0) @@ -867,9 +849,7 @@ async def test_urlencoded_formdata_charset( async def test_formdata_boundary_from_headers( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: boundary = "some_boundary" file_path = pathlib.Path(__file__).parent / "aiohttp.png" @@ -881,7 +861,7 @@ async def test_formdata_boundary_from_headers( headers=CIMultiDict( {"Content-Type": f"multipart/form-data; boundary={boundary}"} ), - loop=loop, + loop=asyncio.get_running_loop(), ) async with await req._send(conn): await asyncio.sleep(0) @@ -889,11 +869,8 @@ async def test_formdata_boundary_from_headers( assert req.body._boundary == boundary.encode() -async def test_post_data( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, -) -> None: +async def test_post_data(conn: mock.Mock, make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() for meth in ClientRequest.POST_METHODS: req = make_client_request( meth, URL("http://python.org/"), data={"life": "42"}, loop=loop @@ -907,10 +884,8 @@ async def test_post_data( resp.close() -async def test_pass_falsy_data( - loop: asyncio.AbstractEventLoop, - make_client_request: _RequestMaker, -) -> None: +async def test_pass_falsy_data(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() with mock.patch("aiohttp.client_reqrep.ClientRequest._update_body_from_data") as m: req = make_client_request("post", URL("http://python.org/"), data={}, loop=loop) m.assert_called_once_with({}) @@ -918,9 +893,7 @@ async def test_pass_falsy_data( async def test_pass_falsy_data_file( - loop: asyncio.AbstractEventLoop, - tmp_path: pathlib.Path, - make_client_request: _RequestMaker, + tmp_path: pathlib.Path, make_client_request: _RequestMaker ) -> None: testfile = (tmp_path / "tmpfile").open("w+b") testfile.write(b"data") @@ -931,7 +904,7 @@ async def test_pass_falsy_data_file( URL("http://python.org/"), data=testfile, skip_auto_headers=skip, - loop=loop, + loop=asyncio.get_running_loop(), ) assert req.headers.get("CONTENT-LENGTH", None) is not None await req._close() @@ -939,10 +912,8 @@ async def test_pass_falsy_data_file( # Elasticsearch API requires to send request body with GET-requests -async def test_get_with_data( - loop: asyncio.AbstractEventLoop, - make_client_request: _RequestMaker, -) -> None: +async def test_get_with_data(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() for meth in ClientRequest.GET_METHODS: req = make_client_request( meth, URL("http://python.org/"), data={"life": "42"}, loop=loop @@ -953,11 +924,8 @@ async def test_get_with_data( await req._close() -async def test_bytes_data( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, -) -> None: +async def test_bytes_data(conn: mock.Mock, make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() for meth in ClientRequest.POST_METHODS: req = make_client_request( meth, URL("http://python.org/"), data=b"binary data", loop=loop @@ -973,10 +941,9 @@ async def test_bytes_data( @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_content_encoding( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request( "post", URL("http://python.org/"), data="foo", compress="deflate", loop=loop ) @@ -992,10 +959,9 @@ async def test_content_encoding( # type: ignore[misc] async def test_content_encoding_dont_set_headers_if_no_body( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request( "post", URL("http://python.org/"), compress="deflate", loop=loop ) @@ -1024,16 +990,14 @@ async def test_content_encoding_rejects_unknown_string( @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_content_encoding_header( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: req = make_client_request( "post", URL("http://python.org/"), data="foo", headers=CIMultiDict({"Content-Encoding": "deflate"}), - loop=loop, + loop=asyncio.get_running_loop(), ) with mock.patch( "aiohttp.client_reqrep.StreamWriter", autospec=True, spec_set=True @@ -1047,9 +1011,7 @@ async def test_content_encoding_header( # type: ignore[misc] async def test_compress_and_content_encoding( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: with pytest.raises(ValueError): make_client_request( @@ -1058,20 +1020,16 @@ async def test_compress_and_content_encoding( data="foo", headers=CIMultiDict({"content-encoding": "deflate"}), compress="deflate", - loop=loop, + loop=asyncio.get_running_loop(), ) -async def test_chunked( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, -) -> None: +async def test_chunked(conn: mock.Mock, make_client_request: _RequestMaker) -> None: req = make_client_request( "post", URL("http://python.org/"), headers=CIMultiDict({"TRANSFER-ENCODING": "gzip"}), - loop=loop, + loop=asyncio.get_running_loop(), ) resp = await req._send(conn) assert "gzip" == req.headers["TRANSFER-ENCODING"] @@ -1079,16 +1037,12 @@ async def test_chunked( resp.close() -async def test_chunked2( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, -) -> None: +async def test_chunked2(conn: mock.Mock, make_client_request: _RequestMaker) -> None: req = make_client_request( "post", URL("http://python.org/"), headers=CIMultiDict({"Transfer-encoding": "chunked"}), - loop=loop, + loop=asyncio.get_running_loop(), ) resp = await req._send(conn) assert "chunked" == req.headers["TRANSFER-ENCODING"] @@ -1097,16 +1051,14 @@ async def test_chunked2( async def test_chunked_empty_body( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: """Ensure write_bytes is called even if the body is empty.""" req = make_client_request( "post", URL("http://python.org/"), chunked=True, - loop=loop, + loop=asyncio.get_running_loop(), data=b"", ) with mock.patch.object(req, "_write_bytes") as write_bytes: @@ -1118,12 +1070,10 @@ async def test_chunked_empty_body( async def test_chunked_explicit( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: req = make_client_request( - "post", URL("http://python.org/"), chunked=True, loop=loop + "post", URL("http://python.org/"), chunked=True, loop=asyncio.get_running_loop() ) with mock.patch( "aiohttp.client_reqrep.StreamWriter", autospec=True, spec_set=True @@ -1137,9 +1087,7 @@ async def test_chunked_explicit( async def test_chunked_length( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: with pytest.raises(ValueError): make_client_request( @@ -1147,14 +1095,12 @@ async def test_chunked_length( URL("http://python.org/"), headers=CIMultiDict({"CONTENT-LENGTH": "1000"}), chunked=True, - loop=loop, + loop=asyncio.get_running_loop(), ) async def test_chunked_transfer_encoding( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: with pytest.raises(ValueError): make_client_request( @@ -1162,14 +1108,12 @@ async def test_chunked_transfer_encoding( URL("http://python.org/"), headers=CIMultiDict({"TRANSFER-ENCODING": "chunked"}), chunked=True, - loop=loop, + loop=asyncio.get_running_loop(), ) -async def test_file_upload_not_chunked( - loop: asyncio.AbstractEventLoop, - make_client_request: _RequestMaker, -) -> None: +async def test_file_upload_not_chunked(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() file_path = pathlib.Path(__file__).parent / "aiohttp.png" with file_path.open("rb") as f: req = make_client_request("post", URL("http://python.org/"), data=f, loop=loop) @@ -1180,7 +1124,6 @@ async def test_file_upload_not_chunked( @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_precompressed_data_stays_intact( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: data = ZLibBackend.compress(b"foobar") @@ -1190,7 +1133,7 @@ async def test_precompressed_data_stays_intact( # type: ignore[misc] data=data, headers=CIMultiDict({"CONTENT-ENCODING": "deflate"}), compress=False, - loop=loop, + loop=asyncio.get_running_loop(), ) assert not req.compress assert not req.chunked @@ -1199,7 +1142,6 @@ async def test_precompressed_data_stays_intact( # type: ignore[misc] async def test_body_with_size_sets_content_length( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: """Test that when body has a size and no Content-Length header is set, it gets added.""" @@ -1211,7 +1153,7 @@ async def test_body_with_size_sets_content_length( "post", URL("http://python.org/"), data=data, - loop=loop, + loop=asyncio.get_running_loop(), ) # Verify Content-Length was set from body.size @@ -1223,7 +1165,6 @@ async def test_body_with_size_sets_content_length( async def test_body_payload_with_size_no_content_length( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: """Test that when a body payload is set via update_body, Content-Length is added.""" @@ -1235,7 +1176,7 @@ async def test_body_payload_with_size_no_content_length( req = make_client_request( "post", URL("http://python.org/"), - loop=loop, + loop=asyncio.get_running_loop(), ) # POST method with None body should have Content-Length: 0 @@ -1259,10 +1200,8 @@ async def test_body_payload_with_size_no_content_length( await req._close() -async def test_file_upload_not_chunked_seek( - loop: asyncio.AbstractEventLoop, - make_client_request: _RequestMaker, -) -> None: +async def test_file_upload_not_chunked_seek(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() file_path = pathlib.Path(__file__).parent / "aiohttp.png" with file_path.open("rb") as f: f.seek(100) @@ -1271,10 +1210,8 @@ async def test_file_upload_not_chunked_seek( await req._close() -async def test_file_upload_force_chunked( - loop: asyncio.AbstractEventLoop, - make_client_request: _RequestMaker, -) -> None: +async def test_file_upload_force_chunked(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() file_path = pathlib.Path(__file__).parent / "aiohttp.png" with file_path.open("rb") as f: req = make_client_request( @@ -1285,11 +1222,8 @@ async def test_file_upload_force_chunked( await req._close() -async def test_expect100( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, -) -> None: +async def test_expect100(conn: mock.Mock, make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() req = make_client_request( "get", URL("http://python.org/"), expect100=True, loop=loop ) @@ -1301,15 +1235,13 @@ async def test_expect100( async def test_expect_100_continue_header( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: req = make_client_request( "get", URL("http://python.org/"), headers=CIMultiDict({"expect": "100-continue"}), - loop=loop, + loop=asyncio.get_running_loop(), ) resp = await req._send(conn) assert "100-continue" == req.headers["EXPECT"] @@ -1319,11 +1251,10 @@ async def test_expect_100_continue_header( async def test_data_stream( - loop: asyncio.AbstractEventLoop, - buf: bytearray, - conn: mock.Mock, - make_client_request: _RequestMaker, + buf: bytearray, conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() + async def gen() -> AsyncIterator[bytes]: yield b"binary data" yield b" result" @@ -1352,17 +1283,14 @@ async def _mock_write_bytes( async def test_data_file( - loop: asyncio.AbstractEventLoop, - buf: bytearray, - conn: mock.Mock, - make_client_request: _RequestMaker, + buf: bytearray, conn: mock.Mock, make_client_request: _RequestMaker ) -> None: with io.BufferedReader(io.BytesIO(b"*" * 2)) as file_handle: req = make_client_request( "POST", URL("http://python.org/"), data=file_handle, - loop=loop, + loop=asyncio.get_running_loop(), ) assert req.chunked assert isinstance(req.body, payload.BufferedReaderPayload) @@ -1389,10 +1317,9 @@ async def _mock_write_bytes( async def test_data_stream_exc( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() fut = loop.create_future() async def gen() -> AsyncIterator[bytes]: @@ -1420,10 +1347,9 @@ async def throw_exc() -> None: async def test_data_stream_exc_chain( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() fut = loop.create_future() async def gen() -> AsyncIterator[None]: @@ -1454,11 +1380,10 @@ async def throw_exc() -> None: async def test_data_stream_continue( - loop: asyncio.AbstractEventLoop, - buf: bytearray, - conn: mock.Mock, - make_client_request: _RequestMaker, + buf: bytearray, conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() + async def gen() -> AsyncIterator[bytes]: yield b"binary data" yield b" result" @@ -1487,11 +1412,9 @@ async def coro() -> None: async def test_data_continue( - loop: asyncio.AbstractEventLoop, - buf: bytearray, - conn: mock.Mock, - make_client_request: _RequestMaker, + buf: bytearray, conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request( "POST", URL("http://python.org/"), data=b"data", expect100=True, loop=loop ) @@ -1514,11 +1437,10 @@ async def coro() -> None: async def test_close( - loop: asyncio.AbstractEventLoop, - buf: bytearray, - conn: mock.Mock, - make_client_request: _RequestMaker, + buf: bytearray, conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() + async def gen() -> AsyncIterator[bytes]: await asyncio.sleep(0.00001) yield b"result" @@ -1531,15 +1453,11 @@ async def gen() -> AsyncIterator[bytes]: resp.close() -async def test_bad_version( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, -) -> None: +async def test_bad_version(conn: mock.Mock, make_client_request: _RequestMaker) -> None: req = make_client_request( "GET", URL("http://python.org"), - loop=loop, + loop=asyncio.get_running_loop(), headers=CIMultiDict({"Connection": "Close"}), version=("1", "1\r\nInjected-Header: not allowed"), # type: ignore[arg-type] ) @@ -1549,10 +1467,10 @@ async def test_bad_version( async def test_custom_response_class( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() + class CustomResponse(ClientResponse): async def read(self) -> bytes: return b"customized!" @@ -1567,10 +1485,9 @@ async def read(self) -> bytes: async def test_oserror_on_write_bytes( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request("POST", URL("http://python.org/"), loop=loop) await req.update_body(b"test data") @@ -1586,10 +1503,9 @@ async def test_oserror_on_write_bytes( @pytest.mark.skipif(sys.version_info < (3, 11), reason="Needs Task.cancelling()") async def test_cancel_close( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, + conn: mock.Mock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request("get", URL("http://python.org"), loop=loop) req._writer = asyncio.Future() # type: ignore[assignment] @@ -1604,11 +1520,8 @@ async def test_cancel_close( # type: ignore[misc] await t -async def test_terminate( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, - make_client_request: _RequestMaker, -) -> None: +async def test_terminate(conn: mock.Mock, make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() req = make_client_request("get", URL("http://python.org"), loop=loop) async def _mock_write_bytes(*args: object, **kwargs: object) -> None: @@ -1705,9 +1618,7 @@ async def test_terminate_without_writer(make_client_request: _RequestMaker) -> N assert req._writer is None -async def test_custom_req_rep( - loop: asyncio.AbstractEventLoop, create_mocked_conn: mock.Mock -) -> None: +async def test_custom_req_rep(create_mocked_conn: mock.Mock) -> None: conn = None class CustomResponse(ClientResponse): @@ -1916,13 +1827,11 @@ async def test_get_content_length(make_client_request: _RequestMaker) -> None: async def test_write_bytes_with_content_length_limit( - loop: asyncio.AbstractEventLoop, - buf: bytearray, - conn: mock.Mock, - make_client_request: _RequestMaker, + buf: bytearray, conn: mock.Mock, make_client_request: _RequestMaker ) -> None: """Test that write_bytes respects content_length limit for different body types.""" # Test with bytes data + loop = asyncio.get_running_loop() data = b"Hello World" req = make_client_request("post", URL("http://python.org/"), loop=loop) @@ -1945,7 +1854,6 @@ async def test_write_bytes_with_content_length_limit( ], ) async def test_write_bytes_with_iterable_content_length_limit( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, buf: bytearray, conn: mock.Mock, data: list[bytes] | bytes, @@ -1953,6 +1861,7 @@ async def test_write_bytes_with_iterable_content_length_limit( # type: ignore[m ) -> None: """Test that write_bytes respects content_length limit for iterable data.""" # Test with iterable data + loop = asyncio.get_running_loop() req = make_client_request("post", URL("http://python.org/"), loop=loop) # Convert list to async generator if needed @@ -1975,12 +1884,10 @@ async def gen() -> AsyncIterator[bytes]: async def test_write_bytes_empty_iterable_with_content_length( - loop: asyncio.AbstractEventLoop, - buf: bytearray, - conn: mock.Mock, - make_client_request: _RequestMaker, + buf: bytearray, conn: mock.Mock, make_client_request: _RequestMaker ) -> None: """Test that write_bytes handles empty iterable body with content_length.""" + loop = asyncio.get_running_loop() req = make_client_request("post", URL("http://python.org/"), loop=loop) # Create an empty async generator @@ -2175,10 +2082,10 @@ async def test_content_length_for_methods( # type: ignore[misc] method: str, data: bytes | None, expected_content_length: str | None, - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: """Test that Content-Length header is set correctly for all HTTP methods.""" + loop = asyncio.get_running_loop() req = make_client_request(method, URL("http://python.org/"), data=data, loop=loop) actual_content_length = req.headers.get(hdrs.CONTENT_LENGTH) @@ -2198,10 +2105,10 @@ def test_non_get_methods_classification(method: str) -> None: async def test_content_length_with_string_data( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: """Test Content-Length when data is a string.""" + loop = asyncio.get_running_loop() data = "Hello, World!" req = make_client_request("POST", URL("http://python.org/"), data=data, loop=loop) # String should be encoded to bytes, default encoding is utf-8 @@ -2210,10 +2117,10 @@ async def test_content_length_with_string_data( async def test_content_length_with_async_iterable( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: """Test that async iterables use chunked encoding, not Content-Length.""" + loop = asyncio.get_running_loop() async def data_gen() -> AsyncIterator[bytes]: yield b"chunk1" # pragma: no cover @@ -2228,7 +2135,6 @@ async def data_gen() -> AsyncIterator[bytes]: async def test_content_length_not_overridden( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: """Test that explicitly set Content-Length is not overridden.""" @@ -2237,18 +2143,16 @@ async def test_content_length_not_overridden( URL("http://python.org/"), data=b"test", headers=CIMultiDict({hdrs.CONTENT_LENGTH: "100"}), - loop=loop, + loop=asyncio.get_running_loop(), ) # Should keep the explicitly set value assert req.headers[hdrs.CONTENT_LENGTH] == "100" await req._close() -async def test_content_length_with_formdata( - loop: asyncio.AbstractEventLoop, - make_client_request: _RequestMaker, -) -> None: +async def test_content_length_with_formdata(make_client_request: _RequestMaker) -> None: """Test Content-Length with FormData.""" + loop = asyncio.get_running_loop() form = aiohttp.FormData() form.add_field("field", "value") @@ -2259,7 +2163,6 @@ async def test_content_length_with_formdata( async def test_no_content_length_with_chunked( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: """Test that chunked encoding prevents Content-Length header.""" @@ -2268,7 +2171,7 @@ async def test_no_content_length_with_chunked( URL("http://python.org/"), data=b"test", chunked=True, - loop=loop, + loop=asyncio.get_running_loop(), ) assert hdrs.CONTENT_LENGTH not in req.headers assert req.headers[hdrs.TRANSFER_ENCODING] == "chunked" @@ -2277,12 +2180,11 @@ async def test_no_content_length_with_chunked( @pytest.mark.parametrize("method", ["POST", "PUT", "PATCH", "DELETE"]) async def test_update_body_none_sets_content_length_zero( # type: ignore[misc] - method: str, - loop: asyncio.AbstractEventLoop, - make_client_request: _RequestMaker, + method: str, make_client_request: _RequestMaker ) -> None: """Test that updating body to None sets Content-Length: 0 for POST-like methods.""" # Create request with initial body + loop = asyncio.get_running_loop() req = make_client_request( method, URL("http://python.org/"), data=b"initial", loop=loop ) @@ -2296,12 +2198,11 @@ async def test_update_body_none_sets_content_length_zero( # type: ignore[misc] @pytest.mark.parametrize("method", ["GET", "HEAD", "OPTIONS", "TRACE"]) async def test_update_body_none_no_content_length_for_get_methods( # type: ignore[misc] - method: str, - loop: asyncio.AbstractEventLoop, - make_client_request: _RequestMaker, + method: str, make_client_request: _RequestMaker ) -> None: """Test that updating body to None doesn't set Content-Length for GET-like methods.""" # Create request with initial body + loop = asyncio.get_running_loop() req = make_client_request( method, URL("http://python.org/"), data=b"initial", loop=loop ) diff --git a/tests/test_client_response.py b/tests/test_client_response.py index 9d7025efaca..96a14ca56eb 100644 --- a/tests/test_client_response.py +++ b/tests/test_client_response.py @@ -208,9 +208,8 @@ def test_repr_non_ascii_reason() -> None: ) -async def test_read_and_release_connection( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_read_and_release_connection(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -238,9 +237,8 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": assert response._connection is None -async def test_read_and_release_connection_with_error( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_read_and_release_connection_with_error(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -263,7 +261,8 @@ async def test_read_and_release_connection_with_error( assert response._closed -async def test_release(loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: +async def test_release(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -290,9 +289,7 @@ async def test_release(loop: asyncio.AbstractEventLoop, session: ClientSession) sys.implementation.name != "cpython", reason="Other implementations has different GC strategies", ) -async def test_release_on_del( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_release_on_del(session: ClientSession) -> None: connection = mock.Mock() connection.protocol.upgraded = False @@ -305,7 +302,7 @@ def run(conn: Connection) -> None: continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, request_headers=CIMultiDict[str](), original_url=url, @@ -318,9 +315,7 @@ def run(conn: Connection) -> None: assert connection.release.called -async def test_response_eof( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_response_eof(session: ClientSession) -> None: url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -329,7 +324,7 @@ async def test_response_eof( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, request_headers=CIMultiDict[str](), original_url=url, @@ -343,9 +338,7 @@ async def test_response_eof( assert response._connection is None -async def test_response_eof_upgraded( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_response_eof_upgraded(session: ClientSession) -> None: url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -354,7 +347,7 @@ async def test_response_eof_upgraded( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, request_headers=CIMultiDict[str](), original_url=url, @@ -368,9 +361,7 @@ async def test_response_eof_upgraded( assert response._connection is conn -async def test_response_eof_after_connection_detach( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_response_eof_after_connection_detach(session: ClientSession) -> None: url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -379,7 +370,7 @@ async def test_response_eof_after_connection_detach( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, request_headers=CIMultiDict[str](), original_url=url, @@ -393,7 +384,8 @@ async def test_response_eof_after_connection_detach( assert response._connection is None -async def test_text(loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: +async def test_text(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -423,9 +415,8 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": assert response._connection is None -async def test_text_bad_encoding( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_text_bad_encoding(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -458,9 +449,8 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": assert response._connection is None -async def test_text_badly_encoded_encoding_header( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_text_badly_encoded_encoding_header(session: ClientSession) -> None: + loop = asyncio.get_running_loop() session._resolve_charset = lambda *_: "utf-8" url = URL("http://def-cl-resp.org") response = ClientResponse( @@ -492,9 +482,8 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": assert encoding == "utf-8" -async def test_text_custom_encoding( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_text_custom_encoding(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -526,9 +515,8 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": @pytest.mark.parametrize("content_type", ("text/plain", "text/plain;charset=invalid")) -async def test_text_charset_resolver( - content_type: str, loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_text_charset_resolver(content_type: str, session: ClientSession) -> None: + loop = asyncio.get_running_loop() session._resolve_charset = lambda r, b: "cp1251" url = URL("http://def-cl-resp.org") response = ClientResponse( @@ -561,9 +549,7 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": assert response.get_encoding() == "cp1251" -async def test_get_encoding_body_none( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_get_encoding_body_none(session: ClientSession) -> None: url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -572,7 +558,7 @@ async def test_get_encoding_body_none( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, request_headers=CIMultiDict[str](), original_url=url, @@ -591,9 +577,8 @@ async def test_get_encoding_body_none( assert response.closed -async def test_text_after_read( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_text_after_read(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -623,7 +608,8 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": assert response._connection is None -async def test_json(loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: +async def test_json(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -653,9 +639,8 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": assert response._connection is None -async def test_json_extended_content_type( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_json_extended_content_type(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -685,9 +670,8 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": assert response._connection is None -async def test_json_custom_content_type( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_json_custom_content_type(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -717,9 +701,7 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": assert response._connection is None -async def test_json_custom_loader( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_json_custom_loader(session: ClientSession) -> None: url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -728,7 +710,7 @@ async def test_json_custom_loader( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, request_headers=CIMultiDict[str](), original_url=url, @@ -744,9 +726,7 @@ def custom(content: str) -> str: assert res == "data-custom" -async def test_json_invalid_content_type( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_json_invalid_content_type(session: ClientSession) -> None: url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -755,7 +735,7 @@ async def test_json_invalid_content_type( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, request_headers=CIMultiDict[str](), original_url=url, @@ -772,9 +752,7 @@ async def test_json_invalid_content_type( assert info.value.status == 500 -async def test_json_no_content( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_json_no_content(session: ClientSession) -> None: url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -783,7 +761,7 @@ async def test_json_no_content( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, request_headers=CIMultiDict[str](), original_url=url, @@ -796,9 +774,8 @@ async def test_json_no_content( await response.json(content_type=None) -async def test_json_override_encoding( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_json_override_encoding(session: ClientSession) -> None: + loop = asyncio.get_running_loop() url = URL("http://def-cl-resp.org") response = ClientResponse( "get", @@ -1260,9 +1237,8 @@ def test_redirect_history_in_exception() -> None: assert (hist_response,) == cm.value.history -async def test_response_read_triggers_callback( - loop: asyncio.AbstractEventLoop, session: ClientSession -) -> None: +async def test_response_read_triggers_callback(session: ClientSession) -> None: + loop = asyncio.get_running_loop() trace = mock.create_autospec(Trace, instance=True, spec_set=True) response_method = "get" response_url = URL("http://def-cl-resp.org") diff --git a/tests/test_client_session.py b/tests/test_client_session.py index 8075a446fa6..c239c05661d 100644 --- a/tests/test_client_session.py +++ b/tests/test_client_session.py @@ -341,9 +341,7 @@ async def test_closed(session: ClientSession) -> None: async def test_connector( - create_session: Callable[..., Awaitable[ClientSession]], - loop: asyncio.AbstractEventLoop, - mocker: MockerFixture, + create_session: Callable[..., Awaitable[ClientSession]], mocker: MockerFixture ) -> None: connector = TCPConnector() m = mocker.spy(connector, "close") @@ -356,9 +354,7 @@ async def test_connector( async def test_create_connector( - create_session: Callable[..., Awaitable[ClientSession]], - loop: asyncio.AbstractEventLoop, - mocker: MockerFixture, + create_session: Callable[..., Awaitable[ClientSession]], mocker: MockerFixture ) -> None: session = await create_session() m = mocker.spy(session.connector, "close") @@ -514,7 +510,8 @@ async def test_double_close( assert connector.closed -async def test_del(connector: BaseConnector, loop: asyncio.AbstractEventLoop) -> None: +async def test_del(connector: BaseConnector) -> None: + loop = asyncio.get_running_loop() loop.set_debug(False) # N.B. don't use session fixture, it stores extra reference internally session = ClientSession(connector=connector) @@ -530,9 +527,8 @@ async def test_del(connector: BaseConnector, loop: asyncio.AbstractEventLoop) -> assert logs[0] == expected -async def test_del_debug( - connector: BaseConnector, loop: asyncio.AbstractEventLoop -) -> None: +async def test_del_debug(connector: BaseConnector) -> None: + loop = asyncio.get_running_loop() loop.set_debug(True) # N.B. don't use session fixture, it stores extra reference internally session = ClientSession(connector=connector) @@ -553,12 +549,10 @@ async def test_del_debug( async def test_borrow_connector_loop( - connector: BaseConnector, - create_session: Callable[..., Awaitable[ClientSession]], - loop: asyncio.AbstractEventLoop, + connector: BaseConnector, create_session: Callable[..., Awaitable[ClientSession]] ) -> None: async with ClientSession(connector=connector) as session: - assert session._loop is loop + assert session._loop is asyncio.get_running_loop() async def test_reraise_os_error( @@ -762,9 +756,7 @@ async def create_connection( await session.close() -async def test_cookie_jar_usage( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_cookie_jar_usage(aiohttp_client: AiohttpClient) -> None: req_url = None class MockCookieJar(abc.AbstractCookieJar): @@ -883,7 +875,7 @@ async def handler(request: web.Request) -> web.Response: assert "adhoc=value" in resp.request_info.headers.get("Cookie", "") -async def test_session_default_version(loop: asyncio.AbstractEventLoop) -> None: +async def test_session_default_version() -> None: session = aiohttp.ClientSession() assert session.version == aiohttp.HttpVersion11 await session.close() @@ -901,7 +893,7 @@ async def test_proxy_str(session: ClientSession, params: _Params) -> None: ] -async def test_default_proxy(loop: asyncio.AbstractEventLoop) -> None: +async def test_default_proxy() -> None: proxy_url = URL("http://proxy.example.com") proxy_auth = mock.Mock() proxy_url2 = URL("http://proxy.example2.com") @@ -950,9 +942,7 @@ class OnCall(Exception): await session.close() -async def test_request_tracing( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_request_tracing(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.Response: return web.json_response({"ok": True}) @@ -1056,9 +1046,7 @@ async def on_request_headers_sent( assert gathered_req_headers["Custom-Header"] == "Custom value" -async def test_request_tracing_url_params( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_request_tracing_url_params(aiohttp_client: AiohttpClient) -> None: async def root_handler(request: web.Request) -> web.Response: return web.Response() @@ -1256,9 +1244,7 @@ async def test_request_tracing_exception() -> None: await session.close() -async def test_request_tracing_interpose_headers( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_request_tracing_interpose_headers(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.Response: return web.Response() @@ -1303,9 +1289,7 @@ async def test_client_session_custom_attr() -> None: await session.close() -async def test_client_session_timeout_default_args( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_client_session_timeout_default_args() -> None: session1 = ClientSession() assert session1.timeout == client.DEFAULT_TIMEOUT await session1.close() @@ -1437,9 +1421,8 @@ async def test_base_url_without_trailing_slash() -> None: ClientSession(base_url="http://example.com/test") -async def test_instantiation_with_invalid_timeout_value( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_instantiation_with_invalid_timeout_value() -> None: + loop = asyncio.get_running_loop() loop.set_debug(False) logs = [] loop.set_exception_handler(lambda loop, ctx: logs.append(ctx)) diff --git a/tests/test_client_ws.py b/tests/test_client_ws.py index e36852dc26c..5ad01da5dfe 100644 --- a/tests/test_client_ws.py +++ b/tests/test_client_ws.py @@ -21,9 +21,7 @@ from aiohttp.streams import EofStream -async def test_ws_connect( - ws_key: str, loop: asyncio.AbstractEventLoop, key_data: bytes -) -> None: +async def test_ws_connect(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -36,7 +34,7 @@ async def test_ws_connect( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) res = await aiohttp.ClientSession().ws_connect( @@ -49,7 +47,7 @@ async def test_ws_connect( async def test_ws_connect_read_timeout_is_reset_to_inf( - ws_key: str, loop: asyncio.AbstractEventLoop, key_data: bytes + ws_key: str, key_data: bytes ) -> None: resp = mock.Mock() resp.status = 101 @@ -65,7 +63,7 @@ async def test_ws_connect_read_timeout_is_reset_to_inf( mock.patch("aiohttp.client.ClientSession.request") as m_req, ): m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) res = await aiohttp.ClientSession().ws_connect( @@ -78,9 +76,7 @@ async def test_ws_connect_read_timeout_is_reset_to_inf( assert resp.connection.protocol.read_timeout is None -async def test_ws_connect_read_timeout_stays_inf( - ws_key: str, loop: asyncio.AbstractEventLoop, key_data: bytes -) -> None: +async def test_ws_connect_read_timeout_stays_inf(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -95,7 +91,7 @@ async def test_ws_connect_read_timeout_stays_inf( mock.patch("aiohttp.client.ClientSession.request") as m_req, ): m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) res = await aiohttp.ClientSession().ws_connect( @@ -111,7 +107,7 @@ async def test_ws_connect_read_timeout_stays_inf( async def test_ws_connect_read_timeout_reset_to_max( - ws_key: str, loop: asyncio.AbstractEventLoop, key_data: bytes + ws_key: str, key_data: bytes ) -> None: resp = mock.Mock() resp.status = 101 @@ -127,7 +123,7 @@ async def test_ws_connect_read_timeout_reset_to_max( mock.patch("aiohttp.client.ClientSession.request") as m_req, ): m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) res = await aiohttp.ClientSession().ws_connect( @@ -142,15 +138,13 @@ async def test_ws_connect_read_timeout_reset_to_max( assert resp.connection.protocol.read_timeout == 1.0 -async def test_ws_connect_with_origin( - key_data: bytes, loop: asyncio.AbstractEventLoop -) -> None: +async def test_ws_connect_with_origin(key_data: bytes) -> None: resp = mock.Mock() resp.status = 403 with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) origin = "https://example.org/page.html" @@ -163,9 +157,7 @@ async def test_ws_connect_with_origin( assert m_req.call_args[1]["headers"][hdrs.ORIGIN] == origin -async def test_ws_connect_with_params( - ws_key: str, loop: asyncio.AbstractEventLoop, key_data: bytes -) -> None: +async def test_ws_connect_with_params(ws_key: str, key_data: bytes) -> None: params = {"key1": "value1", "key2": "value2"} resp = mock.Mock() @@ -180,7 +172,7 @@ async def test_ws_connect_with_params( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) await aiohttp.ClientSession().ws_connect( @@ -190,9 +182,8 @@ async def test_ws_connect_with_params( assert m_req.call_args[1]["params"] == params -async def test_ws_connect_custom_response( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_custom_response(ws_key: str, key_data: bytes) -> None: + class CustomResponse(client.ClientWebSocketResponse): def read(self, decode: bool = False) -> str: return "customized!" @@ -208,7 +199,7 @@ def read(self, decode: bool = False) -> str: with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) res = await aiohttp.ClientSession( @@ -220,9 +211,7 @@ def read(self, decode: bool = False) -> str: assert res.read() == "customized!" # type: ignore[attr-defined] -async def test_ws_connect_err_status( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_err_status(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 500 resp.headers = { @@ -233,7 +222,7 @@ async def test_ws_connect_err_status( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) with pytest.raises(client.WSServerHandshakeError) as ctx: @@ -244,9 +233,7 @@ async def test_ws_connect_err_status( assert ctx.value.message == "Invalid response status" -async def test_ws_connect_err_upgrade( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_err_upgrade(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -257,7 +244,7 @@ async def test_ws_connect_err_upgrade( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) with pytest.raises(client.WSServerHandshakeError) as ctx: @@ -268,9 +255,7 @@ async def test_ws_connect_err_upgrade( assert ctx.value.message == "Invalid upgrade header" -async def test_ws_connect_err_conn( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_err_conn(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -281,7 +266,7 @@ async def test_ws_connect_err_conn( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) with pytest.raises(client.WSServerHandshakeError) as ctx: @@ -292,9 +277,7 @@ async def test_ws_connect_err_conn( assert ctx.value.message == "Invalid connection header" -async def test_ws_connect_err_challenge( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_err_challenge(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -305,7 +288,7 @@ async def test_ws_connect_err_challenge( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) with pytest.raises(client.WSServerHandshakeError) as ctx: @@ -316,9 +299,7 @@ async def test_ws_connect_err_challenge( assert ctx.value.message == "Invalid challenge response" -async def test_ws_connect_common_headers( - ws_key: str, loop: asyncio.AbstractEventLoop, key_data: bytes -) -> None: +async def test_ws_connect_common_headers(ws_key: str, key_data: bytes) -> None: # Emulate a headers dict being reused for a second ws_connect. # In this scenario, we need to ensure that the newly generated secret key @@ -364,9 +345,7 @@ async def mock_get( await test_connection() -async def test_close( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_close(ws_key: str, key_data: bytes) -> None: mresp = mock.Mock() mresp.status = 101 mresp.headers = { @@ -379,7 +358,7 @@ async def test_close( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(mresp) writer = mock.create_autospec( RealWebSocketWriter, instance=True, spec_set=True @@ -406,9 +385,7 @@ async def test_close( await session.close() -async def test_close_eofstream( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_close_eofstream(ws_key: str, key_data: bytes) -> None: mresp = mock.Mock() mresp.status = 101 mresp.headers = { @@ -421,7 +398,7 @@ async def test_close_eofstream( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(mresp) writer = WebSocketWriter.return_value = mock.Mock() @@ -439,9 +416,7 @@ async def test_close_eofstream( await session.close() # type: ignore[unreachable] -async def test_close_connection_lost( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_close_connection_lost(ws_key: str, key_data: bytes) -> None: """Test the websocket client handles the connection being closed out from under it.""" mresp = mock.Mock(spec_set=client.ClientResponse) mresp.status = 101 @@ -457,7 +432,7 @@ async def test_close_connection_lost( mock.patch("aiohttp.client.ClientSession.request") as m_req, ): m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(mresp) session = aiohttp.ClientSession() @@ -474,9 +449,7 @@ async def test_close_connection_lost( await session.close() # type: ignore[unreachable] -async def test_close_exc( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_close_exc(ws_key: str, key_data: bytes) -> None: mresp = mock.Mock() mresp.status = 101 mresp.headers = { @@ -489,7 +462,7 @@ async def test_close_exc( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(mresp) writer = mock.create_autospec( RealWebSocketWriter, instance=True, spec_set=True @@ -510,9 +483,7 @@ async def test_close_exc( await session.close() -async def test_close_exc2( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_close_exc2(ws_key: str, key_data: bytes) -> None: mresp = mock.Mock() mresp.status = 101 mresp.headers = { @@ -525,7 +496,7 @@ async def test_close_exc2( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(mresp) writer = WebSocketWriter.return_value = mock.Mock() @@ -547,10 +518,7 @@ async def test_close_exc2( @pytest.mark.parametrize("exc", (ClientConnectionResetError, ConnectionResetError)) async def test_send_data_after_close( - exc: type[Exception], - ws_key: str, - key_data: bytes, - loop: asyncio.AbstractEventLoop, + exc: type[Exception], ws_key: str, key_data: bytes ) -> None: mresp = mock.Mock() mresp.status = 101 @@ -563,7 +531,7 @@ async def test_send_data_after_close( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(mresp) resp = await aiohttp.ClientSession().ws_connect("http://test.org") @@ -581,9 +549,7 @@ async def test_send_data_after_close( await meth(*args) -async def test_send_data_type_errors( - ws_key: str, key_data: bytes, loop: asyncio.AbstractEventLoop -) -> None: +async def test_send_data_type_errors(ws_key: str, key_data: bytes) -> None: mresp = mock.Mock() mresp.status = 101 mresp.headers = { @@ -596,7 +562,7 @@ async def test_send_data_type_errors( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(mresp) WebSocketWriter.return_value = mock.Mock() @@ -610,9 +576,7 @@ async def test_send_data_type_errors( await resp.send_json(set()) -async def test_reader_read_exception( - ws_key: str, key_data: bytes, loop: asyncio.AbstractEventLoop -) -> None: +async def test_reader_read_exception(ws_key: str, key_data: bytes) -> None: hresp = mock.Mock() hresp.status = 101 hresp.headers = { @@ -625,7 +589,7 @@ async def test_reader_read_exception( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(hresp) writer = mock.create_autospec( @@ -646,7 +610,7 @@ async def test_reader_read_exception( await session.close() -async def test_receive_runtime_err(loop: asyncio.AbstractEventLoop) -> None: +async def test_receive_runtime_err() -> None: resp = client.ClientWebSocketResponse( mock.Mock(), mock.Mock(), @@ -655,7 +619,7 @@ async def test_receive_runtime_err(loop: asyncio.AbstractEventLoop) -> None: ClientWSTimeout(ws_receive=10.0), True, True, - loop, + asyncio.get_running_loop(), ) resp._waiting = True @@ -663,9 +627,7 @@ async def test_receive_runtime_err(loop: asyncio.AbstractEventLoop) -> None: await resp.receive() -async def test_heartbeat_reset_coalesces_on_data( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_heartbeat_reset_coalesces_on_data() -> None: response = mock.Mock() response.connection = None resp = client.ClientWebSocketResponse( @@ -676,7 +638,7 @@ async def test_heartbeat_reset_coalesces_on_data( ClientWSTimeout(ws_receive=10.0), True, True, - loop, + asyncio.get_running_loop(), heartbeat=0.05, ) with mock.patch.object(resp, "_reset_heartbeat", autospec=True) as reset: @@ -688,9 +650,7 @@ async def test_heartbeat_reset_coalesces_on_data( assert reset.call_count == 1 -async def test_receive_does_not_reset_heartbeat( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_receive_does_not_reset_heartbeat() -> None: response = mock.Mock() response.connection = None msg = mock.Mock(type=aiohttp.WSMsgType.TEXT) @@ -704,7 +664,7 @@ async def test_receive_does_not_reset_heartbeat( ClientWSTimeout(ws_receive=10.0), True, True, - loop, + asyncio.get_running_loop(), heartbeat=0.05, ) with mock.patch.object(resp, "_reset_heartbeat", autospec=True) as reset: @@ -714,9 +674,7 @@ async def test_receive_does_not_reset_heartbeat( reset.assert_not_called() -async def test_cancel_heartbeat_cancels_pending_heartbeat_reset_handle( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_cancel_heartbeat_cancels_pending_heartbeat_reset_handle() -> None: response = mock.Mock() response.connection = None resp = client.ClientWebSocketResponse( @@ -727,7 +685,7 @@ async def test_cancel_heartbeat_cancels_pending_heartbeat_reset_handle( ClientWSTimeout(ws_receive=10.0), True, True, - loop, + asyncio.get_running_loop(), heartbeat=0.05, ) @@ -742,9 +700,7 @@ async def test_cancel_heartbeat_cancels_pending_heartbeat_reset_handle( assert handle.cancelled() -async def test_flush_heartbeat_reset_returns_early_when_not_needed( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_flush_heartbeat_reset_returns_early_when_not_needed() -> None: response = mock.Mock() response.connection = None resp = client.ClientWebSocketResponse( @@ -755,7 +711,7 @@ async def test_flush_heartbeat_reset_returns_early_when_not_needed( ClientWSTimeout(ws_receive=10.0), True, True, - loop, + asyncio.get_running_loop(), heartbeat=0.05, ) resp._need_heartbeat_reset = False @@ -765,9 +721,7 @@ async def test_flush_heartbeat_reset_returns_early_when_not_needed( reset.assert_not_called() -async def test_send_heartbeat_returns_early_when_reset_is_pending( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_send_heartbeat_returns_early_when_reset_is_pending() -> None: response = mock.Mock() response.connection = None writer = mock.Mock() @@ -779,7 +733,7 @@ async def test_send_heartbeat_returns_early_when_reset_is_pending( ClientWSTimeout(ws_receive=10.0), True, True, - loop, + asyncio.get_running_loop(), heartbeat=0.05, ) resp._need_heartbeat_reset = True @@ -789,9 +743,7 @@ async def test_send_heartbeat_returns_early_when_reset_is_pending( writer.send_frame.assert_not_called() -async def test_ws_connect_close_resp_on_err( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_close_resp_on_err(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 500 resp.headers = { @@ -802,7 +754,7 @@ async def test_ws_connect_close_resp_on_err( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) with pytest.raises(client.WSServerHandshakeError): @@ -813,7 +765,7 @@ async def test_ws_connect_close_resp_on_err( async def test_ws_connect_non_overlapped_protocols( - ws_key: str, loop: asyncio.AbstractEventLoop, key_data: bytes + ws_key: str, key_data: bytes ) -> None: resp = mock.Mock() resp.status = 101 @@ -827,7 +779,7 @@ async def test_ws_connect_non_overlapped_protocols( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) res = await aiohttp.ClientSession().ws_connect( @@ -838,7 +790,7 @@ async def test_ws_connect_non_overlapped_protocols( async def test_ws_connect_non_overlapped_protocols_2( - ws_key: str, loop: asyncio.AbstractEventLoop, key_data: bytes + ws_key: str, key_data: bytes ) -> None: resp = mock.Mock() resp.status = 101 @@ -852,7 +804,7 @@ async def test_ws_connect_non_overlapped_protocols_2( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) connector = aiohttp.TCPConnector(force_close=True) @@ -864,9 +816,7 @@ async def test_ws_connect_non_overlapped_protocols_2( del res -async def test_ws_connect_deflate( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_deflate(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -879,7 +829,7 @@ async def test_ws_connect_deflate( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) res = await aiohttp.ClientSession().ws_connect( @@ -890,9 +840,7 @@ async def test_ws_connect_deflate( assert res.client_notakeover is False -async def test_ws_connect_deflate_per_message( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_deflate_per_message(ws_key: str, key_data: bytes) -> None: mresp = mock.Mock() mresp.status = 101 mresp.headers = { @@ -906,7 +854,7 @@ async def test_ws_connect_deflate_per_message( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(mresp) writer = mock.create_autospec( RealWebSocketWriter, instance=True, spec_set=True @@ -941,7 +889,7 @@ async def test_ws_connect_deflate_per_message( async def test_ws_connect_deflate_server_not_support( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes + ws_key: str, key_data: bytes ) -> None: resp = mock.Mock() resp.status = 101 @@ -954,7 +902,7 @@ async def test_ws_connect_deflate_server_not_support( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) res = await aiohttp.ClientSession().ws_connect( @@ -965,9 +913,7 @@ async def test_ws_connect_deflate_server_not_support( assert res.client_notakeover is False -async def test_ws_connect_deflate_notakeover( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_deflate_notakeover(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -981,7 +927,7 @@ async def test_ws_connect_deflate_notakeover( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) res = await aiohttp.ClientSession().ws_connect( @@ -992,9 +938,7 @@ async def test_ws_connect_deflate_notakeover( assert res.client_notakeover is True -async def test_ws_connect_deflate_client_wbits( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_deflate_client_wbits(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -1008,7 +952,7 @@ async def test_ws_connect_deflate_client_wbits( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) res = await aiohttp.ClientSession().ws_connect( @@ -1020,7 +964,7 @@ async def test_ws_connect_deflate_client_wbits( async def test_ws_connect_deflate_client_wbits_bad( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes + ws_key: str, key_data: bytes ) -> None: resp = mock.Mock() resp.status = 101 @@ -1034,16 +978,14 @@ async def test_ws_connect_deflate_client_wbits_bad( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) with pytest.raises(client.WSServerHandshakeError): await aiohttp.ClientSession().ws_connect("http://test.org", compress=15) -async def test_ws_connect_deflate_server_ext_bad( - loop: asyncio.AbstractEventLoop, ws_key: str, key_data: bytes -) -> None: +async def test_ws_connect_deflate_server_ext_bad(ws_key: str, key_data: bytes) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -1055,7 +997,7 @@ async def test_ws_connect_deflate_server_ext_bad( with mock.patch("aiohttp.client.os") as m_os: with mock.patch("aiohttp.client.ClientSession.request") as m_req: m_os.urandom.return_value = key_data - m_req.return_value = loop.create_future() + m_req.return_value = asyncio.get_running_loop().create_future() m_req.return_value.set_result(resp) with pytest.raises(client.WSServerHandshakeError): diff --git a/tests/test_client_ws_functional.py b/tests/test_client_ws_functional.py index ea8a44ab04e..81ae09e828b 100644 --- a/tests/test_client_ws_functional.py +++ b/tests/test_client_ws_functional.py @@ -1047,7 +1047,7 @@ async def handler(request: web.Request) -> NoReturn: async def test_close_websocket_while_ping_inflight( - aiohttp_client: AiohttpClient, loop: asyncio.AbstractEventLoop + aiohttp_client: AiohttpClient, ) -> None: """Test closing the websocket while a ping is in-flight.""" ping_received = False @@ -1071,7 +1071,7 @@ async def handler(request: web.Request) -> NoReturn: await resp.send_bytes(b"ask") cancelled = False - ping_started = loop.create_future() + ping_started = asyncio.get_running_loop().create_future() async def delayed_send_frame( message: bytes, opcode: int, compress: int | None = None @@ -1375,10 +1375,9 @@ async def handler(request: web.Request) -> NoReturn: await resp.close() -async def test_websocket_connection_cancellation( - aiohttp_client: AiohttpClient, loop: asyncio.AbstractEventLoop -) -> None: +async def test_websocket_connection_cancellation(aiohttp_client: AiohttpClient) -> None: """Test canceling the WebSocket connection task does not raise an exception in __del__.""" + loop = asyncio.get_running_loop() async def handler(request: web.Request) -> NoReturn: ws = web.WebSocketResponse() diff --git a/tests/test_connector.py b/tests/test_connector.py index 5b8f1e36db9..e071e80862f 100644 --- a/tests/test_connector.py +++ b/tests/test_connector.py @@ -136,7 +136,8 @@ def create_mocked_conn( return proto -async def test_connection_del(loop: asyncio.AbstractEventLoop) -> None: +async def test_connection_del() -> None: + loop = asyncio.get_running_loop() connector = mock.Mock() key = mock.Mock() protocol = mock.Mock() @@ -197,7 +198,8 @@ def test_connection_del_loop_closed(loop: asyncio.AbstractEventLoop) -> None: assert not exc_handler.called -async def test_del(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> None: +async def test_del(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector() proto = create_mocked_conn(loop, should_close=False) conn._release(key, proto) @@ -222,8 +224,9 @@ async def test_del(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> None: @pytest.mark.xfail async def test_del_with_scheduled_cleanup( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, key: ConnectionKey + key: ConnectionKey, ) -> None: + loop = asyncio.get_running_loop() loop.set_debug(True) conn = aiohttp.BaseConnector(keepalive_timeout=0.01) transp = create_mocked_conn(loop) @@ -275,11 +278,11 @@ async def make_conn() -> aiohttp.BaseConnector: assert exc_handler.called -async def test_del_empty_connector(loop: asyncio.AbstractEventLoop) -> None: +async def test_del_empty_connector() -> None: conn = aiohttp.BaseConnector() exc_handler = mock.Mock() - loop.set_exception_handler(exc_handler) + asyncio.get_running_loop().set_exception_handler(exc_handler) del conn @@ -293,7 +296,7 @@ async def test_create_conn() -> None: await conn.close() -async def test_async_context_manager(loop: asyncio.AbstractEventLoop) -> None: +async def test_async_context_manager() -> None: conn = aiohttp.BaseConnector() async with conn as c: @@ -339,7 +342,8 @@ async def test_close_with_proto_closed_none(key: ConnectionKey) -> None: assert conn.closed -async def test_get(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> None: +async def test_get(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector() try: assert await conn._get(key, []) is None @@ -354,7 +358,8 @@ async def test_get(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> None: await conn.close() -async def test_get_unconnected_proto(loop: asyncio.AbstractEventLoop) -> None: +async def test_get_unconnected_proto() -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector() key = ConnectionKey("localhost", 80, False, False, None, None, None) try: @@ -375,7 +380,8 @@ async def test_get_unconnected_proto(loop: asyncio.AbstractEventLoop) -> None: await conn.close() -async def test_get_unconnected_proto_ssl(loop: asyncio.AbstractEventLoop) -> None: +async def test_get_unconnected_proto_ssl() -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector() key = ConnectionKey("localhost", 80, True, False, None, None, None) try: @@ -396,7 +402,8 @@ async def test_get_unconnected_proto_ssl(loop: asyncio.AbstractEventLoop) -> Non await conn.close() -async def test_get_expired(loop: asyncio.AbstractEventLoop) -> None: +async def test_get_expired() -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector() key = ConnectionKey("localhost", 80, False, False, None, None, None) try: @@ -411,7 +418,8 @@ async def test_get_expired(loop: asyncio.AbstractEventLoop) -> None: @pytest.mark.usefixtures("enable_cleanup_closed") -async def test_get_expired_ssl(loop: asyncio.AbstractEventLoop) -> None: +async def test_get_expired_ssl() -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector(enable_cleanup_closed=True) key = ConnectionKey("localhost", 80, True, False, None, None, None) try: @@ -459,7 +467,8 @@ async def test_release_acquired_closed(key: ConnectionKey) -> None: await conn.close() -async def test_release(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> None: +async def test_release(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector() with mock.patch.object(conn, "_release_waiter", autospec=True, spec_set=True) as m: proto = create_mocked_conn(loop, should_close=False) @@ -478,11 +487,11 @@ async def test_release(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> N @pytest.mark.usefixtures("enable_cleanup_closed") async def test_release_ssl_transport( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, ssl_key: ConnectionKey + ssl_key: ConnectionKey, ) -> None: conn = aiohttp.BaseConnector(enable_cleanup_closed=True) with mock.patch.object(conn, "_release_waiter", autospec=True, spec_set=True): - proto = create_mocked_conn(loop) + proto = create_mocked_conn(asyncio.get_running_loop()) transport = proto.transport conn._acquired.add(proto) conn._acquired_per_host[ssl_key].add(proto) @@ -510,9 +519,7 @@ async def test_release_already_closed(key: ConnectionKey) -> None: assert not m2.called -async def test_release_waiter_no_limit( - loop: asyncio.AbstractEventLoop, key: ConnectionKey, key2: ConnectionKey -) -> None: +async def test_release_waiter_no_limit(key: ConnectionKey, key2: ConnectionKey) -> None: # limit is 0 conn = aiohttp.BaseConnector(limit=0) w = mock.Mock() @@ -525,7 +532,7 @@ async def test_release_waiter_no_limit( async def test_release_waiter_first_available( - loop: asyncio.AbstractEventLoop, key: ConnectionKey, key2: ConnectionKey + key: ConnectionKey, key2: ConnectionKey ) -> None: conn = aiohttp.BaseConnector() w1, w2 = mock.Mock(), mock.Mock() @@ -544,7 +551,7 @@ async def test_release_waiter_first_available( async def test_release_waiter_release_first( - loop: asyncio.AbstractEventLoop, key: ConnectionKey, key2: ConnectionKey + key: ConnectionKey, key2: ConnectionKey ) -> None: conn = aiohttp.BaseConnector(limit=1) w1, w2 = mock.Mock(), mock.Mock() @@ -559,7 +566,7 @@ async def test_release_waiter_release_first( async def test_release_waiter_skip_done_waiter( - loop: asyncio.AbstractEventLoop, key: ConnectionKey, key2: ConnectionKey + key: ConnectionKey, key2: ConnectionKey ) -> None: conn = aiohttp.BaseConnector(limit=1) w1, w2 = mock.Mock(), mock.Mock() @@ -573,9 +580,7 @@ async def test_release_waiter_skip_done_waiter( await conn.close() -async def test_release_waiter_per_host( - loop: asyncio.AbstractEventLoop, key: ConnectionKey, key2: ConnectionKey -) -> None: +async def test_release_waiter_per_host(key: ConnectionKey, key2: ConnectionKey) -> None: # no limit conn = aiohttp.BaseConnector(limit=0, limit_per_host=2) w1, w2 = mock.Mock(), mock.Mock() @@ -591,7 +596,7 @@ async def test_release_waiter_per_host( async def test_release_waiter_no_available( - loop: asyncio.AbstractEventLoop, key: ConnectionKey, key2: ConnectionKey + key: ConnectionKey, key2: ConnectionKey ) -> None: # limit is 0 conn = aiohttp.BaseConnector(limit=0) @@ -619,21 +624,17 @@ async def test_release_close(key: ConnectionKey) -> None: await conn.close() -async def test__release_acquired_per_host1( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test__release_acquired_per_host1(key: ConnectionKey) -> None: conn = aiohttp.BaseConnector(limit_per_host=10) - conn._release_acquired(key, create_mocked_conn(loop)) + conn._release_acquired(key, create_mocked_conn(asyncio.get_running_loop())) assert len(conn._acquired_per_host) == 0 await conn.close() -async def test__release_acquired_per_host2( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test__release_acquired_per_host2(key: ConnectionKey) -> None: conn = aiohttp.BaseConnector(limit_per_host=10) - handler = create_mocked_conn(loop) + handler = create_mocked_conn(asyncio.get_running_loop()) conn._acquired_per_host[key].add(handler) conn._release_acquired(key, handler) assert len(conn._acquired_per_host) == 0 @@ -641,9 +642,8 @@ async def test__release_acquired_per_host2( await conn.close() -async def test__release_acquired_per_host3( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test__release_acquired_per_host3(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector(limit_per_host=10) handler = create_mocked_conn(loop) handler2 = create_mocked_conn(loop) @@ -657,10 +657,9 @@ async def test__release_acquired_per_host3( async def test_tcp_connector_certificate_error( - loop: asyncio.AbstractEventLoop, - start_connection: mock.AsyncMock, - make_client_request: _RequestMaker, + start_connection: mock.AsyncMock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() req = make_client_request("GET", URL("https://127.0.0.1:443"), loop=loop) conn = aiohttp.TCPConnector() @@ -682,10 +681,9 @@ async def test_tcp_connector_certificate_error( async def test_tcp_connector_server_hostname_default( - loop: asyncio.AbstractEventLoop, - start_connection: mock.AsyncMock, - make_client_request: _RequestMaker, + start_connection: mock.AsyncMock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector() with mock.patch.object( @@ -702,10 +700,9 @@ async def test_tcp_connector_server_hostname_default( async def test_tcp_connector_server_hostname_override( - loop: asyncio.AbstractEventLoop, - start_connection: mock.AsyncMock, - make_client_request: _RequestMaker, + start_connection: mock.AsyncMock, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector() with mock.patch.object( @@ -724,8 +721,9 @@ async def test_tcp_connector_server_hostname_override( async def test_tcp_connector_multiple_hosts_errors( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector() ip1 = "192.168.1.1" @@ -893,10 +891,9 @@ def get_extra_info(param: str) -> object: [0.1, 0.25, None], ) async def test_tcp_connector_happy_eyeballs( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, - happy_eyeballs_delay: float | None, - make_client_request: _RequestMaker, + happy_eyeballs_delay: float | None, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector(happy_eyeballs_delay=happy_eyeballs_delay) ip1 = "dead::beef::" @@ -981,9 +978,8 @@ async def create_connection( await conn.close() -async def test_tcp_connector_interleave( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker -) -> None: +async def test_tcp_connector_interleave(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector(interleave=2) ip1 = "192.168.1.1" @@ -1076,8 +1072,9 @@ async def create_connection( async def test_tcp_connector_family_is_respected( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector(family=socket.AF_INET) ip1 = "dead::beef::" @@ -1162,10 +1159,9 @@ async def create_connection( ], ) async def test_tcp_connector_multiple_hosts_one_timeout( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, - request_url: str, - make_client_request: _RequestMaker, + request_url: str, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector() ip1 = "192.168.1.1" @@ -1274,7 +1270,7 @@ async def create_connection( await conn.close() -async def test_tcp_connector_resolve_host(loop: asyncio.AbstractEventLoop) -> None: +async def test_tcp_connector_resolve_host() -> None: conn = aiohttp.TCPConnector(use_dns_cache=True) res = await conn._resolve_host("localhost", 8080) @@ -1297,7 +1293,7 @@ async def test_tcp_connector_resolve_host(loop: asyncio.AbstractEventLoop) -> No @pytest.fixture -def dns_response(loop: asyncio.AbstractEventLoop) -> Callable[[], Awaitable[list[str]]]: +def dns_response() -> Callable[[], Awaitable[list[str]]]: async def coro() -> list[str]: # simulates a network operation await asyncio.sleep(0) @@ -1307,7 +1303,7 @@ async def coro() -> list[str]: async def test_tcp_connector_dns_cache_not_expired( - loop: asyncio.AbstractEventLoop, dns_response: Callable[[], Awaitable[list[str]]] + dns_response: Callable[[], Awaitable[list[str]]], ) -> None: with mock.patch("aiohttp.connector.DefaultResolver") as m_resolver: @@ -1326,7 +1322,7 @@ async def test_tcp_connector_dns_cache_not_expired( async def test_tcp_connector_dns_cache_forever( - loop: asyncio.AbstractEventLoop, dns_response: Callable[[], Awaitable[list[str]]] + dns_response: Callable[[], Awaitable[list[str]]], ) -> None: with mock.patch("aiohttp.connector.DefaultResolver") as m_resolver: mock_default_resolver = mock.create_autospec( @@ -1346,7 +1342,7 @@ async def test_tcp_connector_dns_cache_forever( async def test_tcp_connector_use_dns_cache_disabled( - loop: asyncio.AbstractEventLoop, dns_response: Callable[[], Awaitable[list[str]]] + dns_response: Callable[[], Awaitable[list[str]]], ) -> None: with mock.patch("aiohttp.connector.DefaultResolver") as m_resolver: @@ -1374,8 +1370,9 @@ async def test_tcp_connector_use_dns_cache_disabled( async def test_tcp_connector_dns_throttle_requests( - loop: asyncio.AbstractEventLoop, dns_response: Callable[[], Awaitable[list[str]]] + dns_response: Callable[[], Awaitable[list[str]]], ) -> None: + loop = asyncio.get_running_loop() with mock.patch("aiohttp.connector.DefaultResolver") as m_resolver: mock_default_resolver = mock.create_autospec( AbstractResolver, instance=True, spec_set=True @@ -1404,9 +1401,8 @@ async def mock_resolve(*_args: object, **_kwargs: object) -> list[str]: await conn.close() -async def test_tcp_connector_dns_throttle_requests_exception_spread( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_dns_throttle_requests_exception_spread() -> None: + loop = asyncio.get_running_loop() with mock.patch("aiohttp.connector.DefaultResolver") as m_resolver: e = Exception() @@ -1431,8 +1427,9 @@ async def test_tcp_connector_dns_throttle_requests_exception_spread( async def test_tcp_connector_dns_throttle_requests_cancelled_when_close( - loop: asyncio.AbstractEventLoop, dns_response: Callable[[], Awaitable[list[str]]] + dns_response: Callable[[], Awaitable[list[str]]], ) -> None: + loop = asyncio.get_running_loop() with mock.patch("aiohttp.connector.DefaultResolver") as m_resolver: async def mock_resolve(*_args: object, **_kwargs: object) -> list[str]: @@ -1459,9 +1456,7 @@ async def mock_resolve(*_args: object, **_kwargs: object) -> list[str]: @pytest.fixture -def dns_response_error( - loop: asyncio.AbstractEventLoop, -) -> Callable[[], Awaitable[NoReturn]]: +def dns_response_error() -> Callable[[], Awaitable[NoReturn]]: async def coro() -> NoReturn: # simulates a network operation await asyncio.sleep(0) @@ -1471,10 +1466,10 @@ async def coro() -> NoReturn: async def test_tcp_connector_cancel_dns_error_captured( - loop: asyncio.AbstractEventLoop, dns_response_error: Callable[[], Awaitable[NoReturn]], make_client_request: _RequestMaker, ) -> None: + loop = asyncio.get_running_loop() exception_handler_called = False def exception_handler(loop: asyncio.AbstractEventLoop, context: object) -> None: @@ -1504,7 +1499,7 @@ def exception_handler(loop: asyncio.AbstractEventLoop, context: object) -> None: async def test_tcp_connector_dns_tracing( - loop: asyncio.AbstractEventLoop, dns_response: Callable[[], Awaitable[list[str]]] + dns_response: Callable[[], Awaitable[list[str]]], ) -> None: session = mock.Mock() trace_config_ctx = mock.Mock() @@ -1552,7 +1547,7 @@ async def test_tcp_connector_dns_tracing( async def test_tcp_connector_dns_tracing_cache_disabled( - loop: asyncio.AbstractEventLoop, dns_response: Callable[[], Awaitable[list[str]]] + dns_response: Callable[[], Awaitable[list[str]]], ) -> None: session = mock.Mock() trace_config_ctx = mock.Mock() @@ -1610,8 +1605,9 @@ async def test_tcp_connector_dns_tracing_cache_disabled( async def test_tcp_connector_dns_tracing_throttle_requests( - loop: asyncio.AbstractEventLoop, dns_response: Callable[[], Awaitable[list[str]]] + dns_response: Callable[[], Awaitable[list[str]]], ) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_dns_cache_hit = mock.AsyncMock() @@ -1655,9 +1651,8 @@ async def test_tcp_connector_close_resolver() -> None: m_resolver.close.assert_awaited_once() -async def test_dns_error( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker -) -> None: +async def test_dns_error(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() connector = aiohttp.TCPConnector() with mock.patch.object( connector, @@ -1674,9 +1669,7 @@ async def test_dns_error( await connector.close() -async def test_get_pop_empty_conns( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_get_pop_empty_conns(key: ConnectionKey) -> None: # see issue #473 conn = aiohttp.BaseConnector() assert await conn._get(key, []) is None @@ -1685,13 +1678,11 @@ async def test_get_pop_empty_conns( await conn.close() -async def test_release_close_do_not_add_to_pool( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_release_close_do_not_add_to_pool(key: ConnectionKey) -> None: # see issue #473 conn = aiohttp.BaseConnector() - proto = create_mocked_conn(loop, should_close=True) + proto = create_mocked_conn(asyncio.get_running_loop(), should_close=True) conn._acquired.add(proto) conn._release(key, proto) @@ -1701,8 +1692,9 @@ async def test_release_close_do_not_add_to_pool( async def test_release_close_do_not_delete_existing_connections( - loop: asyncio.AbstractEventLoop, key: ConnectionKey + key: ConnectionKey, ) -> None: + loop = asyncio.get_running_loop() proto1 = create_mocked_conn(loop) conn = aiohttp.BaseConnector() @@ -1716,9 +1708,7 @@ async def test_release_close_do_not_delete_existing_connections( await conn.close() -async def test_release_not_started( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_release_not_started(key: ConnectionKey) -> None: conn = aiohttp.BaseConnector() proto = create_mocked_conn(should_close=False) conn._acquired.add(proto) @@ -1726,17 +1716,15 @@ async def test_release_not_started( # assert conn._conns == {key: [(proto, 10)]} rec = conn._conns[key] assert rec[0][0] == proto - assert rec[0][1] == pytest.approx(loop.time(), abs=0.05) + assert rec[0][1] == pytest.approx(asyncio.get_running_loop().time(), abs=0.05) assert not proto.close.called await conn.close() -async def test_release_not_opened( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_release_not_opened(key: ConnectionKey) -> None: conn = aiohttp.BaseConnector() - proto = create_mocked_conn(loop) + proto = create_mocked_conn(asyncio.get_running_loop()) conn._acquired.add(proto) conn._release(key, proto) assert proto.close.called @@ -1744,11 +1732,8 @@ async def test_release_not_opened( await conn.close() -async def test_connect( - loop: asyncio.AbstractEventLoop, - key: ConnectionKey, - make_client_request: _RequestMaker, -) -> None: +async def test_connect(key: ConnectionKey, make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -1770,9 +1755,8 @@ async def test_connect( await conn.close() -async def test_connect_tracing( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker -) -> None: +async def test_connect_tracing(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_connection_create_start = mock.AsyncMock() @@ -1814,8 +1798,9 @@ async def test_connect_tracing( ], ) async def test_exception_during_connetion_create_tracing( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, signal: str, make_client_request: _RequestMaker + signal: str, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_signal = mock.AsyncMock(side_effect=asyncio.CancelledError) @@ -1848,8 +1833,9 @@ async def test_exception_during_connetion_create_tracing( # type: ignore[misc] async def test_exception_during_connection_queued_tracing( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_signal = mock.AsyncMock(side_effect=asyncio.CancelledError) @@ -1889,8 +1875,9 @@ async def test_exception_during_connection_queued_tracing( async def test_exception_during_connection_reuse_tracing( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_signal = mock.AsyncMock(side_effect=asyncio.CancelledError) @@ -1930,9 +1917,9 @@ async def test_exception_during_connection_reuse_tracing( async def test_cancellation_during_waiting_for_free_connection( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, ) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() waiter_wait_stated_future = loop.create_future() @@ -1974,9 +1961,8 @@ async def on_connection_queued_start(*args: object, **kwargs: object) -> None: assert key not in conn._acquired_per_host -async def test_close_during_connect( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker -) -> None: +async def test_close_during_connect(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -2041,8 +2027,9 @@ async def test_cleanup(key: ConnectionKey) -> None: @pytest.mark.usefixtures("enable_cleanup_closed") async def test_cleanup_close_ssl_transport( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, ssl_key: ConnectionKey + ssl_key: ConnectionKey, ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) transport = proto.transport testset: defaultdict[ConnectionKey, deque[tuple[ResponseHandler, float]]] = ( @@ -2068,7 +2055,7 @@ async def test_cleanup_close_ssl_transport( # type: ignore[misc] await asyncio.sleep(0) # Give cleanup a chance to close transports -async def test_cleanup2(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> None: +async def test_cleanup2(key: ConnectionKey) -> None: m = create_mocked_conn() m.is_connected.return_value = True testset: defaultdict[ConnectionKey, deque[tuple[ResponseHandler, float]]] = ( @@ -2089,7 +2076,8 @@ async def test_cleanup2(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> await conn.close() -async def test_cleanup3(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> None: +async def test_cleanup3(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() m = create_mocked_conn(loop) m.is_connected.return_value = True testset: defaultdict[ConnectionKey, deque[tuple[ResponseHandler, float]]] = ( @@ -2113,10 +2101,8 @@ async def test_cleanup3(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> @pytest.mark.usefixtures("enable_cleanup_closed") -async def test_cleanup_closed( - loop: asyncio.AbstractEventLoop, mocker: MockerFixture -) -> None: - m = mocker.spy(loop, "call_at") +async def test_cleanup_closed(mocker: MockerFixture) -> None: + m = mocker.spy(asyncio.get_running_loop(), "call_at") conn = aiohttp.BaseConnector(enable_cleanup_closed=True) tr = mock.Mock() @@ -2141,9 +2127,7 @@ async def test_cleanup_closed_is_noop_on_fixed_cpython() -> None: assert conn._cleanup_closed_disabled is True -async def test_cleanup_closed_disabled( - loop: asyncio.AbstractEventLoop, mocker: MockerFixture -) -> None: +async def test_cleanup_closed_disabled(mocker: MockerFixture) -> None: conn = aiohttp.BaseConnector(enable_cleanup_closed=False) tr = mock.Mock() @@ -2155,7 +2139,7 @@ async def test_cleanup_closed_disabled( await conn.close() -async def test_tcp_connector_ctor(loop: asyncio.AbstractEventLoop) -> None: +async def test_tcp_connector_ctor() -> None: conn = aiohttp.TCPConnector() assert conn._ssl is True @@ -2169,9 +2153,7 @@ async def test_tcp_connector_ctor(loop: asyncio.AbstractEventLoop) -> None: sys.version_info < (3, 11), reason="Use test_tcp_connector_ssl_shutdown_timeout_pre_311 for Python < 3.11", ) -async def test_tcp_connector_ssl_shutdown_timeout( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_ssl_shutdown_timeout() -> None: # Test default value (no warning expected) conn = aiohttp.TCPConnector() assert conn._ssl_shutdown_timeout == 0 @@ -2198,9 +2180,7 @@ async def test_tcp_connector_ssl_shutdown_timeout( sys.version_info >= (3, 11), reason="This test is for Python < 3.11 runtime warning behavior", ) -async def test_tcp_connector_ssl_shutdown_timeout_pre_311( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_ssl_shutdown_timeout_pre_311() -> None: """Test that both deprecation and runtime warnings are issued on Python < 3.11.""" # Test custom value - expect both deprecation and runtime warnings with warnings.catch_warnings(record=True) as w: @@ -2218,11 +2198,10 @@ async def test_tcp_connector_ssl_shutdown_timeout_pre_311( sys.version_info < (3, 11), reason="ssl_shutdown_timeout requires Python 3.11+" ) async def test_tcp_connector_ssl_shutdown_timeout_passed_to_create_connection( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, - start_connection: mock.AsyncMock, - make_client_request: _RequestMaker, + start_connection: mock.AsyncMock, make_client_request: _RequestMaker ) -> None: # Test that ssl_shutdown_timeout is passed to create_connection for SSL connections + loop = asyncio.get_running_loop() with pytest.warns( DeprecationWarning, match="ssl_shutdown_timeout parameter is deprecated" ): @@ -2281,11 +2260,10 @@ async def test_tcp_connector_ssl_shutdown_timeout_passed_to_create_connection( @pytest.mark.skipif(sys.version_info >= (3, 11), reason="Test for Python < 3.11") async def test_tcp_connector_ssl_shutdown_timeout_not_passed_pre_311( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, - start_connection: mock.AsyncMock, - make_client_request: _RequestMaker, + start_connection: mock.AsyncMock, make_client_request: _RequestMaker ) -> None: # Test that ssl_shutdown_timeout is NOT passed to create_connection on Python < 3.11 + loop = asyncio.get_running_loop() with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") conn = aiohttp.TCPConnector(ssl_shutdown_timeout=2.5) @@ -2312,9 +2290,7 @@ async def test_tcp_connector_ssl_shutdown_timeout_not_passed_pre_311( # type: i await conn.close() -async def test_tcp_connector_close_abort_ssl_when_shutdown_timeout_zero( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_close_abort_ssl_when_shutdown_timeout_zero() -> None: """Test that close() uses abort() for SSL connections when ssl_shutdown_timeout=0.""" with pytest.warns( DeprecationWarning, match="ssl_shutdown_timeout parameter is deprecated" @@ -2342,9 +2318,9 @@ async def test_tcp_connector_close_abort_ssl_when_shutdown_timeout_zero( proto.close.assert_not_called() -async def test_tcp_connector_close_doesnt_abort_non_ssl_when_shutdown_timeout_zero( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_close_doesnt_abort_non_ssl_when_shutdown_timeout_zero() -> ( + None +): """Test that close() still uses close() for non-SSL connections even when ssl_shutdown_timeout=0.""" with pytest.warns( DeprecationWarning, match="ssl_shutdown_timeout parameter is deprecated" @@ -2372,9 +2348,7 @@ async def test_tcp_connector_close_doesnt_abort_non_ssl_when_shutdown_timeout_ze proto.abort.assert_not_called() -async def test_tcp_connector_ssl_shutdown_timeout_warning_pre_311( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_ssl_shutdown_timeout_warning_pre_311() -> None: """Test that a warning is issued for non-zero ssl_shutdown_timeout on Python < 3.11.""" with ( mock.patch.object(sys, "version_info", (3, 10, 0)), @@ -2413,9 +2387,7 @@ async def test_tcp_connector_ssl_shutdown_timeout_warning_pre_311( await conn.close() -async def test_tcp_connector_ssl_shutdown_timeout_zero_no_warning_pre_311( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_ssl_shutdown_timeout_zero_no_warning_pre_311() -> None: """Test that no warning is issued for ssl_shutdown_timeout=0 on Python < 3.11.""" with ( mock.patch.object(sys, "version_info", (3, 10, 0)), @@ -2433,9 +2405,7 @@ async def test_tcp_connector_ssl_shutdown_timeout_zero_no_warning_pre_311( await conn.close() -async def test_tcp_connector_ssl_shutdown_timeout_sentinel_no_warning_pre_311( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_ssl_shutdown_timeout_sentinel_no_warning_pre_311() -> None: """Test that no warning is issued when sentinel is used on Python < 3.11.""" with ( mock.patch.object(sys, "version_info", (3, 10, 0)), @@ -2451,11 +2421,10 @@ async def test_tcp_connector_ssl_shutdown_timeout_sentinel_no_warning_pre_311( async def test_tcp_connector_ssl_shutdown_timeout_zero_not_passed( - loop: asyncio.AbstractEventLoop, - start_connection: mock.AsyncMock, - make_client_request: _RequestMaker, + start_connection: mock.AsyncMock, make_client_request: _RequestMaker ) -> None: """Test that ssl_shutdown_timeout=0 is NOT passed to create_connection.""" + loop = asyncio.get_running_loop() with pytest.warns( DeprecationWarning, match="ssl_shutdown_timeout parameter is deprecated" ): @@ -2484,11 +2453,10 @@ async def test_tcp_connector_ssl_shutdown_timeout_zero_not_passed( sys.version_info < (3, 11), reason="ssl_shutdown_timeout requires Python 3.11+" ) async def test_tcp_connector_ssl_shutdown_timeout_nonzero_passed( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, - start_connection: mock.AsyncMock, - make_client_request: _RequestMaker, + start_connection: mock.AsyncMock, make_client_request: _RequestMaker ) -> None: """Test that non-zero ssl_shutdown_timeout IS passed to create_connection on Python 3.11+.""" + loop = asyncio.get_running_loop() with pytest.warns( DeprecationWarning, match="ssl_shutdown_timeout parameter is deprecated" ): @@ -2513,9 +2481,7 @@ async def test_tcp_connector_ssl_shutdown_timeout_nonzero_passed( # type: ignor await conn.close() -async def test_tcp_connector_close_abort_ssl_connections_in_conns( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_close_abort_ssl_connections_in_conns() -> None: """Test that SSL connections in _conns are aborted when ssl_shutdown_timeout=0.""" with pytest.warns( DeprecationWarning, match="ssl_shutdown_timeout parameter is deprecated" @@ -2533,7 +2499,7 @@ async def test_tcp_connector_close_abort_ssl_connections_in_conns( # Add the protocol to _conns key = ConnectionKey("host", 443, True, True, None, None, None) - conn._conns[key] = deque([(proto, loop.time())]) + conn._conns[key] = deque([(proto, asyncio.get_running_loop().time())]) # Close the connector await conn.close() @@ -2543,14 +2509,12 @@ async def test_tcp_connector_close_abort_ssl_connections_in_conns( proto.close.assert_not_called() -async def test_tcp_connector_allowed_protocols(loop: asyncio.AbstractEventLoop) -> None: +async def test_tcp_connector_allowed_protocols() -> None: conn = aiohttp.TCPConnector() assert conn.allowed_protocol_schema_set == {"", "tcp", "http", "https", "ws", "wss"} -async def test_start_tls_exception_with_ssl_shutdown_timeout_zero( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_start_tls_exception_with_ssl_shutdown_timeout_zero() -> None: """Test _start_tls_connection exception handling with ssl_shutdown_timeout=0.""" with pytest.warns( DeprecationWarning, match="ssl_shutdown_timeout parameter is deprecated" @@ -2582,9 +2546,7 @@ async def test_start_tls_exception_with_ssl_shutdown_timeout_zero( sys.version_info < (3, 11), reason="Use test_start_tls_exception_with_ssl_shutdown_timeout_nonzero_pre_311 for Python < 3.11", ) -async def test_start_tls_exception_with_ssl_shutdown_timeout_nonzero( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_start_tls_exception_with_ssl_shutdown_timeout_nonzero() -> None: """Test _start_tls_connection exception handling with ssl_shutdown_timeout>0.""" with pytest.warns( DeprecationWarning, match="ssl_shutdown_timeout parameter is deprecated" @@ -2616,9 +2578,7 @@ async def test_start_tls_exception_with_ssl_shutdown_timeout_nonzero( sys.version_info >= (3, 11), reason="This test is for Python < 3.11 runtime warning behavior", ) -async def test_start_tls_exception_with_ssl_shutdown_timeout_nonzero_pre_311( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_start_tls_exception_with_ssl_shutdown_timeout_nonzero_pre_311() -> None: """Test _start_tls_connection exception handling with ssl_shutdown_timeout>0 on Python < 3.11.""" with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") @@ -2671,9 +2631,7 @@ async def test_invalid_ssl_param() -> None: aiohttp.TCPConnector(ssl=object()) # type: ignore[arg-type] -async def test_tcp_connector_ctor_fingerprint_valid( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_ctor_fingerprint_valid() -> None: valid = aiohttp.Fingerprint(hashlib.sha256(b"foo").digest()) conn = aiohttp.TCPConnector(ssl=valid) assert conn._ssl is valid @@ -2681,17 +2639,17 @@ async def test_tcp_connector_ctor_fingerprint_valid( await conn.close() -async def test_insecure_fingerprint_md5(loop: asyncio.AbstractEventLoop) -> None: +async def test_insecure_fingerprint_md5() -> None: with pytest.raises(ValueError): aiohttp.TCPConnector(ssl=aiohttp.Fingerprint(hashlib.md5(b"foo").digest())) -async def test_insecure_fingerprint_sha1(loop: asyncio.AbstractEventLoop) -> None: +async def test_insecure_fingerprint_sha1() -> None: with pytest.raises(ValueError): aiohttp.TCPConnector(ssl=aiohttp.Fingerprint(hashlib.sha1(b"foo").digest())) -async def test_tcp_connector_clear_dns_cache(loop: asyncio.AbstractEventLoop) -> None: +async def test_tcp_connector_clear_dns_cache() -> None: conn = aiohttp.TCPConnector() h1: ResolveResult = { "hostname": "a", @@ -2730,9 +2688,7 @@ async def test_tcp_connector_clear_dns_cache(loop: asyncio.AbstractEventLoop) -> await conn.close() -async def test_tcp_connector_clear_dns_cache_bad_args( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_clear_dns_cache_bad_args() -> None: conn = aiohttp.TCPConnector() with pytest.raises(ValueError): conn.clear_dns_cache("localhost") @@ -2817,8 +2773,8 @@ async def test_ssl_context_once() -> None: assert conn3._get_ssl_context(req) is _SSL_CONTEXT_VERIFIED -async def test_close_twice(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> None: - proto: ResponseHandler = create_mocked_conn(loop) +async def test_close_twice(key: ConnectionKey) -> None: + proto: ResponseHandler = create_mocked_conn(asyncio.get_running_loop()) conn = aiohttp.BaseConnector() conn._conns[key] = deque([(proto, 0)]) @@ -2833,9 +2789,7 @@ async def test_close_twice(loop: asyncio.AbstractEventLoop, key: ConnectionKey) assert conn.closed -async def test_close_cancels_cleanup_handle( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_close_cancels_cleanup_handle(key: ConnectionKey) -> None: conn = aiohttp.BaseConnector() conn._release(key, create_mocked_conn(should_close=False)) assert conn._cleanup_handle is not None @@ -2843,9 +2797,8 @@ async def test_close_cancels_cleanup_handle( assert conn._cleanup_handle is None -async def test_close_cancels_resolve_host( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker -) -> None: +async def test_close_cancels_resolve_host(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() cancelled = False async def delay_resolve(*args: object, **kwargs: object) -> None: @@ -2879,9 +2832,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> None: async def test_multiple_dns_resolution_requests_success( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: """Verify that multiple DNS resolution requests are handled correctly.""" + loop = asyncio.get_running_loop() async def delay_resolve(*args: object, **kwargs: object) -> list[ResolveResult]: """Delayed resolve() task.""" @@ -2941,9 +2895,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> list[ResolveResult]: async def test_multiple_dns_resolution_requests_failure( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: """Verify that DNS resolution failure for multiple requests is handled correctly.""" + loop = asyncio.get_running_loop() async def delay_resolve(*args: object, **kwargs: object) -> list[ResolveResult]: """Delayed resolve() task.""" @@ -2994,9 +2949,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> list[ResolveResult]: async def test_multiple_dns_resolution_requests_cancelled( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: """Verify that DNS resolution cancellation does not affect other tasks.""" + loop = asyncio.get_running_loop() async def delay_resolve(*args: object, **kwargs: object) -> list[ResolveResult]: """Delayed resolve() task.""" @@ -3046,9 +3002,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> list[ResolveResult]: async def test_multiple_dns_resolution_requests_first_cancelled( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: """Verify that first DNS resolution cancellation does not make other resolutions fail.""" + loop = asyncio.get_running_loop() async def delay_resolve(*args: object, **kwargs: object) -> list[ResolveResult]: """Delayed resolve() task.""" @@ -3109,9 +3066,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> list[ResolveResult]: async def test_multiple_dns_resolution_requests_first_fails_second_successful( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: """Verify that first DNS resolution fails the first time and is successful the second time.""" + loop = asyncio.get_running_loop() attempt = 0 async def delay_resolve(*args: object, **kwargs: object) -> list[ResolveResult]: @@ -3188,7 +3146,7 @@ async def delay_resolve(*args: object, **kwargs: object) -> list[ResolveResult]: assert len(conn._resolve_host_tasks) == 0 -async def test_close_abort_closed_transports(loop: asyncio.AbstractEventLoop) -> None: +async def test_close_abort_closed_transports() -> None: tr = mock.Mock() conn = aiohttp.BaseConnector() @@ -3201,25 +3159,21 @@ async def test_close_abort_closed_transports(loop: asyncio.AbstractEventLoop) -> @pytest.mark.usefixtures("enable_cleanup_closed") -async def test_close_cancels_cleanup_closed_handle( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_close_cancels_cleanup_closed_handle() -> None: conn = aiohttp.BaseConnector(enable_cleanup_closed=True) assert conn._cleanup_closed_handle is not None await conn.close() assert conn._cleanup_closed_handle is None -async def test_ctor_with_default_loop(loop: asyncio.AbstractEventLoop) -> None: +async def test_ctor_with_default_loop() -> None: conn = aiohttp.BaseConnector() - assert loop is conn._loop + assert asyncio.get_running_loop() is conn._loop await conn.close() -async def test_base_connector_allows_high_level_protocols( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_base_connector_allows_high_level_protocols() -> None: conn = aiohttp.BaseConnector() assert conn.allowed_protocol_schema_set == { "", @@ -3231,10 +3185,9 @@ async def test_base_connector_allows_high_level_protocols( async def test_connect_with_limit( - loop: asyncio.AbstractEventLoop, - key: ConnectionKey, - make_client_request: _RequestMaker, + key: ConnectionKey, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3277,10 +3230,9 @@ async def f() -> None: async def test_connect_queued_operation_tracing( - loop: asyncio.AbstractEventLoop, - key: ConnectionKey, - make_client_request: _RequestMaker, + key: ConnectionKey, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_connection_queued_start = mock.AsyncMock() @@ -3326,10 +3278,9 @@ async def f() -> None: async def test_connect_reuseconn_tracing( - loop: asyncio.AbstractEventLoop, - key: ConnectionKey, - make_client_request: _RequestMaker, + key: ConnectionKey, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_connection_reuseconn = mock.AsyncMock() @@ -3369,12 +3320,12 @@ async def test_connect_reuseconn_tracing( ], ) async def test_connect_reuse_proxy_headers( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker, test_case: str, wait_for_con: bool, expect_proxy_auth_header: bool, ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3447,10 +3398,9 @@ async def _create_con(*args: Any, **kwargs: Any) -> None: async def test_connect_with_limit_and_limit_per_host( - loop: asyncio.AbstractEventLoop, - key: ConnectionKey, - make_client_request: _RequestMaker, + key: ConnectionKey, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3484,10 +3434,9 @@ async def f() -> None: async def test_connect_with_no_limit_and_limit_per_host( - loop: asyncio.AbstractEventLoop, - key: ConnectionKey, - make_client_request: _RequestMaker, + key: ConnectionKey, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3519,10 +3468,9 @@ async def f() -> None: async def test_connect_with_no_limits( - loop: asyncio.AbstractEventLoop, - key: ConnectionKey, - make_client_request: _RequestMaker, + key: ConnectionKey, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3554,10 +3502,9 @@ async def f() -> None: async def test_connect_with_limit_cancelled( - loop: asyncio.AbstractEventLoop, - key: ConnectionKey, - make_client_request: _RequestMaker, + key: ConnectionKey, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3582,9 +3529,7 @@ async def test_connect_with_limit_cancelled( await conn.close() -async def test_connect_with_capacity_release_waiters( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_connect_with_capacity_release_waiters() -> None: async def check_with_exc(err: Exception) -> None: conn = aiohttp.BaseConnector(limit=1) with mock.patch.object( @@ -3604,8 +3549,9 @@ async def check_with_exc(err: Exception) -> None: async def test_connect_with_limit_concurrent( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.should_close = False proto.is_connected.return_value = True @@ -3665,9 +3611,8 @@ async def f(start: bool = True) -> None: assert max_connections == num_connections -async def test_connect_waiters_cleanup( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker -) -> None: +async def test_connect_waiters_cleanup(make_client_request: _RequestMaker) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3688,8 +3633,9 @@ async def test_connect_waiters_cleanup( async def test_connect_waiters_cleanup_key_error( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3716,10 +3662,9 @@ async def test_connect_waiters_cleanup_key_error( async def test_close_with_acquired_connection( - loop: asyncio.AbstractEventLoop, - key: ConnectionKey, - make_client_request: _RequestMaker, + key: ConnectionKey, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3743,51 +3688,48 @@ async def test_close_with_acquired_connection( assert connection.closed -async def test_default_force_close(loop: asyncio.AbstractEventLoop) -> None: +async def test_default_force_close() -> None: connector = aiohttp.BaseConnector() assert not connector.force_close await connector.close() -async def test_limit_property(loop: asyncio.AbstractEventLoop) -> None: +async def test_limit_property() -> None: conn = aiohttp.BaseConnector(limit=15) assert 15 == conn.limit await conn.close() -async def test_limit_per_host_property(loop: asyncio.AbstractEventLoop) -> None: +async def test_limit_per_host_property() -> None: conn = aiohttp.BaseConnector(limit_per_host=15) assert 15 == conn.limit_per_host await conn.close() -async def test_limit_property_default(loop: asyncio.AbstractEventLoop) -> None: +async def test_limit_property_default() -> None: conn = aiohttp.BaseConnector() assert conn.limit == 100 await conn.close() -async def test_limit_per_host_property_default(loop: asyncio.AbstractEventLoop) -> None: +async def test_limit_per_host_property_default() -> None: conn = aiohttp.BaseConnector() assert conn.limit_per_host == 0 await conn.close() -async def test_force_close_and_explicit_keep_alive( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_force_close_and_explicit_keep_alive() -> None: aiohttp.BaseConnector(force_close=True) aiohttp.BaseConnector(force_close=True, keepalive_timeout=None) with pytest.raises(ValueError): aiohttp.BaseConnector(keepalive_timeout=30, force_close=True) -async def test_error_on_connection( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_error_on_connection(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector(limit=1, limit_per_host=10) req = mock.Mock() @@ -3833,7 +3775,8 @@ async def create_connection( await conn.close() -async def test_cancelled_waiter(loop: asyncio.AbstractEventLoop) -> None: +async def test_cancelled_waiter() -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector(limit=1) req = mock.Mock() req.connection_key = "key" @@ -3856,9 +3799,8 @@ async def create_connection(req: object, traces: object = None) -> ResponseHandl await conn.close() -async def test_error_on_connection_with_cancelled_waiter( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_error_on_connection_with_cancelled_waiter(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.BaseConnector(limit=1, limit_per_host=10) req = mock.Mock() @@ -3912,9 +3854,7 @@ async def create_connection( await conn.close() -async def test_tcp_connector( - aiohttp_client: AiohttpClient, loop: asyncio.AbstractEventLoop -) -> None: +async def test_tcp_connector(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.Response: return web.Response() @@ -3928,8 +3868,9 @@ async def handler(request: web.Request) -> web.Response: @pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="requires UNIX sockets") async def test_unix_connector_not_found( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: + loop = asyncio.get_running_loop() connector = aiohttp.UnixConnector("/" + uuid.uuid4().hex) req = make_client_request("GET", URL("http://www.python.org"), loop=loop) @@ -3939,8 +3880,9 @@ async def test_unix_connector_not_found( # type: ignore[misc] @pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="requires UNIX sockets") async def test_unix_connector_permission( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: + loop = asyncio.get_running_loop() m = mock.AsyncMock(side_effect=PermissionError()) with mock.patch.object(loop, "create_unix_connection", m): connector = aiohttp.UnixConnector("/" + uuid.uuid4().hex) @@ -4004,7 +3946,7 @@ async def test_default_use_dns_cache() -> None: async def test_resolver_not_called_with_address_is_ip( - loop: asyncio.AbstractEventLoop, make_client_request: _RequestMaker + make_client_request: _RequestMaker, ) -> None: resolver = mock.MagicMock() connector = aiohttp.TCPConnector(resolver=resolver) @@ -4012,7 +3954,7 @@ async def test_resolver_not_called_with_address_is_ip( req = make_client_request( "GET", URL(f"http://127.0.0.1:{unused_port()}"), - loop=loop, + loop=asyncio.get_running_loop(), response_class=mock.Mock(), ) @@ -4413,7 +4355,7 @@ async def send_dns_cache_hit(self, *args: object, **kwargs: object) -> None: await connector.close() -async def test_connector_throttle_trace_race(loop: asyncio.AbstractEventLoop) -> None: +async def test_connector_throttle_trace_race() -> None: key = ("", 0) token: ResolveResult = { "hostname": "localhost", @@ -4442,9 +4384,7 @@ async def send_dns_cache_hit(self, *args: object, **kwargs: object) -> None: await connector.close() -async def test_connector_resolve_in_case_of_trace_cache_miss_exception( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_connector_resolve_in_case_of_trace_cache_miss_exception() -> None: token: ResolveResult = { "hostname": "localhost", "host": "127.0.0.1", @@ -4504,10 +4444,9 @@ async def resolve_response( async def test_connector_does_not_remove_needed_waiters( - loop: asyncio.AbstractEventLoop, - key: ConnectionKey, - make_client_request: _RequestMaker, + key: ConnectionKey, make_client_request: _RequestMaker ) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -4586,11 +4525,10 @@ def test_connect() -> Literal[True]: async def test_tcp_connector_socket_factory( - loop: asyncio.AbstractEventLoop, - start_connection: mock.AsyncMock, - make_client_request: _RequestMaker, + start_connection: mock.AsyncMock, make_client_request: _RequestMaker ) -> None: """Check that socket factory is called""" + loop = asyncio.get_running_loop() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: start_connection.return_value = s @@ -4720,10 +4658,9 @@ async def test_available_connections_no_limits( assert conn._available_connections(other_host_key2) == 1 -async def test_connect_tunnel_connection_release( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_connect_tunnel_connection_release() -> None: """Test _ConnectTunnelConnection.release() does not pool the connection.""" + loop = asyncio.get_running_loop() connector = mock.create_autospec( aiohttp.BaseConnector, spec_set=True, instance=True ) diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 80adbb7dd15..0588342109a 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -395,10 +395,9 @@ async def test_timer_context_timeout_does_not_leak_upward() -> None: ) async def test_timer_context_timeout_does_swallow_cancellation() -> None: """Verify that the TimerContext does not swallow cancellation.""" - loop = asyncio.get_running_loop() current_task = asyncio.current_task() assert current_task is not None - ctx = helpers.TimerContext(loop) + ctx = helpers.TimerContext(asyncio.get_running_loop()) async def task_with_timeout() -> None: new_task = asyncio.current_task() @@ -430,16 +429,14 @@ def test_timer_context_no_task(loop: asyncio.AbstractEventLoop) -> None: pass -async def test_weakref_handle(loop: asyncio.AbstractEventLoop) -> None: +async def test_weakref_handle() -> None: cb = mock.Mock() - helpers.weakref_handle(cb, "test", 0.01, loop) + helpers.weakref_handle(cb, "test", 0.01, asyncio.get_running_loop()) await asyncio.sleep(0.1) assert cb.test.called -async def test_weakref_handle_with_small_threshold( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_weakref_handle_with_small_threshold() -> None: cb = mock.Mock() loop = mock.Mock() loop.time.return_value = 10 @@ -449,9 +446,9 @@ async def test_weakref_handle_with_small_threshold( ) -async def test_weakref_handle_weak(loop: asyncio.AbstractEventLoop) -> None: +async def test_weakref_handle_weak() -> None: cb = mock.Mock() - helpers.weakref_handle(cb, "test", 0.01, loop) + helpers.weakref_handle(cb, "test", 0.01, asyncio.get_running_loop()) del cb gc.collect() await asyncio.sleep(0.1) @@ -468,7 +465,7 @@ def test_ceil_call_later() -> None: loop.call_at.assert_called_with(21.0, cb) -async def test_ceil_timeout_round(loop: asyncio.AbstractEventLoop) -> None: +async def test_ceil_timeout_round() -> None: async with helpers.ceil_timeout(7.5) as cm: if sys.version_info >= (3, 11): w = cm.when() @@ -480,7 +477,7 @@ async def test_ceil_timeout_round(loop: asyncio.AbstractEventLoop) -> None: assert frac == 0 -async def test_ceil_timeout_small(loop: asyncio.AbstractEventLoop) -> None: +async def test_ceil_timeout_small() -> None: async with helpers.ceil_timeout(1.1) as cm: if sys.version_info >= (3, 11): w = cm.when() @@ -508,7 +505,7 @@ def test_ceil_call_later_no_timeout() -> None: assert not loop.call_at.called -async def test_ceil_timeout_none(loop: asyncio.AbstractEventLoop) -> None: +async def test_ceil_timeout_none() -> None: async with helpers.ceil_timeout(None) as cm: if sys.version_info >= (3, 11): assert cm.when() is None @@ -516,9 +513,7 @@ async def test_ceil_timeout_none(loop: asyncio.AbstractEventLoop) -> None: assert cm.deadline is None -async def test_ceil_timeout_small_with_overriden_threshold( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_ceil_timeout_small_with_overriden_threshold() -> None: async with helpers.ceil_timeout(1.5, ceil_threshold=1) as cm: if sys.version_info >= (3, 11): w = cm.when() @@ -752,14 +747,14 @@ def test_get_env_proxy_for_url(proxy_env_vars: dict[str, str], url_input: str) - # ------------- set_result / set_exception ---------------------- -async def test_set_result(loop: asyncio.AbstractEventLoop) -> None: - fut = loop.create_future() +async def test_set_result() -> None: + fut = asyncio.get_running_loop().create_future() helpers.set_result(fut, 123) assert 123 == await fut -async def test_set_result_cancelled(loop: asyncio.AbstractEventLoop) -> None: - fut = loop.create_future() +async def test_set_result_cancelled() -> None: + fut = asyncio.get_running_loop().create_future() fut.cancel() helpers.set_result(fut, 123) @@ -767,15 +762,15 @@ async def test_set_result_cancelled(loop: asyncio.AbstractEventLoop) -> None: await fut -async def test_set_exception(loop: asyncio.AbstractEventLoop) -> None: - fut = loop.create_future() +async def test_set_exception() -> None: + fut = asyncio.get_running_loop().create_future() helpers.set_exception(fut, RuntimeError()) with pytest.raises(RuntimeError): await fut -async def test_set_exception_cancelled(loop: asyncio.AbstractEventLoop) -> None: - fut = loop.create_future() +async def test_set_exception_cancelled() -> None: + fut = asyncio.get_running_loop().create_future() fut.cancel() helpers.set_exception(fut, RuntimeError()) diff --git a/tests/test_http_parser.py b/tests/test_http_parser.py index 0e66b18c625..8233f5d85db 100644 --- a/tests/test_http_parser.py +++ b/tests/test_http_parser.py @@ -1717,9 +1717,8 @@ async def test_http_response_parser_bad_chunked_lax( @pytest.mark.dev_mode -async def test_http_response_parser_bad_chunked_strict_py( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_http_response_parser_bad_chunked_strict_py() -> None: + loop = asyncio.get_running_loop() protocol = ResponseHandler(loop) response = HttpResponseParserPy( @@ -1742,9 +1741,8 @@ async def test_http_response_parser_bad_chunked_strict_py( "HttpRequestParserC" not in dir(aiohttp.http_parser), reason="C based HTTP parser not available", ) -async def test_http_response_parser_bad_chunked_strict_c( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_http_response_parser_bad_chunked_strict_c() -> None: + loop = asyncio.get_running_loop() protocol = ResponseHandler(loop) response = HttpResponseParserC( diff --git a/tests/test_http_writer.py b/tests/test_http_writer.py index 091731afe5a..6ae8220e1ea 100644 --- a/tests/test_http_writer.py +++ b/tests/test_http_writer.py @@ -57,7 +57,7 @@ def writelines(chunks: Iterable[bytes]) -> None: @pytest.fixture -def protocol(loop: asyncio.AbstractEventLoop, transport: asyncio.Transport) -> Any: +def protocol(transport: asyncio.Transport) -> Any: return mock.create_autospec( BaseProtocol, spec_set=True, instance=True, transport=transport ) @@ -94,12 +94,9 @@ def test_payloadwriter_properties( async def test_write_headers_buffered_small_payload( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) headers = CIMultiDict({"Content-Length": "11", "Host": "example.com"}) # Write headers - should be buffered @@ -117,12 +114,9 @@ async def test_write_headers_buffered_small_payload( async def test_write_headers_chunked_coalescing( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() headers = CIMultiDict({"Transfer-Encoding": "chunked", "Host": "example.com"}) @@ -141,12 +135,9 @@ async def test_write_headers_chunked_coalescing( async def test_write_eof_with_buffered_headers( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) headers = CIMultiDict({"Content-Length": "9", "Host": "example.com"}) # Write headers - should be buffered @@ -162,12 +153,9 @@ async def test_write_eof_with_buffered_headers( async def test_set_eof_sends_buffered_headers( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) headers = CIMultiDict({"Host": "example.com"}) # Write headers - should be buffered @@ -183,11 +171,9 @@ async def test_set_eof_sends_buffered_headers( async def test_write_payload_eof( - transport: asyncio.Transport, - protocol: BaseProtocol, - loop: asyncio.AbstractEventLoop, + transport: asyncio.Transport, protocol: BaseProtocol ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) await msg.write(b"data1") await msg.write(b"data2") @@ -198,12 +184,9 @@ async def test_write_payload_eof( async def test_write_payload_chunked( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() await msg.write(b"data") await msg.write_eof() @@ -212,12 +195,9 @@ async def test_write_payload_chunked( async def test_write_payload_chunked_multiple( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() await msg.write(b"data1") await msg.write(b"data2") @@ -227,11 +207,9 @@ async def test_write_payload_chunked_multiple( async def test_write_payload_length( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.length = 2 await msg.write(b"d") await msg.write(b"ata") @@ -244,11 +222,9 @@ async def test_write_payload_length( @pytest.mark.usefixtures("disable_writelines") @pytest.mark.internal # Used for performance benchmarking async def test_write_large_payload_deflate_compression_data_in_eof( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write(b"data" * 4096) @@ -271,11 +247,9 @@ async def test_write_large_payload_deflate_compression_data_in_eof( @pytest.mark.usefixtures("disable_writelines") @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_large_payload_deflate_compression_data_in_eof_all_zlib( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write(b"data" * 4096) @@ -305,11 +279,9 @@ async def test_write_large_payload_deflate_compression_data_in_eof_all_zlib( @pytest.mark.usefixtures("enable_writelines") @pytest.mark.internal # Used for performance benchmarking async def test_write_large_payload_deflate_compression_data_in_eof_writelines( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write(b"data" * 4096) @@ -333,11 +305,9 @@ async def test_write_large_payload_deflate_compression_data_in_eof_writelines( @pytest.mark.usefixtures("enable_writelines") @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_large_payload_deflate_compression_data_in_eof_writelines_all_zlib( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write(b"data" * 4096) @@ -368,11 +338,9 @@ async def test_write_large_payload_deflate_compression_data_in_eof_writelines_al async def test_write_payload_chunked_filter( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() await msg.write(b"da") await msg.write(b"ta") @@ -384,11 +352,9 @@ async def test_write_payload_chunked_filter( async def test_write_payload_chunked_filter_multiple_chunks( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() await msg.write(b"da") await msg.write(b"ta") @@ -405,12 +371,10 @@ async def test_write_payload_chunked_filter_multiple_chunks( @pytest.mark.internal # Used for performance benchmarking async def test_write_payload_deflate_compression( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: COMPRESSED = b"x\x9cKI,I\x04\x00\x04\x00\x01\x9b" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write(b"data") await msg.write_eof() @@ -423,11 +387,9 @@ async def test_write_payload_deflate_compression( @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_payload_deflate_compression_all_zlib( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write(b"data") await msg.write_eof() @@ -440,12 +402,10 @@ async def test_write_payload_deflate_compression_all_zlib( @pytest.mark.internal # Used for performance benchmarking async def test_write_payload_deflate_compression_chunked( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: expected = b"2\r\nx\x9c\r\na\r\nKI,I\x04\x00\x04\x00\x01\x9b\r\n0\r\n\r\n" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() await msg.write(b"data") @@ -459,11 +419,9 @@ async def test_write_payload_deflate_compression_chunked( @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_payload_deflate_compression_chunked_all_zlib( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() await msg.write(b"data") @@ -479,12 +437,10 @@ async def test_write_payload_deflate_compression_chunked_all_zlib( @pytest.mark.usefixtures("force_writelines_small_payloads") @pytest.mark.internal # Used for performance benchmarking async def test_write_payload_deflate_compression_chunked_writelines( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: expected = b"2\r\nx\x9c\r\na\r\nKI,I\x04\x00\x04\x00\x01\x9b\r\n0\r\n\r\n" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() await msg.write(b"data") @@ -500,11 +456,9 @@ async def test_write_payload_deflate_compression_chunked_writelines( @pytest.mark.usefixtures("force_writelines_small_payloads") @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_payload_deflate_compression_chunked_writelines_all_zlib( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() await msg.write(b"data") @@ -518,12 +472,9 @@ async def test_write_payload_deflate_compression_chunked_writelines_all_zlib( @pytest.mark.internal # Used for performance benchmarking async def test_write_payload_deflate_and_chunked( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -537,12 +488,9 @@ async def test_write_payload_deflate_and_chunked( @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_payload_deflate_and_chunked_all_zlib( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -555,12 +503,10 @@ async def test_write_payload_deflate_and_chunked_all_zlib( @pytest.mark.internal # Used for performance benchmarking async def test_write_payload_deflate_compression_chunked_data_in_eof( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: expected = b"2\r\nx\x9c\r\nd\r\nKI,IL\xcdK\x01\x00\x0b@\x02\xd2\r\n0\r\n\r\n" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() await msg.write(b"data") @@ -574,11 +520,9 @@ async def test_write_payload_deflate_compression_chunked_data_in_eof( @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_payload_deflate_compression_chunked_data_in_eof_all_zlib( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() await msg.write(b"data") @@ -594,12 +538,10 @@ async def test_write_payload_deflate_compression_chunked_data_in_eof_all_zlib( @pytest.mark.usefixtures("force_writelines_small_payloads") @pytest.mark.internal # Used for performance benchmarking async def test_write_payload_deflate_compression_chunked_data_in_eof_writelines( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: expected = b"2\r\nx\x9c\r\nd\r\nKI,IL\xcdK\x01\x00\x0b@\x02\xd2\r\n0\r\n\r\n" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() await msg.write(b"data") @@ -615,11 +557,9 @@ async def test_write_payload_deflate_compression_chunked_data_in_eof_writelines( @pytest.mark.usefixtures("force_writelines_small_payloads") @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_payload_deflate_compression_chunked_data_in_eof_writelines_all_zlib( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() await msg.write(b"data") @@ -633,11 +573,9 @@ async def test_write_payload_deflate_compression_chunked_data_in_eof_writelines_ @pytest.mark.internal # Used for performance benchmarking async def test_write_large_payload_deflate_compression_chunked_data_in_eof( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -660,11 +598,9 @@ async def test_write_large_payload_deflate_compression_chunked_data_in_eof( @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_large_payload_deflate_compression_chunked_data_in_eof_all_zlib( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -689,11 +625,9 @@ async def test_write_large_payload_deflate_compression_chunked_data_in_eof_all_z @pytest.mark.usefixtures("force_writelines_small_payloads") @pytest.mark.internal # Used for performance benchmarking async def test_write_large_payload_deflate_compression_chunked_data_in_eof_writelines( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -718,11 +652,9 @@ async def test_write_large_payload_deflate_compression_chunked_data_in_eof_write @pytest.mark.usefixtures("force_writelines_small_payloads") @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_large_payload_deflate_compression_chunked_data_in_eof_writelines_all_zlib( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -745,11 +677,9 @@ async def test_write_large_payload_deflate_compression_chunked_data_in_eof_write @pytest.mark.internal # Used for performance benchmarking async def test_write_payload_deflate_compression_chunked_connection_lost( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() await msg.write(b"data") @@ -764,11 +694,9 @@ async def test_write_payload_deflate_compression_chunked_connection_lost( @pytest.mark.usefixtures("parametrize_zlib_backend") async def test_write_payload_deflate_compression_chunked_connection_lost_all_zlib( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() await msg.write(b"data") @@ -782,12 +710,9 @@ async def test_write_payload_deflate_compression_chunked_connection_lost_all_zli async def test_write_payload_bytes_memoryview( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) mv = memoryview(b"abcd") @@ -799,12 +724,9 @@ async def test_write_payload_bytes_memoryview( async def test_write_payload_short_ints_memoryview( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() payload = memoryview(array.array("H", [65, 66, 67])) @@ -820,12 +742,9 @@ async def test_write_payload_short_ints_memoryview( async def test_write_payload_2d_shape_memoryview( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() mv = memoryview(b"ABCDEF") @@ -839,12 +758,9 @@ async def test_write_payload_2d_shape_memoryview( async def test_write_payload_slicing_long_memoryview( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.length = 4 mv = memoryview(b"ABCDEF") @@ -858,11 +774,9 @@ async def test_write_payload_slicing_long_memoryview( async def test_write_drain( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) with mock.patch.object(msg, "drain", autospec=True, spec_set=True) as m: await msg.write(b"1" * (64 * 1024 * 2), drain=False) assert not m.called @@ -873,11 +787,11 @@ async def test_write_drain( async def test_write_calls_callback( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: + loop = asyncio.get_running_loop() + async def on_chunk_sent(chunk: bytes) -> None: """Mock signature""" @@ -890,10 +804,10 @@ async def on_chunk_sent(chunk: bytes) -> None: async def test_write_eof_calls_callback( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: + loop = asyncio.get_running_loop() + async def on_chunk_sent(chunk: bytes) -> None: """Mock signature""" @@ -906,11 +820,9 @@ async def on_chunk_sent(chunk: bytes) -> None: async def test_write_to_closing_transport( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) await msg.write(b"Before closing") transport.is_closing.return_value = True # type: ignore[attr-defined] @@ -920,16 +832,14 @@ async def test_write_to_closing_transport( async def test_write_to_closed_transport( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test that writing to a closed transport raises ClientConnectionResetError. The StreamWriter checks to see if protocol.transport is None before writing to the transport. If it is None, it raises ConnectionResetError. """ - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) await msg.write(b"Before transport close") protocol.transport = None @@ -940,33 +850,25 @@ async def test_write_to_closed_transport( await msg.write(b"After transport closed") -async def test_drain( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, -) -> None: - msg = http.StreamWriter(protocol, loop) +async def test_drain(protocol: BaseProtocol, transport: asyncio.Transport) -> None: + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) await msg.drain() assert protocol._drain_helper.called # type: ignore[attr-defined] async def test_drain_no_transport( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg._protocol.transport = None await msg.drain() assert not protocol._drain_helper.called # type: ignore[attr-defined] async def test_write_headers_prevents_injection( - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) status_line = "HTTP/1.1 200 OK" wrong_headers = CIMultiDict({"Set-Cookie: abc=123\r\nContent-Length": "256"}) with pytest.raises(ValueError): @@ -977,11 +879,9 @@ async def test_write_headers_prevents_injection( async def test_set_eof_after_write_headers( - protocol: BaseProtocol, - transport: mock.Mock, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: mock.Mock ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) status_line = "HTTP/1.1 200 OK" good_headers = CIMultiDict({"Set-Cookie": "abc=123"}) @@ -1000,11 +900,9 @@ async def test_set_eof_after_write_headers( async def test_write_headers_does_not_write_immediately( - protocol: BaseProtocol, - transport: mock.Mock, - loop: asyncio.AbstractEventLoop, + protocol: BaseProtocol, transport: mock.Mock ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) status_line = "HTTP/1.1 200 OK" headers = CIMultiDict({"Content-Type": "text/plain"}) @@ -1019,12 +917,9 @@ async def test_write_headers_does_not_write_immediately( async def test_write_headers_with_compression_coalescing( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") headers = CIMultiDict({"Content-Encoding": "deflate", "Host": "example.com"}) @@ -1083,13 +978,10 @@ def test_serialize_headers_raises_on_null_byte() -> None: async def test_write_compressed_data_with_headers_coalescing( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test that headers are coalesced with compressed data in write() method.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") headers = CIMultiDict({"Content-Encoding": "deflate", "Host": "example.com"}) @@ -1107,13 +999,10 @@ async def test_write_compressed_data_with_headers_coalescing( async def test_write_compressed_chunked_with_headers_coalescing( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test headers coalescing with compressed chunked data.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() headers = CIMultiDict( @@ -1137,13 +1026,10 @@ async def test_write_compressed_chunked_with_headers_coalescing( async def test_write_multiple_compressed_chunks_after_headers_sent( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test multiple compressed writes after headers are already sent.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") headers = CIMultiDict({"Content-Encoding": "deflate"}) @@ -1166,13 +1052,10 @@ async def test_write_multiple_compressed_chunks_after_headers_sent( async def test_write_eof_empty_compressed_with_buffered_headers( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test write_eof with no data but compression enabled and buffered headers.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") headers = CIMultiDict({"Content-Encoding": "deflate"}) @@ -1191,13 +1074,10 @@ async def test_write_eof_empty_compressed_with_buffered_headers( async def test_write_compressed_gzip_with_headers_coalescing( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test gzip compression with header coalescing.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("gzip") headers = CIMultiDict({"Content-Encoding": "gzip"}) @@ -1216,13 +1096,10 @@ async def test_write_compressed_gzip_with_headers_coalescing( async def test_compression_with_content_length_constraint( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test compression respects content length constraints.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.length = 5 # Set small content length headers = CIMultiDict({"Content-Length": "5"}) @@ -1241,13 +1118,10 @@ async def test_compression_with_content_length_constraint( async def test_write_compressed_zero_length_chunk( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test writing empty chunk with compression.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write_headers("POST /data HTTP/1.1", CIMultiDict()) @@ -1264,13 +1138,10 @@ async def test_write_compressed_zero_length_chunk( async def test_chunked_compressed_eof_coalescing( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test chunked compressed data with EOF marker coalescing.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() headers = CIMultiDict( @@ -1309,14 +1180,11 @@ async def test_chunked_compressed_eof_coalescing( async def test_compression_different_strategies( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test compression with different strategies.""" # Test with best speed strategy (default) - msg1 = http.StreamWriter(protocol, loop) + msg1 = http.StreamWriter(protocol, asyncio.get_running_loop()) msg1.enable_compression("deflate") # Default strategy await msg1.write_headers("POST /fast HTTP/1.1", CIMultiDict()) @@ -1335,13 +1203,10 @@ async def test_compression_different_strategies( async def test_chunked_headers_single_write_with_set_eof( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test that set_eof combines headers and chunked EOF in single write.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() # Write headers - should be buffered @@ -1370,13 +1235,10 @@ async def test_chunked_headers_single_write_with_set_eof( async def test_send_headers_forces_header_write( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test that send_headers() forces writing buffered headers.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) headers = CIMultiDict({"Content-Length": "10", "Host": "example.com"}) # Write headers (should be buffered) @@ -1399,13 +1261,10 @@ async def test_send_headers_forces_header_write( async def test_send_headers_idempotent( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test that send_headers() is idempotent and safe to call multiple times.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) headers = CIMultiDict({"Content-Length": "5", "Host": "example.com"}) # Write headers (should be buffered) @@ -1427,13 +1286,10 @@ async def test_send_headers_idempotent( async def test_send_headers_no_buffered_headers( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test that send_headers() is safe when no headers are buffered.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) # Call send_headers without writing headers first msg.send_headers() # Should not crash @@ -1441,13 +1297,10 @@ async def test_send_headers_no_buffered_headers( async def test_write_drain_condition_with_small_buffer( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test that drain is not called when buffer_size <= LIMIT.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) # Write headers first await msg.write_headers("GET /test HTTP/1.1", CIMultiDict()) @@ -1470,13 +1323,10 @@ async def test_write_drain_condition_with_small_buffer( async def test_write_drain_condition_with_large_buffer( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test that drain is called only when drain=True AND buffer_size > LIMIT.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) # Write headers first await msg.write_headers("GET /test HTTP/1.1", CIMultiDict()) @@ -1499,13 +1349,10 @@ async def test_write_drain_condition_with_large_buffer( async def test_write_no_drain_with_large_buffer( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test that drain is not called when drain=False even with large buffer.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) # Write headers first await msg.write_headers("GET /test HTTP/1.1", CIMultiDict()) @@ -1528,12 +1375,10 @@ async def test_write_no_drain_with_large_buffer( async def test_set_eof_idempotent( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test that set_eof() is idempotent and can be called multiple times safely.""" + loop = asyncio.get_running_loop() msg = http.StreamWriter(protocol, loop) # Test 1: Multiple set_eof calls with buffered headers @@ -1594,13 +1439,10 @@ async def test_set_eof_idempotent( async def test_non_chunked_write_empty_body( - buf: bytearray, - protocol: BaseProtocol, - transport: mock.Mock, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: mock.Mock ) -> None: """Test non-chunked response with empty body.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) # Non-chunked response with Content-Length: 0 headers = CIMultiDict({"Content-Length": "0"}) @@ -1615,13 +1457,10 @@ async def test_non_chunked_write_empty_body( async def test_chunked_headers_sent_with_empty_chunk_not_eof( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test chunked encoding where headers are sent without data and not EOF.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() headers = CIMultiDict({"Transfer-Encoding": "chunked"}) @@ -1639,13 +1478,10 @@ async def test_chunked_headers_sent_with_empty_chunk_not_eof( async def test_chunked_set_eof_after_headers_sent( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test chunked encoding where set_eof is called after headers already sent.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() headers = CIMultiDict({"Transfer-Encoding": "chunked"}) @@ -1665,13 +1501,10 @@ async def test_chunked_set_eof_after_headers_sent( @pytest.mark.usefixtures("enable_writelines") @pytest.mark.usefixtures("force_writelines_small_payloads") async def test_write_eof_chunked_with_data_using_writelines( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test write_eof with chunked data that uses writelines (line 336).""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() headers = CIMultiDict({"Transfer-Encoding": "chunked"}) @@ -1697,13 +1530,10 @@ async def test_write_eof_chunked_with_data_using_writelines( async def test_send_headers_with_payload_chunked_eof_no_data( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, + buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: """Test _send_headers_with_payload with chunked, is_eof=True but no chunk data.""" - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() headers = CIMultiDict({"Transfer-Encoding": "chunked"}) diff --git a/tests/test_proxy_functional.py b/tests/test_proxy_functional.py index 7c92b840790..cedbf19b014 100644 --- a/tests/test_proxy_functional.py +++ b/tests/test_proxy_functional.py @@ -279,9 +279,7 @@ async def handler(request: web.Request) -> web.Response: @pytest.fixture def proxy_test_server( - aiohttp_raw_server: AiohttpRawServer, - loop: asyncio.AbstractEventLoop, - monkeypatch: pytest.MonkeyPatch, + aiohttp_raw_server: AiohttpRawServer, monkeypatch: pytest.MonkeyPatch ) -> Callable[[], Awaitable[mock.Mock]]: # Handle all proxy requests and imitate remote server response. @@ -450,7 +448,6 @@ async def test_proxy_http_auth_from_url( async def test_proxy_http_acquired_cleanup( proxy_test_server: Callable[[], Awaitable[mock.Mock]], - loop: asyncio.AbstractEventLoop, ) -> None: url = "http://aiohttp.io/path" @@ -473,7 +470,6 @@ async def test_proxy_http_acquired_cleanup( @pytest.mark.skip("we need to reconsider how we test this") async def test_proxy_http_acquired_cleanup_force( proxy_test_server: Callable[[], Awaitable[mock.Mock]], - loop: asyncio.AbstractEventLoop, ) -> None: url = "http://aiohttp.io/path" @@ -498,7 +494,6 @@ async def request() -> None: @pytest.mark.skip("we need to reconsider how we test this") async def test_proxy_http_multi_conn_limit( proxy_test_server: Callable[[], Awaitable[mock.Mock]], - loop: asyncio.AbstractEventLoop, ) -> None: url = "http://aiohttp.io/path" limit, multi_conn_num = 1, 5 @@ -569,7 +564,6 @@ async def test_proxy_https_connect_with_port( @pytest.mark.xfail async def test_proxy_https_send_body( proxy_test_server: Callable[[], Awaitable[mock.Mock]], - loop: asyncio.AbstractEventLoop, ) -> None: sess = aiohttp.ClientSession() try: @@ -671,7 +665,6 @@ async def test_proxy_https_auth( @pytest.mark.xfail async def test_proxy_https_acquired_cleanup( proxy_test_server: Callable[[], Awaitable[mock.Mock]], - loop: asyncio.AbstractEventLoop, ) -> None: url = "https://secure.aiohttp.io/path" @@ -697,7 +690,6 @@ async def request() -> None: @pytest.mark.xfail async def test_proxy_https_acquired_cleanup_force( proxy_test_server: Callable[[], Awaitable[mock.Mock]], - loop: asyncio.AbstractEventLoop, ) -> None: url = "https://secure.aiohttp.io/path" @@ -723,7 +715,6 @@ async def request() -> None: @pytest.mark.xfail async def test_proxy_https_multi_conn_limit( proxy_test_server: Callable[[], Awaitable[mock.Mock]], - loop: asyncio.AbstractEventLoop, ) -> None: url = "https://secure.aiohttp.io/path" limit, multi_conn_num = 1, 5 diff --git a/tests/test_resolver.py b/tests/test_resolver.py index e19df43e7e2..822946aec96 100644 --- a/tests/test_resolver.py +++ b/tests/test_resolver.py @@ -166,9 +166,7 @@ async def fake(*args: Any, **kwargs: Any) -> tuple[str, int]: @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") @pytest.mark.usefixtures("check_no_lingering_resolvers") -async def test_async_resolver_positive_ipv4_lookup( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_async_resolver_positive_ipv4_lookup() -> None: with patch("aiodns.DNSResolver") as mock: mock().getaddrinfo.return_value = fake_aiodns_getaddrinfo_ipv4_result( ["127.0.0.1"] @@ -188,9 +186,7 @@ async def test_async_resolver_positive_ipv4_lookup( @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") @pytest.mark.usefixtures("check_no_lingering_resolvers") -async def test_async_resolver_positive_link_local_ipv6_lookup( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_async_resolver_positive_link_local_ipv6_lookup() -> None: with patch("aiodns.DNSResolver") as mock: mock().getaddrinfo.return_value = fake_aiodns_getaddrinfo_ipv6_result( ["fe80::1"] @@ -214,7 +210,7 @@ async def test_async_resolver_positive_link_local_ipv6_lookup( @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") @pytest.mark.usefixtures("check_no_lingering_resolvers") -async def test_async_resolver_multiple_replies(loop: asyncio.AbstractEventLoop) -> None: +async def test_async_resolver_multiple_replies() -> None: with patch("aiodns.DNSResolver") as mock: ips = ["127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4"] mock().getaddrinfo.return_value = fake_aiodns_getaddrinfo_ipv4_result(ips) @@ -227,7 +223,7 @@ async def test_async_resolver_multiple_replies(loop: asyncio.AbstractEventLoop) @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") @pytest.mark.usefixtures("check_no_lingering_resolvers") -async def test_async_resolver_negative_lookup(loop: asyncio.AbstractEventLoop) -> None: +async def test_async_resolver_negative_lookup() -> None: with patch("aiodns.DNSResolver") as mock: mock().getaddrinfo.side_effect = aiodns.error.DNSError() resolver = AsyncResolver() @@ -238,9 +234,7 @@ async def test_async_resolver_negative_lookup(loop: asyncio.AbstractEventLoop) - @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") @pytest.mark.usefixtures("check_no_lingering_resolvers") -async def test_async_resolver_no_hosts_in_getaddrinfo( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_async_resolver_no_hosts_in_getaddrinfo() -> None: with patch("aiodns.DNSResolver") as mock: mock().getaddrinfo.return_value = fake_aiodns_getaddrinfo_ipv4_result([]) resolver = AsyncResolver() @@ -344,21 +338,20 @@ async def unknown_addrinfo(*args: Any, **kwargs: Any) -> _UnknownAddrInfo: assert len(res) == 0 -async def test_close_for_threaded_resolver(loop: asyncio.AbstractEventLoop) -> None: +async def test_close_for_threaded_resolver() -> None: resolver = ThreadedResolver() await resolver.close() @pytest.mark.skipif(aiodns is None, reason="aiodns required") @pytest.mark.usefixtures("check_no_lingering_resolvers") -async def test_close_for_async_resolver(loop: asyncio.AbstractEventLoop) -> None: +async def test_close_for_async_resolver() -> None: resolver = AsyncResolver() await resolver.close() -async def test_default_loop_for_threaded_resolver( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_default_loop_for_threaded_resolver() -> None: + loop = asyncio.get_running_loop() asyncio.set_event_loop(loop) resolver = ThreadedResolver() assert resolver._loop is loop @@ -366,9 +359,7 @@ async def test_default_loop_for_threaded_resolver( @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") @pytest.mark.usefixtures("check_no_lingering_resolvers") -async def test_async_resolver_ipv6_positive_lookup( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_async_resolver_ipv6_positive_lookup() -> None: with patch("aiodns.DNSResolver") as mock: mock().getaddrinfo.return_value = fake_aiodns_getaddrinfo_ipv6_result(["::1"]) resolver = AsyncResolver() @@ -386,9 +377,7 @@ async def test_async_resolver_ipv6_positive_lookup( @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") @pytest.mark.usefixtures("check_no_lingering_resolvers") -async def test_async_resolver_error_messages_passed( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_async_resolver_error_messages_passed() -> None: """Ensure error messages are passed through from aiodns.""" with patch("aiodns.DNSResolver", autospec=True, spec_set=True) as mock: mock().getaddrinfo.side_effect = aiodns.error.DNSError(1, "Test error message") @@ -402,9 +391,7 @@ async def test_async_resolver_error_messages_passed( @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") @pytest.mark.usefixtures("check_no_lingering_resolvers") -async def test_async_resolver_error_messages_passed_no_hosts( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_async_resolver_error_messages_passed_no_hosts() -> None: """Ensure error messages are passed through from aiodns.""" with patch("aiodns.DNSResolver", autospec=True, spec_set=True) as mock: mock().getaddrinfo.return_value = fake_aiodns_getaddrinfo_ipv6_result([]) @@ -418,7 +405,7 @@ async def test_async_resolver_error_messages_passed_no_hosts( @pytest.mark.usefixtures("check_no_lingering_resolvers") async def test_async_resolver_aiodns_not_present( - loop: asyncio.AbstractEventLoop, monkeypatch: pytest.MonkeyPatch + monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr("aiohttp.resolver.aiodns", None) with pytest.raises(RuntimeError): diff --git a/tests/test_streams.py b/tests/test_streams.py index 2680b226266..036f3080d32 100644 --- a/tests/test_streams.py +++ b/tests/test_streams.py @@ -1136,7 +1136,7 @@ async def test_empty_stream_reader_iter_chunks() -> None: @pytest.fixture async def buffer(loop: asyncio.AbstractEventLoop) -> streams.DataQueue[bytes]: - return streams.DataQueue(loop) + return streams.DataQueue(asyncio.get_running_loop()) class TestDataQueue: diff --git a/tests/test_test_utils.py b/tests/test_test_utils.py index e1577a1ab1c..a1445640ed9 100644 --- a/tests/test_test_utils.py +++ b/tests/test_test_utils.py @@ -129,9 +129,7 @@ async def test_get_route() -> None: loop.run_until_complete(test_get_route()) -async def test_client_websocket( - loop: asyncio.AbstractEventLoop, test_client: _TestClient -) -> None: +async def test_client_websocket(test_client: _TestClient) -> None: resp = await test_client.ws_connect("/websocket") await resp.send_str("foo") msg = await resp.receive() @@ -142,9 +140,7 @@ async def test_client_websocket( assert msg.type == aiohttp.WSMsgType.CLOSE -async def test_client_cookie( - loop: asyncio.AbstractEventLoop, test_client: _TestClient -) -> None: +async def test_client_cookie(test_client: _TestClient) -> None: assert not test_client.session.cookie_jar await test_client.get("/cookie") cookies = list(test_client.session.cookie_jar) @@ -155,18 +151,14 @@ async def test_client_cookie( @pytest.mark.parametrize( "method", ["get", "post", "options", "post", "put", "patch", "delete"] ) -async def test_test_client_methods( - method: str, loop: asyncio.AbstractEventLoop, test_client: _TestClient -) -> None: +async def test_test_client_methods(method: str, test_client: _TestClient) -> None: resp = await getattr(test_client, method)("/") assert resp.status == 200 text = await resp.text() assert _hello_world_str == text -async def test_test_client_head( - loop: asyncio.AbstractEventLoop, test_client: _TestClient -) -> None: +async def test_test_client_head(test_client: _TestClient) -> None: resp = await test_client.head("/") assert resp.status == 200 @@ -266,7 +258,7 @@ async def hello(request: web.BaseRequest) -> NoReturn: assert client.port == 0 -async def test_test_server_context_manager(loop: asyncio.AbstractEventLoop) -> None: +async def test_test_server_context_manager() -> None: app = _create_example_app() async with TestServer(app) as server: client = aiohttp.ClientSession() @@ -285,9 +277,7 @@ def test_client_unsupported_arg() -> None: ) -async def test_server_make_url_yarl_compatibility( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_server_make_url_yarl_compatibility() -> None: app = _create_example_app() async with TestServer(app) as server: make_url = server.make_url @@ -335,9 +325,7 @@ async def handler(request: web.Request) -> web.Response: assert num_requests == 1 -async def test_server_context_manager( - app: web.Application, loop: asyncio.AbstractEventLoop -) -> None: +async def test_server_context_manager(app: web.Application) -> None: async with TestServer(app) as server: async with aiohttp.ClientSession() as client: async with client.head(server.make_url("/")) as resp: @@ -348,7 +336,7 @@ async def test_server_context_manager( "method", ["head", "get", "post", "options", "post", "put", "patch", "delete"] ) async def test_client_context_manager_response( - method: str, app: web.Application, loop: asyncio.AbstractEventLoop + method: str, app: web.Application ) -> None: async with TestClient(TestServer(app)) as client: async with getattr(client, method)("/") as resp: @@ -359,9 +347,7 @@ async def test_client_context_manager_response( async def test_custom_port( - loop: asyncio.AbstractEventLoop, - app: web.Application, - unused_port_socket: socket.socket, + app: web.Application, unused_port_socket: socket.socket ) -> None: sock = unused_port_socket port = sock.getsockname()[1] @@ -384,11 +370,9 @@ async def test_custom_port( ("hostname", "expected_host"), [("127.0.0.1", "127.0.0.1"), ("localhost", "127.0.0.1"), ("::1", "::1")], ) -async def test_test_server_hostnames( - hostname: str, expected_host: str, loop: asyncio.AbstractEventLoop -) -> None: +async def test_test_server_hostnames(hostname: str, expected_host: str) -> None: app = _create_example_app() - server = TestServer(app, host=hostname, loop=loop) + server = TestServer(app, host=hostname, loop=asyncio.get_running_loop()) async with server: pass assert server.host == expected_host @@ -396,8 +380,9 @@ async def test_test_server_hostnames( @pytest.mark.parametrize("test_server_cls", [TestServer, RawTestServer]) async def test_base_test_server_socket_factory( - test_server_cls: type, app: web.Application, loop: asyncio.AbstractEventLoop + test_server_cls: type, app: web.Application ) -> None: + loop = asyncio.get_running_loop() factory_called = False def factory(host: str, port: int, family: socket.AddressFamily) -> socket.socket: diff --git a/tests/test_urldispatch.py b/tests/test_urldispatch.py index 6603389f16d..ced5cb54f72 100644 --- a/tests/test_urldispatch.py +++ b/tests/test_urldispatch.py @@ -1,4 +1,3 @@ -import asyncio import pathlib import platform import re @@ -1194,17 +1193,13 @@ def test_subapp_rule_resource(app: web.Application) -> None: resource.url_for() -async def test_add_domain_not_str( - app: web.Application, loop: asyncio.AbstractEventLoop -) -> None: +async def test_add_domain_not_str(app: web.Application) -> None: app = web.Application() with pytest.raises(TypeError): app.add_domain(1, app) # type: ignore[arg-type] -async def test_add_domain( - app: web.Application, loop: asyncio.AbstractEventLoop -) -> None: +async def test_add_domain(app: web.Application) -> None: subapp1 = web.Application() h1 = make_handler() subapp1.router.add_get("/", h1) diff --git a/tests/test_web_middleware.py b/tests/test_web_middleware.py index 00301eccb31..9e8179b0871 100644 --- a/tests/test_web_middleware.py +++ b/tests/test_web_middleware.py @@ -1,4 +1,3 @@ -import asyncio from collections.abc import Awaitable, Callable, Iterable from typing import NoReturn @@ -15,9 +14,7 @@ ] -async def test_middleware_modifies_response( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_middleware_modifies_response(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.Response: return web.Response(body=b"OK") @@ -43,9 +40,7 @@ async def middleware(request: web.Request, handler: Handler) -> web.Response: assert "OK[MIDDLEWARE]" == txt -async def test_middleware_handles_exception( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_middleware_handles_exception(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> NoReturn: raise RuntimeError("Error text") @@ -67,9 +62,7 @@ async def middleware(request: web.Request, handler: Handler) -> web.Response: assert "Error text[MIDDLEWARE]" == txt -async def test_middleware_chain( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_middleware_chain(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.Response: return web.Response(text="OK") @@ -116,9 +109,7 @@ async def middleware(request: web.Request, handler: Handler) -> web.Response: ] -async def test_middleware_subapp( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_middleware_subapp(aiohttp_client: AiohttpClient) -> None: async def sub_handler(request: web.Request) -> web.Response: return web.Response(text="OK") @@ -166,7 +157,7 @@ async def middleware( @pytest.fixture -def cli(loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient) -> CLI: +def cli(aiohttp_client: AiohttpClient) -> CLI: async def handler(request: web.Request) -> web.Response: return web.Response(text="OK") @@ -441,9 +432,7 @@ async def paymethod(request: web.Request) -> NoReturn: assert resp.url.path != "/paymethod" -async def test_old_style_middleware( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_old_style_middleware(aiohttp_client: AiohttpClient) -> None: async def view_handler(request: web.Request) -> web.Response: return web.Response(body=b"OK") @@ -471,9 +460,7 @@ async def middleware(request: web.Request, handler: Handler) -> web.Response: assert "OK[old style middleware]" == txt -async def test_new_style_middleware_class( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_new_style_middleware_class(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.Response: return web.Response(body=b"OK") @@ -499,9 +486,7 @@ async def __call__( assert "OK[new style middleware]" == txt -async def test_new_style_middleware_method( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_new_style_middleware_method(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.Response: return web.Response(body=b"OK") diff --git a/tests/test_web_server.py b/tests/test_web_server.py index 63f27f01b25..ab6b4cc02ac 100644 --- a/tests/test_web_server.py +++ b/tests/test_web_server.py @@ -45,12 +45,10 @@ async def handler(request: web.BaseRequest) -> web.Response: async def test_raw_server_not_http_exception( - aiohttp_raw_server: AiohttpRawServer, - aiohttp_client: AiohttpClient, - loop: asyncio.AbstractEventLoop, + aiohttp_raw_server: AiohttpRawServer, aiohttp_client: AiohttpClient ) -> None: # disable debug mode not to print traceback - loop.set_debug(False) + asyncio.get_running_loop().set_debug(False) exc = RuntimeError("custom runtime error") @@ -74,16 +72,14 @@ async def handler(request: web.BaseRequest) -> NoReturn: async def test_raw_server_logs_invalid_method_with_loop_debug( - aiohttp_raw_server: AiohttpRawServer, - aiohttp_client: AiohttpClient, - loop: asyncio.AbstractEventLoop, + aiohttp_raw_server: AiohttpRawServer, aiohttp_client: AiohttpClient ) -> None: exc = BadHttpMethod(b"\x16\x03\x03\x01F\x01".decode(), "error") async def handler(request: web.BaseRequest) -> NoReturn: raise exc - loop = asyncio.get_event_loop() + loop = asyncio.get_running_loop() loop.set_debug(True) logger = mock.Mock() server = await aiohttp_raw_server(handler, logger=logger) @@ -121,16 +117,14 @@ async def handler(request: web.BaseRequest) -> NoReturn: async def test_raw_server_logs_invalid_method_without_loop_debug( - aiohttp_raw_server: AiohttpRawServer, - aiohttp_client: AiohttpClient, - loop: asyncio.AbstractEventLoop, + aiohttp_raw_server: AiohttpRawServer, aiohttp_client: AiohttpClient ) -> None: exc = BadHttpMethod(b"\x16\x03\x03\x01F\x01".decode(), "error") async def handler(request: web.BaseRequest) -> NoReturn: raise exc - loop = asyncio.get_event_loop() + loop = asyncio.get_running_loop() loop.set_debug(False) logger = mock.Mock() server = await aiohttp_raw_server(handler, logger=logger) @@ -152,9 +146,7 @@ async def handler(request: web.BaseRequest) -> NoReturn: async def test_raw_server_logs_invalid_method_second_request( - aiohttp_raw_server: AiohttpRawServer, - aiohttp_client: AiohttpClient, - loop: asyncio.AbstractEventLoop, + aiohttp_raw_server: AiohttpRawServer, aiohttp_client: AiohttpClient ) -> None: exc = BadHttpMethod(b"\x16\x03\x03\x01F\x01".decode(), "error") request_count = 0 @@ -166,7 +158,7 @@ async def handler(request: web.BaseRequest) -> web.Response: raise exc return web.Response() - loop = asyncio.get_event_loop() + loop = asyncio.get_running_loop() loop.set_debug(False) logger = mock.Mock() server = await aiohttp_raw_server(handler, logger=logger) @@ -185,16 +177,14 @@ async def handler(request: web.BaseRequest) -> web.Response: async def test_raw_server_logs_bad_status_line_as_exception( - aiohttp_raw_server: AiohttpRawServer, - aiohttp_client: AiohttpClient, - loop: asyncio.AbstractEventLoop, + aiohttp_raw_server: AiohttpRawServer, aiohttp_client: AiohttpClient ) -> None: exc = BadStatusLine(b"\x16\x03\x03\x01F\x01".decode(), "error") async def handler(request: web.BaseRequest) -> NoReturn: raise exc - loop = asyncio.get_event_loop() + loop = asyncio.get_running_loop() loop.set_debug(False) logger = mock.Mock() server = await aiohttp_raw_server(handler, logger=logger) @@ -316,12 +306,10 @@ async def handler(request: web.BaseRequest) -> NoReturn: async def test_raw_server_html_exception( - aiohttp_raw_server: AiohttpRawServer, - aiohttp_client: AiohttpClient, - loop: asyncio.AbstractEventLoop, + aiohttp_raw_server: AiohttpRawServer, aiohttp_client: AiohttpClient ) -> None: # disable debug mode not to print traceback - loop.set_debug(False) + asyncio.get_running_loop().set_debug(False) exc = RuntimeError("custom runtime error") diff --git a/tests/test_web_websocket.py b/tests/test_web_websocket.py index 12edb532e28..ecc4e025b47 100644 --- a/tests/test_web_websocket.py +++ b/tests/test_web_websocket.py @@ -28,7 +28,7 @@ def __call__( @pytest.fixture -def app(loop: asyncio.AbstractEventLoop) -> web.Application: +def app() -> web.Application: ret: web.Application = mock.create_autospec(web.Application, spec_set=True) ret.on_response_prepare = aiosignal.Signal(ret) # type: ignore[misc] ret.on_response_prepare.freeze() @@ -120,11 +120,9 @@ async def test_nonstarted_receive_str() -> None: await ws.receive_str() -async def test_cancel_heartbeat_cancels_pending_heartbeat_reset_handle( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_cancel_heartbeat_cancels_pending_heartbeat_reset_handle() -> None: ws = web.WebSocketResponse(heartbeat=0.05) - ws._loop = loop + ws._loop = asyncio.get_running_loop() ws._on_data_received() handle = ws._heartbeat_reset_handle assert handle is not None @@ -219,8 +217,7 @@ async def test_write_non_prepared() -> None: async def test_heartbeat_timeout(make_request: _RequestMaker) -> None: """Verify the transport is closed when the heartbeat timeout is reached.""" - loop = asyncio.get_running_loop() - future = loop.create_future() + future = asyncio.get_running_loop().create_future() req = make_request("GET", "/") assert req.transport is not None req.transport.close.side_effect = lambda: future.set_result(None) # type: ignore[attr-defined] @@ -513,9 +510,7 @@ async def test_write_eof_idempotent(make_request: _RequestMaker) -> None: assert len(req.transport.close.mock_calls) == 1 # type: ignore[attr-defined] -async def test_receive_eofstream_in_reader( - make_request: _RequestMaker, loop: asyncio.AbstractEventLoop -) -> None: +async def test_receive_eofstream_in_reader(make_request: _RequestMaker) -> None: req = make_request("GET", "/") ws = web.WebSocketResponse() await ws.prepare(req) @@ -524,7 +519,7 @@ async def test_receive_eofstream_in_reader( exc = EofStream() ws._reader.read = mock.AsyncMock(side_effect=exc) assert ws._payload_writer is not None - f = loop.create_future() + f = asyncio.get_running_loop().create_future() f.set_result(True) ws._payload_writer.drain.return_value = f # type: ignore[attr-defined] msg = await ws.receive() @@ -532,9 +527,7 @@ async def test_receive_eofstream_in_reader( assert ws.closed -async def test_receive_exception_in_reader( - make_request: _RequestMaker, loop: asyncio.AbstractEventLoop -) -> None: +async def test_receive_exception_in_reader(make_request: _RequestMaker) -> None: req = make_request("GET", "/") ws = web.WebSocketResponse() await ws.prepare(req) @@ -543,7 +536,7 @@ async def test_receive_exception_in_reader( exc = Exception() ws._reader.read = mock.AsyncMock(side_effect=exc) - f = loop.create_future() + f = asyncio.get_running_loop().create_future() assert ws._payload_writer is not None ws._payload_writer.drain.return_value = f # type: ignore[attr-defined] f.set_result(True) @@ -554,9 +547,7 @@ async def test_receive_exception_in_reader( assert len(req.transport.close.mock_calls) == 1 # type: ignore[attr-defined] -async def test_receive_close_but_left_open( - make_request: _RequestMaker, loop: asyncio.AbstractEventLoop -) -> None: +async def test_receive_close_but_left_open(make_request: _RequestMaker) -> None: req = make_request("GET", "/") ws = web.WebSocketResponse() await ws.prepare(req) @@ -565,7 +556,7 @@ async def test_receive_close_but_left_open( ws._reader = mock.Mock() ws._reader.read = mock.AsyncMock(return_value=close_message) - f = loop.create_future() + f = asyncio.get_running_loop().create_future() assert ws._payload_writer is not None ws._payload_writer.drain.return_value = f # type: ignore[attr-defined] f.set_result(True) @@ -576,9 +567,7 @@ async def test_receive_close_but_left_open( assert len(req.transport.close.mock_calls) == 1 # type: ignore[attr-defined] -async def test_receive_closing( - make_request: _RequestMaker, loop: asyncio.AbstractEventLoop -) -> None: +async def test_receive_closing(make_request: _RequestMaker) -> None: req = make_request("GET", "/") ws = web.WebSocketResponse() await ws.prepare(req) @@ -588,7 +577,7 @@ async def test_receive_closing( read_mock = mock.AsyncMock(return_value=closing_message) ws._reader.read = read_mock - f = loop.create_future() + f = asyncio.get_running_loop().create_future() assert ws._payload_writer is not None ws._payload_writer.drain.return_value = f # type: ignore[attr-defined] f.set_result(True) @@ -606,9 +595,7 @@ async def test_receive_closing( assert msg.type == WSMsgType.CLOSING -async def test_close_after_closing( - make_request: _RequestMaker, loop: asyncio.AbstractEventLoop -) -> None: +async def test_close_after_closing(make_request: _RequestMaker) -> None: req = make_request("GET", "/") ws = web.WebSocketResponse() await ws.prepare(req) @@ -617,7 +604,7 @@ async def test_close_after_closing( ws._reader = mock.Mock() ws._reader.read = mock.AsyncMock(return_value=closing_message) - f = loop.create_future() + f = asyncio.get_running_loop().create_future() assert ws._payload_writer is not None ws._payload_writer.drain.return_value = f # type: ignore[attr-defined] f.set_result(True) @@ -632,9 +619,7 @@ async def test_close_after_closing( assert len(req.transport.close.mock_calls) == 1 # type: ignore[unreachable] -async def test_receive_timeouterror( - make_request: _RequestMaker, loop: asyncio.AbstractEventLoop -) -> None: +async def test_receive_timeouterror(make_request: _RequestMaker) -> None: req = make_request("GET", "/") ws = web.WebSocketResponse() await ws.prepare(req) diff --git a/tests/test_web_websocket_functional.py b/tests/test_web_websocket_functional.py index 7257c47ba73..073a7d0d7fc 100644 --- a/tests/test_web_websocket_functional.py +++ b/tests/test_web_websocket_functional.py @@ -16,9 +16,7 @@ from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer -async def test_websocket_can_prepare( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_websocket_can_prepare(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> NoReturn: ws = web.WebSocketResponse() assert not ws.can_prepare(request) @@ -32,9 +30,7 @@ async def handler(request: web.Request) -> NoReturn: assert resp.status == 426 -async def test_websocket_json( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_websocket_json(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() assert ws.can_prepare(request) @@ -65,9 +61,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.receive() # Handle close -async def test_websocket_json_invalid_message( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_websocket_json_invalid_message(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() await ws.prepare(request) @@ -91,9 +85,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.receive() # Handle close -async def test_websocket_send_json( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_websocket_send_json(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() await ws.prepare(request) @@ -118,9 +110,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.receive() # Handle close -async def test_websocket_receive_json( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_websocket_receive_json(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() await ws.prepare(request) @@ -147,10 +137,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.receive() # Handle close -async def test_send_recv_text( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_send_recv_text(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() @@ -182,10 +170,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_send_recv_bytes( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_send_recv_bytes(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() @@ -218,10 +204,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_send_recv_json( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_send_recv_json(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() @@ -255,10 +239,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_close_timeout( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - aborted = loop.create_future() +async def test_close_timeout(aiohttp_client: AiohttpClient) -> None: + aborted = asyncio.get_running_loop().create_future() elapsed = 1e10 # something big async def handler(request: web.Request) -> web.WebSocketResponse: @@ -299,9 +281,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.close() -async def test_concurrent_close( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_concurrent_close(aiohttp_client: AiohttpClient) -> None: srv_ws = None async def handler(request: web.Request) -> web.WebSocketResponse: @@ -336,9 +316,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: assert msg.type == WSMsgType.CLOSED -async def test_concurrent_close_multiple_tasks( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_concurrent_close_multiple_tasks(aiohttp_client: AiohttpClient) -> None: srv_ws = None async def handler(request: web.Request) -> web.WebSocketResponse: @@ -377,9 +355,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: assert msg.type == WSMsgType.CLOSED -async def test_close_op_code_from_client( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_close_op_code_from_client(aiohttp_client: AiohttpClient) -> None: srv_ws: web.WebSocketResponse | None = None async def handler(request: web.Request) -> web.WebSocketResponse: @@ -408,10 +384,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: assert msg.type == WSMsgType.CLOSED -async def test_auto_pong_with_closing_by_peer( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_auto_pong_with_closing_by_peer(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() @@ -439,10 +413,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_ping( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_ping(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() @@ -467,10 +439,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_client_ping( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_client_ping(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() @@ -494,10 +464,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.close() -async def test_pong( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_pong(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse(autoping=False) @@ -530,10 +498,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_change_status( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_change_status(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() @@ -556,10 +522,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.close() -async def test_handle_protocol( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_handle_protocol(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse(protocols=("foo", "bar")) @@ -579,10 +543,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_server_close_handshake( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_server_close_handshake(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse(protocols=("foo", "bar")) @@ -603,10 +565,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_client_close_handshake( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_client_close_handshake(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse(autoclose=False, protocols=("foo", "bar")) @@ -638,9 +598,9 @@ async def handler(request: web.Request) -> web.WebSocketResponse: async def test_server_close_handshake_server_eats_client_messages( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient + aiohttp_client: AiohttpClient, ) -> None: - closed = loop.create_future() + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse(protocols=("foo", "bar")) @@ -668,9 +628,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_receive_timeout( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_receive_timeout(aiohttp_client: AiohttpClient) -> None: raised = False async def handler(request: web.Request) -> web.WebSocketResponse: @@ -696,9 +654,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: assert raised -async def test_custom_receive_timeout( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_custom_receive_timeout(aiohttp_client: AiohttpClient) -> None: raised = False async def handler(request: web.Request) -> web.WebSocketResponse: @@ -724,9 +680,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: assert raised -async def test_heartbeat( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_heartbeat(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse(heartbeat=0.05) await ws.prepare(request) @@ -746,9 +700,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.close() -async def test_heartbeat_no_pong( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_heartbeat_no_pong(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse(heartbeat=0.05) await ws.prepare(request) @@ -766,9 +718,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.close() -async def test_heartbeat_connection_closed( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_heartbeat_connection_closed(aiohttp_client: AiohttpClient) -> None: """Test that the connection is closed while ping is in progress.""" ping_count = 0 @@ -810,9 +760,7 @@ async def handler(request: web.Request) -> NoReturn: await ws.close() -async def test_heartbeat_failure_ends_receive( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_heartbeat_failure_ends_receive(aiohttp_client: AiohttpClient) -> None: """Test that no heartbeat response to the server ends the receive call.""" ws_server_close_code = None ws_server_exception = None @@ -845,7 +793,7 @@ async def handler(request: web.Request) -> NoReturn: async def test_heartbeat_no_pong_send_many_messages( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient + aiohttp_client: AiohttpClient, ) -> None: """Test no pong after sending many messages.""" @@ -874,7 +822,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: async def test_heartbeat_no_pong_receive_many_messages( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient + aiohttp_client: AiohttpClient, ) -> None: """Test no pong after receiving many messages.""" @@ -901,10 +849,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.close() -async def test_server_ws_async_for( - loop: asyncio.AbstractEventLoop, aiohttp_server: AiohttpServer -) -> None: - closed = loop.create_future() +async def test_server_ws_async_for(aiohttp_server: AiohttpServer) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() @@ -934,10 +880,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_closed_async_for( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: - closed = loop.create_future() +async def test_closed_async_for(aiohttp_client: AiohttpClient) -> None: + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() @@ -971,9 +915,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await closed -async def test_websocket_disable_keepalive( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_websocket_disable_keepalive(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.StreamResponse: ws = web.WebSocketResponse() if not ws.can_prepare(request): @@ -1002,9 +944,7 @@ async def handler(request: web.Request) -> web.StreamResponse: await ws.receive() # Handle close -async def test_receive_str_nonstring( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_receive_str_nonstring(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse() assert ws.can_prepare(request) @@ -1025,9 +965,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.receive() # Handle close -async def test_receive_bytes_nonbytes( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_receive_bytes_nonbytes(aiohttp_client: AiohttpClient) -> None: async def handler(request: web.Request) -> NoReturn: ws = web.WebSocketResponse() assert ws.can_prepare(request) @@ -1045,9 +983,7 @@ async def handler(request: web.Request) -> NoReturn: await ws.receive_bytes() -async def test_bug3380( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_bug3380(aiohttp_client: AiohttpClient) -> None: async def handle_null(request: web.Request) -> web.Response: return web.json_response({"err": None}) @@ -1073,9 +1009,9 @@ async def ws_handler(request: web.Request) -> web.Response: async def test_receive_being_cancelled_keeps_connection_open( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient + aiohttp_client: AiohttpClient, ) -> None: - closed = loop.create_future() + closed = asyncio.get_running_loop().create_future() async def handler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse(autoping=False) @@ -1118,8 +1054,9 @@ async def handler(request: web.Request) -> web.WebSocketResponse: async def test_receive_timeout_keeps_connection_open( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient + aiohttp_client: AiohttpClient, ) -> None: + loop = asyncio.get_running_loop() closed = loop.create_future() timed_out = loop.create_future() @@ -1338,7 +1275,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: async def test_websocket_prepare_timeout_close_issue( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient + aiohttp_client: AiohttpClient, ) -> None: """Test that WebSocket can handle prepare with early returns. @@ -1367,7 +1304,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: async def test_websocket_prepare_timeout_from_issue_reproducer( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient + aiohttp_client: AiohttpClient, ) -> None: """Test websocket behavior when prepare is interrupted. @@ -1412,9 +1349,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await close_complete.wait() -async def test_websocket_prepared_property( - loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient -) -> None: +async def test_websocket_prepared_property(aiohttp_client: AiohttpClient) -> None: """Test that WebSocketResponse.prepared property correctly reflects state.""" prepare_called = asyncio.Event() diff --git a/tests/test_worker.py b/tests/test_worker.py index 0c0be51e53e..760c43edcb5 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -204,16 +204,14 @@ def test__get_valid_log_format_exc(worker: base_worker.GunicornWebWorker) -> Non async def test__run_ok_parent_changed( - worker: base_worker.GunicornWebWorker, - loop: asyncio.AbstractEventLoop, - unused_port_socket: socket.socket, + worker: base_worker.GunicornWebWorker, unused_port_socket: socket.socket ) -> None: worker.ppid = 0 worker.alive = True sock = unused_port_socket worker.sockets = [sock] worker.log = mock.Mock() - worker.loop = loop + worker.loop = asyncio.get_running_loop() worker.max_requests = 0 worker.cfg.access_log_format = ACCEPTABLE_LOG_FORMAT worker.cfg.is_ssl = False @@ -225,10 +223,9 @@ async def test__run_ok_parent_changed( async def test__run_exc( - worker: base_worker.GunicornWebWorker, - loop: asyncio.AbstractEventLoop, - unused_port_socket: socket.socket, + worker: base_worker.GunicornWebWorker, unused_port_socket: socket.socket ) -> None: + loop = asyncio.get_running_loop() worker.ppid = os.getppid() worker.alive = True sock = unused_port_socket