diff --git a/aiohttp/pytest_plugin.py b/aiohttp/pytest_plugin.py deleted file mode 100644 index 9d11231c6f4..00000000000 --- a/aiohttp/pytest_plugin.py +++ /dev/null @@ -1,441 +0,0 @@ -import asyncio -import contextlib -import inspect -import warnings -from typing import ( - Any, - Awaitable, - Callable, - Dict, - Iterator, - Optional, - Protocol, - Type, - TypeVar, - Union, - overload, -) - -import pytest - -from .test_utils import ( - BaseTestServer, - RawTestServer, - TestClient, - TestServer, - loop_context, - setup_test_loop, - teardown_test_loop, - unused_port as _unused_port, -) -from .web import Application, BaseRequest, Request -from .web_protocol import _RequestHandler - -try: - import uvloop -except ImportError: - uvloop = None # type: ignore[assignment] - -_Request = TypeVar("_Request", bound=BaseRequest) - - -class AiohttpClient(Protocol): - # TODO(PY311): Use Unpack to specify ClientSession kwargs. - @overload - async def __call__( # type: ignore[misc] - self, - __param: Application, - *, - server_kwargs: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> TestClient[Request, Application]: ... - @overload - async def __call__( # type: ignore[misc] - self, - __param: BaseTestServer[_Request], - *, - server_kwargs: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> TestClient[_Request, None]: ... - - -class AiohttpServer(Protocol): - def __call__( - self, app: Application, *, port: Optional[int] = None, **kwargs: Any - ) -> Awaitable[TestServer]: ... - - -class AiohttpRawServer(Protocol): - def __call__( - self, - handler: _RequestHandler[BaseRequest], - *, - port: Optional[int] = None, - **kwargs: Any, - ) -> Awaitable[RawTestServer]: ... - - -def pytest_addoption(parser): # type: ignore[no-untyped-def] - parser.addoption( - "--aiohttp-fast", - action="store_true", - default=False, - help="run tests faster by disabling extra checks", - ) - parser.addoption( - "--aiohttp-loop", - action="store", - default="pyloop", - help="run tests with specific loop: pyloop, uvloop or all", - ) - parser.addoption( - "--aiohttp-enable-loop-debug", - action="store_true", - default=False, - help="enable event loop debug mode", - ) - - -def pytest_fixture_setup(fixturedef): # type: ignore[no-untyped-def] - """Set up pytest fixture. - - Allow fixtures to be coroutines. Run coroutine fixtures in an event loop. - """ - func = fixturedef.func - - if inspect.isasyncgenfunction(func): - # async generator fixture - is_async_gen = True - elif inspect.iscoroutinefunction(func): - # regular async fixture - is_async_gen = False - else: - # not an async fixture, nothing to do - return - - strip_request = False - if "request" not in fixturedef.argnames: - fixturedef.argnames += ("request",) - strip_request = True - - def wrapper(*args, **kwargs): # type: ignore[no-untyped-def] - request = kwargs["request"] - if strip_request: - del kwargs["request"] - - # if neither the fixture nor the test use the 'loop' fixture, - # 'getfixturevalue' will fail because the test is not parameterized - # (this can be removed someday if 'loop' is no longer parameterized) - if "loop" not in request.fixturenames: - raise Exception( - "Asynchronous fixtures must depend on the 'loop' fixture or " - "be used in tests depending from it." - ) - - _loop = request.getfixturevalue("loop") - - if is_async_gen: - # for async generators, we need to advance the generator once, - # then advance it again in a finalizer - gen = func(*args, **kwargs) - - def finalizer(): # type: ignore[no-untyped-def] - try: - return _loop.run_until_complete(gen.__anext__()) - except StopAsyncIteration: - pass - - request.addfinalizer(finalizer) - return _loop.run_until_complete(gen.__anext__()) - else: - return _loop.run_until_complete(func(*args, **kwargs)) - - fixturedef.func = wrapper - - -@pytest.fixture -def fast(request: pytest.FixtureRequest) -> bool: - """--fast config option""" - return request.config.getoption("--aiohttp-fast") # type: ignore[no-any-return] - - -@pytest.fixture -def loop_debug(request: pytest.FixtureRequest) -> bool: - """--enable-loop-debug config option""" - return request.config.getoption("--aiohttp-enable-loop-debug") # type: ignore[no-any-return] - - -@contextlib.contextmanager -def _runtime_warning_context() -> Iterator[None]: - """Context manager which checks for RuntimeWarnings. - - This exists specifically to - avoid "coroutine 'X' was never awaited" warnings being missed. - - If RuntimeWarnings occur in the context a RuntimeError is raised. - """ - with warnings.catch_warnings(record=True) as _warnings: - yield - rw = [ - "{w.filename}:{w.lineno}:{w.message}".format(w=w) - for w in _warnings - if w.category == RuntimeWarning - ] - if rw: - raise RuntimeError( - "{} Runtime Warning{},\n{}".format( - len(rw), "" if len(rw) == 1 else "s", "\n".join(rw) - ) - ) - - # Propagate warnings to pytest - for msg in _warnings: - warnings.showwarning( - msg.message, msg.category, msg.filename, msg.lineno, msg.file, msg.line - ) - - -@contextlib.contextmanager -def _passthrough_loop_context( - loop: Optional[asyncio.AbstractEventLoop], fast: bool = False -) -> Iterator[asyncio.AbstractEventLoop]: - """Passthrough loop context. - - Sets up and tears down a loop unless one is passed in via the loop - argument when it's passed straight through. - """ - if loop: - # loop already exists, pass it straight through - yield loop - else: - # this shadows loop_context's standard behavior - loop = setup_test_loop() - yield loop - teardown_test_loop(loop, fast=fast) - - -def pytest_pycollect_makeitem(collector, name, obj): # type: ignore[no-untyped-def] - """Fix pytest collecting for coroutines.""" - if collector.funcnamefilter(name) and inspect.iscoroutinefunction(obj): - return list(collector._genfunctions(name, obj)) - - -def pytest_pyfunc_call(pyfuncitem): # type: ignore[no-untyped-def] - """Run coroutines in an event loop instead of a normal function call.""" - fast = pyfuncitem.config.getoption("--aiohttp-fast") - if inspect.iscoroutinefunction(pyfuncitem.function): - existing_loop = pyfuncitem.funcargs.get( - "proactor_loop" - ) or pyfuncitem.funcargs.get("loop", None) - with _runtime_warning_context(): - with _passthrough_loop_context(existing_loop, fast=fast) as _loop: - testargs = { - arg: pyfuncitem.funcargs[arg] - for arg in pyfuncitem._fixtureinfo.argnames - } - _loop.run_until_complete(pyfuncitem.obj(**testargs)) - - return True - - -def pytest_generate_tests(metafunc): # type: ignore[no-untyped-def] - if "loop_factory" not in metafunc.fixturenames: - return - - loops = metafunc.config.option.aiohttp_loop - avail_factories: Dict[str, Type[asyncio.AbstractEventLoopPolicy]] - avail_factories = {"pyloop": asyncio.DefaultEventLoopPolicy} - - if uvloop is not None: - avail_factories["uvloop"] = uvloop.EventLoopPolicy - - if loops == "all": - loops = "pyloop,uvloop?" - - factories = {} # type: ignore[var-annotated] - for name in loops.split(","): - required = not name.endswith("?") - name = name.strip(" ?") - if name not in avail_factories: - if required: - raise ValueError( - "Unknown loop '%s', available loops: %s" - % (name, list(factories.keys())) - ) - else: - continue - factories[name] = avail_factories[name] - metafunc.parametrize( - "loop_factory", list(factories.values()), ids=list(factories.keys()) - ) - - -@pytest.fixture -def loop( - loop_factory: Callable[[], asyncio.AbstractEventLoopPolicy], - fast: bool, - loop_debug: bool, -) -> Iterator[asyncio.AbstractEventLoop]: - """Return an instance of the event loop.""" - policy = loop_factory() - asyncio.set_event_loop_policy(policy) - with loop_context(fast=fast) as _loop: - if loop_debug: - _loop.set_debug(True) - asyncio.set_event_loop(_loop) - yield _loop - - -@pytest.fixture -def proactor_loop() -> Iterator[asyncio.AbstractEventLoop]: - policy = asyncio.WindowsProactorEventLoopPolicy() # type: ignore[attr-defined] - asyncio.set_event_loop_policy(policy) - - with loop_context(policy.new_event_loop) as _loop: - asyncio.set_event_loop(_loop) - yield _loop - - -@pytest.fixture -def aiohttp_unused_port() -> Callable[[], int]: - """Return a port that is unused on the current host.""" - return _unused_port - - -@pytest.fixture -def aiohttp_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpServer]: - """Factory to create a TestServer instance, given an app. - - aiohttp_server(app, **kwargs) - """ - servers = [] - - async def go( - app: Application, - *, - host: str = "127.0.0.1", - port: Optional[int] = None, - **kwargs: Any, - ) -> TestServer: - server = TestServer(app, host=host, port=port) - await server.start_server(**kwargs) - servers.append(server) - return server - - yield go - - async def finalize() -> None: - while servers: - await servers.pop().close() - - loop.run_until_complete(finalize()) - - -@pytest.fixture -def aiohttp_raw_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpRawServer]: - """Factory to create a RawTestServer instance, given a web handler. - - aiohttp_raw_server(handler, **kwargs) - """ - servers = [] - - async def go( - handler: _RequestHandler[BaseRequest], - *, - port: Optional[int] = None, - **kwargs: Any, - ) -> RawTestServer: - server = RawTestServer(handler, port=port) - await server.start_server(**kwargs) - servers.append(server) - return server - - yield go - - async def finalize() -> None: - while servers: - await servers.pop().close() - - loop.run_until_complete(finalize()) - - -@pytest.fixture -def aiohttp_client_cls() -> Type[TestClient[Any, Any]]: # type: ignore[misc] - """ - Client class to use in ``aiohttp_client`` factory. - - Use it for passing custom ``TestClient`` implementations. - - Example:: - - class MyClient(TestClient): - async def login(self, *, user, pw): - payload = {"username": user, "password": pw} - return await self.post("/login", json=payload) - - @pytest.fixture - def aiohttp_client_cls(): - return MyClient - - def test_login(aiohttp_client): - app = web.Application() - client = await aiohttp_client(app) - await client.login(user="admin", pw="s3cr3t") - - """ - return TestClient - - -@pytest.fixture -def aiohttp_client( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, aiohttp_client_cls: Type[TestClient[Any, Any]] -) -> Iterator[AiohttpClient]: - """Factory to create a TestClient instance. - - aiohttp_client(app, **kwargs) - aiohttp_client(server, **kwargs) - aiohttp_client(raw_server, **kwargs) - """ - clients = [] - - @overload - async def go( # type: ignore[misc] - __param: Application, - *, - server_kwargs: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> TestClient[Request, Application]: ... - @overload - async def go( # type: ignore[misc] - __param: BaseTestServer[_Request], - *, - server_kwargs: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> TestClient[_Request, None]: ... - async def go( - __param: Union[Application, BaseTestServer[Any]], - *, - server_kwargs: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> TestClient[Any, Any]: - # TODO(PY311): Use Unpack to specify ClientSession kwargs and server_kwargs. - if isinstance(__param, Application): - server_kwargs = server_kwargs or {} - server = TestServer(__param, **server_kwargs) - client = aiohttp_client_cls(server, **kwargs) - elif isinstance(__param, BaseTestServer): - client = aiohttp_client_cls(__param, **kwargs) - else: - raise ValueError("Unknown argument type: %r" % type(__param)) - - await client.start_server() - clients.append(client) - return client - - yield go - - async def finalize() -> None: - while clients: - await clients.pop().close() - - loop.run_until_complete(finalize()) diff --git a/aiohttp/test_utils.py b/aiohttp/test_utils.py index 569baf7c32d..e12392ed143 100644 --- a/aiohttp/test_utils.py +++ b/aiohttp/test_utils.py @@ -98,13 +98,6 @@ def get_port_socket( return s -def unused_port() -> int: - """Return a port that is unused on the current host.""" - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: - s.bind(("127.0.0.1", 0)) - return cast(int, s.getsockname()[1]) - - class BaseTestServer(ABC, Generic[_Request]): __test__ = False @@ -533,49 +526,6 @@ async def get_client(self, server: TestServer) -> TestClient[Request, Applicatio return TestClient(server) -_LOOP_FACTORY = Callable[[], asyncio.AbstractEventLoop] - - -@contextlib.contextmanager -def loop_context( - loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, fast: bool = False -) -> Iterator[asyncio.AbstractEventLoop]: - """A contextmanager that creates an event_loop, for test purposes. - - Handles the creation and cleanup of a test loop. - """ - loop = setup_test_loop(loop_factory) - yield loop - teardown_test_loop(loop, fast=fast) - - -def setup_test_loop( - loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, -) -> asyncio.AbstractEventLoop: - """Create and return an asyncio.BaseEventLoop instance. - - The caller should also call teardown_test_loop, - once they are done with the loop. - """ - loop = loop_factory() - asyncio.set_event_loop(loop) - return loop - - -def teardown_test_loop(loop: asyncio.AbstractEventLoop, fast: bool = False) -> None: - """Teardown and cleanup an event_loop created by setup_test_loop.""" - closed = loop.is_closed() - if not closed: - loop.call_soon(loop.stop) - loop.run_forever() - loop.close() - - if not fast: - gc.collect() - - asyncio.set_event_loop(None) - - def _create_app_mock() -> mock.MagicMock: def get_dict(app: Any, key: str) -> Any: return app.__app_dict[key] diff --git a/docs/testing.rst b/docs/testing.rst index 1d29f335460..78af7f6bbd9 100644 --- a/docs/testing.rst +++ b/docs/testing.rst @@ -26,10 +26,6 @@ For using pytest plugin please install pytest-aiohttp_ library: $ pip install pytest-aiohttp -If you don't want to install *pytest-aiohttp* for some reason you may -insert ``pytest_plugins = 'aiohttp.pytest_plugin'`` line into -``conftest.py`` instead for the same functionality. - The Test Client and Servers @@ -206,22 +202,6 @@ Pytest tooling has the following fixtures: .. versionadded:: 3.0 -.. data:: aiohttp_unused_port() - - Function to return an unused port number for IPv4 TCP protocol:: - - async def test_f(aiohttp_client, aiohttp_unused_port): - port = aiohttp_unused_port() - app = web.Application() - # fill route table - - client = await aiohttp_client(app, server_kwargs={'port': port}) - ... - - .. versionchanged:: 3.0 - - The fixture was renamed from ``unused_port`` to ``aiohttp_unused_port``. - .. data:: aiohttp_client_cls A fixture for passing custom :class:`~aiohttp.test_utils.TestClient` implementations:: @@ -812,47 +792,6 @@ Utilities *return_value* when called. -.. function:: unused_port() - - Return an unused port number for IPv4 TCP protocol. - - :return int: ephemeral port number which could be reused by test server. - -.. function:: loop_context(loop_factory=) - - A contextmanager that creates an event_loop, for test purposes. - - Handles the creation and cleanup of a test loop. - -.. function:: setup_test_loop(loop_factory=) - - Create and return an :class:`asyncio.AbstractEventLoop` instance. - - The caller should also call teardown_test_loop, once they are done - with the loop. - - .. note:: - - As side effect the function changes asyncio *default loop* by - :func:`asyncio.set_event_loop` call. - - Previous default loop is not restored. - - It should not be a problem for test suite: every test expects a - new test loop instance anyway. - - .. versionchanged:: 3.1 - - The function installs a created event loop as *default*. - -.. function:: teardown_test_loop(loop) - - Teardown and cleanup an event_loop created by setup_test_loop. - - :param loop: the loop to teardown - :type loop: asyncio.AbstractEventLoop - - .. _pytest: http://pytest.org/latest/ .. _pytest-aiohttp: https://pypi.python.org/pypi/pytest-aiohttp diff --git a/examples/fake_server.py b/examples/fake_server.py index d7be5954232..df7449f7cb0 100755 --- a/examples/fake_server.py +++ b/examples/fake_server.py @@ -60,9 +60,8 @@ def __init__(self) -> None: self.ssl_context.load_cert_chain(str(ssl_cert), str(ssl_key)) async def start(self) -> Dict[str, int]: - port = test_utils.unused_port() await self.runner.setup() - site = web.TCPSite(self.runner, "127.0.0.1", port, ssl_context=self.ssl_context) + site = web.TCPSite(self.runner, "127.0.0.1", 0, ssl_context=self.ssl_context) await site.start() return {"graph.facebook.com": port} diff --git a/requirements/constraints.txt b/requirements/constraints.txt index 6561e817cbe..5a4ed7116a0 100644 --- a/requirements/constraints.txt +++ b/requirements/constraints.txt @@ -1,6 +1,6 @@ # -# This file is autogenerated by pip-compile with python 3.10 -# To update, run: +# This file is autogenerated by pip-compile with Python 3.10 +# by the following command: # # pip-compile --allow-unsafe --output-file=requirements/constraints.txt --resolver=backtracking --strip-extras requirements/constraints.in # @@ -9,11 +9,17 @@ aiodns==3.2.0 ; sys_platform == "linux" or sys_platform == "darwin" # -r requirements/lint.in # -r requirements/runtime-deps.in aiohappyeyeballs==2.6.1 - # via -r requirements/runtime-deps.in + # via + # -r requirements/runtime-deps.in + # aiohttp +aiohttp==3.11.18 + # via pytest-aiohttp aiohttp-theme==0.1.7 # via -r requirements/doc.in aiosignal==1.3.2 - # via -r requirements/runtime-deps.in + # via + # -r requirements/runtime-deps.in + # aiohttp alabaster==1.0.0 # via sphinx annotated-types==0.7.0 @@ -21,7 +27,10 @@ annotated-types==0.7.0 async-timeout==5.0.1 ; python_version < "3.11" # via # -r requirements/runtime-deps.in + # aiohttp # valkey +attrs==25.3.0 + # via aiohttp babel==2.17.0 # via sphinx blockbuster==1.5.24 @@ -81,6 +90,7 @@ freezegun==1.5.1 frozenlist==1.6.0 # via # -r requirements/runtime-deps.in + # aiohttp # aiosignal gidgethub==5.3.0 # via cherry-picker @@ -117,6 +127,7 @@ multidict==6.4.3 # via # -r requirements/multidict.in # -r requirements/runtime-deps.in + # aiohttp # yarl mypy==1.15.0 ; implementation_name == "cpython" # via @@ -144,6 +155,7 @@ pre-commit==4.2.0 propcache==0.3.1 # via # -r requirements/runtime-deps.in + # aiohttp # yarl proxy-py==2.4.10 # via @@ -175,10 +187,18 @@ pytest==8.1.1 # via # -r requirements/lint.in # -r requirements/test.in + # pytest-aiohttp + # pytest-asyncio # pytest-codspeed # pytest-cov # pytest-mock # pytest-xdist +pytest-aiohttp==1.1.0 + # via + # -r requirements/lint.in + # -r requirements/test.in +pytest-asyncio==0.23.8 + # via pytest-aiohttp pytest-codspeed==3.2.0 # via # -r requirements/lint.in @@ -287,7 +307,9 @@ wait-for-it==2.3.0 wheel==0.46.0 # via pip-tools yarl==1.20.0 - # via -r requirements/runtime-deps.in + # via + # -r requirements/runtime-deps.in + # aiohttp zlib-ng==0.5.1 # via # -r requirements/lint.in diff --git a/requirements/cython.txt b/requirements/cython.txt index 8686651881b..68e6952a973 100644 --- a/requirements/cython.txt +++ b/requirements/cython.txt @@ -1,5 +1,5 @@ # -# This file is autogenerated by pip-compile with python 3.10 +# This file is autogenerated by pip-compile with Python 3.10 # by the following command: # # pip-compile --allow-unsafe --output-file=requirements/cython.txt --resolver=backtracking --strip-extras requirements/cython.in diff --git a/requirements/dev.txt b/requirements/dev.txt index c38430fa80d..f3dd3e975b7 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,6 +1,6 @@ # -# This file is autogenerated by pip-compile with python 3.10 -# To update, run: +# This file is autogenerated by pip-compile with Python 3.10 +# by the following command: # # pip-compile --allow-unsafe --output-file=requirements/dev.txt --resolver=backtracking --strip-extras requirements/dev.in # @@ -9,11 +9,17 @@ aiodns==3.2.0 ; sys_platform == "linux" or sys_platform == "darwin" # -r requirements/lint.in # -r requirements/runtime-deps.in aiohappyeyeballs==2.6.1 - # via -r requirements/runtime-deps.in + # via + # -r requirements/runtime-deps.in + # aiohttp +aiohttp==3.11.18 + # via pytest-aiohttp aiohttp-theme==0.1.7 # via -r requirements/doc.in aiosignal==1.3.2 - # via -r requirements/runtime-deps.in + # via + # -r requirements/runtime-deps.in + # aiohttp alabaster==1.0.0 # via sphinx annotated-types==0.7.0 @@ -21,7 +27,10 @@ annotated-types==0.7.0 async-timeout==5.0.1 ; python_version < "3.11" # via # -r requirements/runtime-deps.in + # aiohttp # valkey +attrs==25.3.0 + # via aiohttp babel==2.17.0 # via sphinx blockbuster==1.5.24 @@ -79,6 +88,7 @@ freezegun==1.5.1 frozenlist==1.6.0 # via # -r requirements/runtime-deps.in + # aiohttp # aiosignal gidgethub==5.3.0 # via cherry-picker @@ -114,6 +124,7 @@ mdurl==0.1.2 multidict==6.4.3 # via # -r requirements/runtime-deps.in + # aiohttp # yarl mypy==1.15.0 ; implementation_name == "cpython" # via @@ -141,6 +152,7 @@ pre-commit==4.2.0 propcache==0.3.1 # via # -r requirements/runtime-deps.in + # aiohttp # yarl proxy-py==2.4.10 # via @@ -170,10 +182,18 @@ pytest==8.1.1 # via # -r requirements/lint.in # -r requirements/test.in + # pytest-aiohttp + # pytest-asyncio # pytest-codspeed # pytest-cov # pytest-mock # pytest-xdist +pytest-aiohttp==1.1.0 + # via + # -r requirements/lint.in + # -r requirements/test.in +pytest-asyncio==0.23.8 + # via pytest-aiohttp pytest-codspeed==3.2.0 # via # -r requirements/lint.in @@ -278,7 +298,9 @@ wait-for-it==2.3.0 wheel==0.46.0 # via pip-tools yarl==1.20.0 - # via -r requirements/runtime-deps.in + # via + # -r requirements/runtime-deps.in + # aiohttp zlib-ng==0.5.1 # via # -r requirements/lint.in diff --git a/requirements/doc.txt b/requirements/doc.txt index 0a39991a9f4..156965c1dbe 100644 --- a/requirements/doc.txt +++ b/requirements/doc.txt @@ -1,6 +1,6 @@ # -# This file is autogenerated by pip-compile with python 3.10 -# To update, run: +# This file is autogenerated by pip-compile with Python 3.10 +# by the following command: # # pip-compile --allow-unsafe --output-file=requirements/doc.txt --resolver=backtracking --strip-extras requirements/doc.in # diff --git a/requirements/lint.in b/requirements/lint.in index 21a9fb4e0f4..0d85f508f35 100644 --- a/requirements/lint.in +++ b/requirements/lint.in @@ -6,6 +6,7 @@ mypy; implementation_name == "cpython" pre-commit proxy.py pytest +pytest-aiohttp pytest-mock pytest_codspeed python-on-whales diff --git a/requirements/lint.txt b/requirements/lint.txt index 0fb6cc2fe8d..3de795149da 100644 --- a/requirements/lint.txt +++ b/requirements/lint.txt @@ -1,15 +1,25 @@ # -# This file is autogenerated by pip-compile with python 3.10 +# This file is autogenerated by pip-compile with Python 3.10 # by the following command: # # pip-compile --allow-unsafe --output-file=requirements/lint.txt --strip-extras requirements/lint.in # aiodns==3.2.0 # via -r requirements/lint.in +aiohappyeyeballs==2.6.1 + # via aiohttp +aiohttp==3.11.18 + # via pytest-aiohttp +aiosignal==1.3.2 + # via aiohttp annotated-types==0.7.0 # via pydantic async-timeout==5.0.1 - # via valkey + # via + # aiohttp + # valkey +attrs==25.3.0 + # via aiohttp blockbuster==1.5.24 # via -r requirements/lint.in cffi==1.17.1 @@ -33,10 +43,16 @@ forbiddenfruit==0.1.4 # via blockbuster freezegun==1.5.1 # via -r requirements/lint.in +frozenlist==1.6.0 + # via + # aiohttp + # aiosignal identify==2.6.10 # via pre-commit idna==3.7 - # via trustme + # via + # trustme + # yarl iniconfig==2.1.0 # via pytest isal==1.7.2 @@ -45,6 +61,10 @@ markdown-it-py==3.0.0 # via rich mdurl==0.1.2 # via markdown-it-py +multidict==6.4.3 + # via + # aiohttp + # yarl mypy==1.15.0 ; implementation_name == "cpython" # via -r requirements/lint.in mypy-extensions==1.1.0 @@ -59,6 +79,10 @@ pluggy==1.5.0 # via pytest pre-commit==4.2.0 # via -r requirements/lint.in +propcache==0.3.1 + # via + # aiohttp + # yarl proxy-py==2.4.10 # via -r requirements/lint.in pycares==4.6.1 @@ -74,8 +98,14 @@ pygments==2.19.1 pytest==8.1.1 # via # -r requirements/lint.in + # pytest-aiohttp + # pytest-asyncio # pytest-codspeed # pytest-mock +pytest-aiohttp==1.1.0 + # via -r requirements/lint.in +pytest-asyncio==0.23.8 + # via pytest-aiohttp pytest-codspeed==3.2.0 # via -r requirements/lint.in pytest-mock==3.14.0 @@ -101,6 +131,7 @@ trustme==1.2.1 # via -r requirements/lint.in typing-extensions==4.13.2 # via + # multidict # mypy # pydantic # pydantic-core @@ -115,5 +146,7 @@ valkey==6.1.0 # via -r requirements/lint.in virtualenv==20.30.0 # via pre-commit +yarl==1.20.0 + # via aiohttp zlib-ng==0.5.1 # via -r requirements/lint.in diff --git a/requirements/multidict.txt b/requirements/multidict.txt index 41435a67142..a7afe8a7970 100644 --- a/requirements/multidict.txt +++ b/requirements/multidict.txt @@ -1,5 +1,5 @@ # -# This file is autogenerated by pip-compile with python 3.10 +# This file is autogenerated by pip-compile with Python 3.10 # by the following command: # # pip-compile --allow-unsafe --output-file=requirements/multidict.txt --resolver=backtracking --strip-extras requirements/multidict.in diff --git a/requirements/runtime-deps.txt b/requirements/runtime-deps.txt index b6c248621f2..5e6dbf30a26 100644 --- a/requirements/runtime-deps.txt +++ b/requirements/runtime-deps.txt @@ -2,7 +2,7 @@ # This file is autogenerated by pip-compile with Python 3.10 # by the following command: # -# pip-compile --allow-unsafe --output-file=requirements/runtime-deps.txt --strip-extras requirements/runtime-deps.in +# pip-compile --allow-unsafe --output-file=requirements/runtime-deps.txt --resolver=backtracking --strip-extras requirements/runtime-deps.in # aiodns==3.2.0 ; sys_platform == "linux" or sys_platform == "darwin" # via -r requirements/runtime-deps.in diff --git a/requirements/test.in b/requirements/test.in index b8b82abd1ce..f2dbebec595 100644 --- a/requirements/test.in +++ b/requirements/test.in @@ -7,6 +7,7 @@ isal mypy; implementation_name == "cpython" proxy.py >= 2.4.4rc5 pytest +pytest-aiohttp pytest-cov pytest-mock pytest-xdist diff --git a/requirements/test.txt b/requirements/test.txt index c4769af1e4a..60fd7a0c0ea 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -1,5 +1,5 @@ # -# This file is autogenerated by pip-compile with python 3.10 +# This file is autogenerated by pip-compile with Python 3.10 # by the following command: # # pip-compile --allow-unsafe --output-file=requirements/test.txt --resolver=backtracking --strip-extras requirements/test.in @@ -7,13 +7,23 @@ aiodns==3.2.0 ; sys_platform == "linux" or sys_platform == "darwin" # via -r requirements/runtime-deps.in aiohappyeyeballs==2.6.1 - # via -r requirements/runtime-deps.in + # via + # -r requirements/runtime-deps.in + # aiohttp +aiohttp==3.11.18 + # via pytest-aiohttp aiosignal==1.3.2 - # via -r requirements/runtime-deps.in + # via + # -r requirements/runtime-deps.in + # aiohttp annotated-types==0.7.0 # via pydantic async-timeout==5.0.1 ; python_version < "3.11" - # via -r requirements/runtime-deps.in + # via + # -r requirements/runtime-deps.in + # aiohttp +attrs==25.3.0 + # via aiohttp blockbuster==1.5.24 # via -r requirements/test.in brotli==1.1.0 ; platform_python_implementation == "CPython" @@ -42,6 +52,7 @@ freezegun==1.5.1 frozenlist==1.6.0 # via # -r requirements/runtime-deps.in + # aiohttp # aiosignal gunicorn==23.0.0 # via -r requirements/base.in @@ -60,6 +71,7 @@ mdurl==0.1.2 multidict==6.4.3 # via # -r requirements/runtime-deps.in + # aiohttp # yarl mypy==1.15.0 ; implementation_name == "cpython" # via -r requirements/test.in @@ -74,6 +86,7 @@ pluggy==1.5.0 propcache==0.3.1 # via # -r requirements/runtime-deps.in + # aiohttp # yarl proxy-py==2.4.10 # via -r requirements/test.in @@ -90,10 +103,16 @@ pygments==2.19.1 pytest==8.1.1 # via # -r requirements/test.in + # pytest-aiohttp + # pytest-asyncio # pytest-codspeed # pytest-cov # pytest-mock # pytest-xdist +pytest-aiohttp==1.1.0 + # via -r requirements/test.in +pytest-asyncio==0.23.8 + # via pytest-aiohttp pytest-codspeed==3.2.0 # via -r requirements/test.in pytest-cov==6.1.1 @@ -135,6 +154,8 @@ uvloop==0.21.0 ; platform_system != "Windows" and implementation_name == "cpytho wait-for-it==2.3.0 # via -r requirements/test.in yarl==1.20.0 - # via -r requirements/runtime-deps.in + # via + # -r requirements/runtime-deps.in + # aiohttp zlib-ng==0.5.1 # via -r requirements/test.in diff --git a/setup.cfg b/setup.cfg index c3c6e0270a1..c69067d96aa 100644 --- a/setup.cfg +++ b/setup.cfg @@ -125,7 +125,7 @@ exclude_lines = [tool:pytest] addopts = # `pytest-xdist`: - --numprocesses=auto + --dist no # show 10 slowest invocations: --durations=10 @@ -146,6 +146,7 @@ addopts = # run tests that are not marked with dev_mode -m "not dev_mode" +asyncio_mode = auto filterwarnings = error ignore:module 'ssl' has no attribute 'OP_NO_COMPRESSION'. The Python interpreter is compiled against OpenSSL < 1.0.0. Ref. https.//docs.python.org/3/library/ssl.html#ssl.OP_NO_COMPRESSION:UserWarning diff --git a/tests/conftest.py b/tests/conftest.py index 573d992e464..ee7c0fd1214 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,6 @@ import asyncio import base64 +import gc import os import socket import ssl @@ -20,7 +21,7 @@ from aiohttp.client_proto import ResponseHandler from aiohttp.compression_utils import ZLibBackend, ZLibBackendProtocol, set_zlib_backend from aiohttp.http import WS_KEY -from aiohttp.test_utils import get_unused_port_socket, loop_context +from aiohttp.test_utils import get_unused_port_socket try: import trustme @@ -39,7 +40,9 @@ uvloop = None # type: ignore[assignment] -pytest_plugins = ("aiohttp.pytest_plugin", "pytester") +# We require pytest-aiohttp to avoid confusing debugging if it's not installed. +pytest_plugins = ("pytest_aiohttp", "pytester") + IS_HPUX = sys.platform.startswith("hp-ux") IS_LINUX = sys.platform.startswith("linux") @@ -60,9 +63,7 @@ def blockbuster(request: pytest.FixtureRequest) -> Iterator[None]: yield return node = node.parent - with blockbuster_ctx( - "aiohttp", excluded_modules=["aiohttp.pytest_plugin", "aiohttp.test_utils"] - ) as bb: + with blockbuster_ctx("aiohttp") as bb: # TODO: Fix blocking call in ClientRequest's constructor. # https://github.com/aio-libs/aiohttp/issues/10435 for func in ["io.TextIOWrapper.read", "os.stat"]: @@ -142,11 +143,11 @@ def pipe_name() -> str: @pytest.fixture def create_mocked_conn( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> Iterator[Callable[[], ResponseHandler]]: def _proto_factory() -> Any: proto = mock.create_autospec(ResponseHandler, instance=True) - proto.closed = loop.create_future() + proto.closed = event_loop.create_future() proto.closed.set_result(None) return proto @@ -231,14 +232,38 @@ def assert_sock_fits(sock_path: str) -> None: return +@pytest.fixture +def proactor_loop() -> Iterator[asyncio.AbstractEventLoop]: + policy = asyncio.WindowsProactorEventLoopPolicy() # type: ignore[attr-defined] + asyncio.set_event_loop_policy(policy) + + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + yield loop + if not loop.is_closed(): + loop.call_soon(loop.stop) + loop.run_forever() + loop.close() + + gc.collect() + asyncio.set_event_loop(None) + + @pytest.fixture def selector_loop() -> Iterator[asyncio.AbstractEventLoop]: policy = asyncio.WindowsSelectorEventLoopPolicy() # type: ignore[attr-defined] asyncio.set_event_loop_policy(policy) - with loop_context(policy.new_event_loop) as _loop: - asyncio.set_event_loop(_loop) - yield _loop + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + yield loop + if not loop.is_closed(): + loop.call_soon(loop.stop) + loop.run_forever() + loop.close() + + gc.collect() + asyncio.set_event_loop(None) @pytest.fixture @@ -246,9 +271,16 @@ def uvloop_loop() -> Iterator[asyncio.AbstractEventLoop]: policy = uvloop.EventLoopPolicy() asyncio.set_event_loop_policy(policy) - with loop_context(policy.new_event_loop) as _loop: - asyncio.set_event_loop(_loop) - yield _loop + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + yield loop + if not loop.is_closed(): + loop.call_soon(loop.stop) + loop.run_forever() + loop.close() + + gc.collect() + asyncio.set_event_loop(None) @pytest.fixture diff --git a/tests/test_benchmarks_client.py b/tests/test_benchmarks_client.py index ef2a4d88c92..4861fd37bf1 100644 --- a/tests/test_benchmarks_client.py +++ b/tests/test_benchmarks_client.py @@ -3,14 +3,14 @@ import asyncio import pytest +from pytest_aiohttp import AiohttpClient from pytest_codspeed import BenchmarkFixture from aiohttp import hdrs, web -from aiohttp.pytest_plugin import AiohttpClient def test_one_hundred_simple_get_requests( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -31,11 +31,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_one_hundred_simple_get_requests_multiple_methods_route( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -59,11 +59,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_one_hundred_get_requests_with_1024_chunked_payload( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -88,11 +88,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_one_hundred_get_requests_with_30000_chunked_payload( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -117,11 +117,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_one_hundred_get_requests_with_512kib_chunked_payload( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -146,11 +146,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_one_hundred_get_requests_iter_chunks_on_512kib_chunked_payload( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -176,12 +176,12 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) @pytest.mark.usefixtures("parametrize_zlib_backend") def test_get_request_with_251308_compressed_chunked_payload( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -211,11 +211,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_one_hundred_get_requests_with_1024_content_length_payload( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -239,11 +239,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_one_hundred_get_requests_with_30000_content_length_payload( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -267,11 +267,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_one_hundred_get_requests_with_512kib_content_length_payload( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -295,11 +295,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_one_hundred_simple_post_requests( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -320,11 +320,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_one_hundred_json_post_requests( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -347,11 +347,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_ten_streamed_responses_iter_any( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -379,11 +379,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_ten_streamed_responses_iter_chunked_4096( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -411,11 +411,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_ten_streamed_responses_iter_chunked_65536( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -443,11 +443,11 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) def test_ten_streamed_responses_iter_chunks( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -475,4 +475,4 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) diff --git a/tests/test_benchmarks_client_request.py b/tests/test_benchmarks_client_request.py index db56e509775..9629610ef73 100644 --- a/tests/test_benchmarks_client_request.py +++ b/tests/test_benchmarks_client_request.py @@ -12,9 +12,9 @@ def test_client_request_update_cookies( - loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture ) -> None: - req = ClientRequest("get", URL("http://python.org"), loop=loop) + req = ClientRequest("get", URL("http://python.org"), loop=event_loop) morsel: "Morsel[str]" = Morsel() morsel.set(key="string", val="Another string", coded_val="really") morsel_cookie = {"str": morsel} @@ -25,7 +25,7 @@ def _run() -> None: def test_create_client_request_with_cookies( - loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture ) -> None: url = URL("http://python.org") @@ -34,7 +34,7 @@ def _run() -> None: ClientRequest( method="get", url=url, - loop=loop, + loop=event_loop, headers=None, data=None, cookies={"cookie": "value"}, @@ -47,7 +47,7 @@ def _run() -> None: def test_create_client_request_with_headers( - loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture ) -> None: url = URL("http://python.org") @@ -56,7 +56,7 @@ def _run() -> None: ClientRequest( method="get", url=url, - loop=loop, + loop=event_loop, headers={"header": "value", "another": "header"}, data=None, cookies=None, @@ -69,10 +69,10 @@ def _run() -> None: def test_send_client_request_one_hundred( - loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture ) -> None: url = URL("http://python.org") - req = ClientRequest("get", url, loop=loop) + req = ClientRequest("get", url, loop=event_loop) class MockTransport(asyncio.Transport): """Mock transport for testing that do no real I/O.""" @@ -118,4 +118,4 @@ async def send_requests() -> None: @benchmark def _run() -> None: - loop.run_until_complete(send_requests()) + event_loop.run_until_complete(send_requests()) diff --git a/tests/test_benchmarks_client_ws.py b/tests/test_benchmarks_client_ws.py index 0338b52fb9d..0362cae52a4 100644 --- a/tests/test_benchmarks_client_ws.py +++ b/tests/test_benchmarks_client_ws.py @@ -3,15 +3,15 @@ import asyncio import pytest +from pytest_aiohttp import AiohttpClient from pytest_codspeed import BenchmarkFixture from aiohttp import web from aiohttp._websocket.helpers import MSG_SIZE -from aiohttp.pytest_plugin import AiohttpClient def test_one_thousand_round_trip_websocket_text_messages( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -38,12 +38,12 @@ async def run_websocket_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_websocket_benchmark()) + event_loop.run_until_complete(run_websocket_benchmark()) @pytest.mark.parametrize("msg_size", [6, MSG_SIZE * 4], ids=["small", "large"]) def test_one_thousand_round_trip_websocket_binary_messages( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, msg_size: int, @@ -72,11 +72,11 @@ async def run_websocket_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_websocket_benchmark()) + event_loop.run_until_complete(run_websocket_benchmark()) def test_one_thousand_large_round_trip_websocket_text_messages( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -104,12 +104,12 @@ async def run_websocket_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_websocket_benchmark()) + event_loop.run_until_complete(run_websocket_benchmark()) @pytest.mark.usefixtures("parametrize_zlib_backend") def test_client_send_large_websocket_compressed_messages( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -137,12 +137,12 @@ async def run_websocket_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_websocket_benchmark()) + event_loop.run_until_complete(run_websocket_benchmark()) @pytest.mark.usefixtures("parametrize_zlib_backend") def test_client_receive_large_websocket_compressed_messages( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -170,4 +170,4 @@ async def run_websocket_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_websocket_benchmark()) + event_loop.run_until_complete(run_websocket_benchmark()) diff --git a/tests/test_benchmarks_http_websocket.py b/tests/test_benchmarks_http_websocket.py index 728921b53eb..454002daccd 100644 --- a/tests/test_benchmarks_http_websocket.py +++ b/tests/test_benchmarks_http_websocket.py @@ -13,10 +13,10 @@ def test_read_large_binary_websocket_messages( - loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture ) -> None: """Read one hundred large binary websocket messages.""" - queue = WebSocketDataQueue(BaseProtocol(loop), 2**18, loop=loop) + queue = WebSocketDataQueue(BaseProtocol(event_loop), 2**18, loop=event_loop) reader = WebSocketReader(queue, max_msg_size=2**18) # PACK3 has a minimum message length of 2**16 bytes. @@ -34,10 +34,10 @@ def _run() -> None: def test_read_one_hundred_websocket_text_messages( - loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture ) -> None: """Benchmark reading 100 WebSocket text messages.""" - queue = WebSocketDataQueue(BaseProtocol(loop), 2**16, loop=loop) + queue = WebSocketDataQueue(BaseProtocol(event_loop), 2**16, loop=event_loop) reader = WebSocketReader(queue, max_msg_size=2**16) raw_message = ( b'\x81~\x01!{"id":1,"src":"shellyplugus-c049ef8c30e4","dst":"aios-1453812500' @@ -71,10 +71,10 @@ async def _drain_helper(self) -> None: def test_send_one_hundred_websocket_text_messages( - loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture ) -> None: """Benchmark sending 100 WebSocket text messages.""" - writer = WebSocketWriter(MockProtocol(loop=loop), MockTransport()) + writer = WebSocketWriter(MockProtocol(loop=event_loop), MockTransport()) raw_message = b"Hello, World!" * 100 async def _send_one_hundred_websocket_text_messages() -> None: @@ -83,14 +83,14 @@ async def _send_one_hundred_websocket_text_messages() -> None: @benchmark def _run() -> None: - loop.run_until_complete(_send_one_hundred_websocket_text_messages()) + event_loop.run_until_complete(_send_one_hundred_websocket_text_messages()) def test_send_one_hundred_large_websocket_text_messages( - loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture ) -> None: """Benchmark sending 100 WebSocket text messages.""" - writer = WebSocketWriter(MockProtocol(loop=loop), MockTransport()) + writer = WebSocketWriter(MockProtocol(loop=event_loop), MockTransport()) raw_message = b"x" * MSG_SIZE * 4 async def _send_one_hundred_websocket_text_messages() -> None: @@ -99,14 +99,16 @@ async def _send_one_hundred_websocket_text_messages() -> None: @benchmark def _run() -> None: - loop.run_until_complete(_send_one_hundred_websocket_text_messages()) + event_loop.run_until_complete(_send_one_hundred_websocket_text_messages()) def test_send_one_hundred_websocket_text_messages_with_mask( - loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture ) -> None: """Benchmark sending 100 masked WebSocket text messages.""" - writer = WebSocketWriter(MockProtocol(loop=loop), MockTransport(), use_mask=True) + writer = WebSocketWriter( + MockProtocol(loop=event_loop), MockTransport(), use_mask=True + ) raw_message = b"Hello, World!" * 100 async def _send_one_hundred_websocket_text_messages() -> None: @@ -115,15 +117,17 @@ async def _send_one_hundred_websocket_text_messages() -> None: @benchmark def _run() -> None: - loop.run_until_complete(_send_one_hundred_websocket_text_messages()) + event_loop.run_until_complete(_send_one_hundred_websocket_text_messages()) @pytest.mark.usefixtures("parametrize_zlib_backend") def test_send_one_hundred_websocket_compressed_messages( - loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture ) -> None: """Benchmark sending 100 WebSocket compressed messages.""" - writer = WebSocketWriter(MockProtocol(loop=loop), MockTransport(), compress=15) + writer = WebSocketWriter( + MockProtocol(loop=event_loop), MockTransport(), compress=15 + ) raw_message = b"Hello, World!" * 100 async def _send_one_hundred_websocket_compressed_messages() -> None: @@ -132,4 +136,4 @@ async def _send_one_hundred_websocket_compressed_messages() -> None: @benchmark def _run() -> None: - loop.run_until_complete(_send_one_hundred_websocket_compressed_messages()) + event_loop.run_until_complete(_send_one_hundred_websocket_compressed_messages()) diff --git a/tests/test_benchmarks_web_fileresponse.py b/tests/test_benchmarks_web_fileresponse.py index 01aa7448c86..e3763cfd924 100644 --- a/tests/test_benchmarks_web_fileresponse.py +++ b/tests/test_benchmarks_web_fileresponse.py @@ -4,14 +4,14 @@ import pathlib from multidict import CIMultiDict +from pytest_aiohttp import AiohttpClient from pytest_codspeed import BenchmarkFixture from aiohttp import ClientResponse, web -from aiohttp.pytest_plugin import AiohttpClient def test_simple_web_file_response( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -33,11 +33,11 @@ async def run_file_response_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_file_response_benchmark()) + event_loop.run_until_complete(run_file_response_benchmark()) def test_simple_web_file_sendfile_fallback_response( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -62,11 +62,11 @@ async def run_file_response_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_file_response_benchmark()) + event_loop.run_until_complete(run_file_response_benchmark()) def test_simple_web_file_response_not_modified( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, benchmark: BenchmarkFixture, ) -> None: @@ -97,9 +97,9 @@ async def run_file_response_benchmark( await client.close() return resp # type: ignore[possibly-undefined] - headers = loop.run_until_complete(make_last_modified_header()) + headers = event_loop.run_until_complete(make_last_modified_header()) @benchmark def _run() -> None: - resp = loop.run_until_complete(run_file_response_benchmark(headers)) + resp = event_loop.run_until_complete(run_file_response_benchmark(headers)) assert resp.status == 304 diff --git a/tests/test_benchmarks_web_middleware.py b/tests/test_benchmarks_web_middleware.py index 497da1819c9..e967ba526c6 100644 --- a/tests/test_benchmarks_web_middleware.py +++ b/tests/test_benchmarks_web_middleware.py @@ -2,16 +2,16 @@ import asyncio +from pytest_aiohttp import AiohttpClient from pytest_codspeed import BenchmarkFixture from aiohttp import web -from aiohttp.pytest_plugin import AiohttpClient from aiohttp.typedefs import Handler def test_ten_web_middlewares( benchmark: BenchmarkFixture, - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient, ) -> None: """Benchmark 100 requests with 10 middlewares.""" @@ -40,4 +40,4 @@ async def run_client_benchmark() -> None: @benchmark def _run() -> None: - loop.run_until_complete(run_client_benchmark()) + event_loop.run_until_complete(run_client_benchmark()) diff --git a/tests/test_benchmarks_web_urldispatcher.py b/tests/test_benchmarks_web_urldispatcher.py index 936ed6320ed..68335afd9d4 100644 --- a/tests/test_benchmarks_web_urldispatcher.py +++ b/tests/test_benchmarks_web_urldispatcher.py @@ -53,7 +53,7 @@ def _mock_request(method: str, path: str) -> web.Request: def test_resolve_root_route( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, ) -> None: """Resolve top level PlainResources route 100 times.""" @@ -75,17 +75,17 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ret.get_info()["path"] == "/", ret.get_info() @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_root_route_with_many_fixed_routes( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, ) -> None: """Resolve top level PlainResources route 100 times.""" @@ -113,17 +113,17 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ret.get_info()["path"] == "/", ret.get_info() @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_static_root_route( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, ) -> None: """Resolve top level StaticResource route 100 times.""" @@ -143,17 +143,17 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ret.get_info()["directory"] == here, ret.get_info() @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_single_fixed_url_with_many_routes( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, ) -> None: """Resolve PlainResources route 100 times.""" @@ -176,17 +176,17 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ret.get_info()["path"] == "/api/server/dispatch/1/update", ret.get_info() @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_multiple_fixed_url_with_many_routes( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, ) -> None: """Resolve 250 different PlainResources routes.""" @@ -211,17 +211,17 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: ret = await router.resolve(request) return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ret.get_info()["path"] == "/api/server/dispatch/249/update", ret.get_info() @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_multiple_level_fixed_url_with_many_routes( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, ) -> None: """Resolve 1024 different PlainResources routes.""" @@ -252,17 +252,17 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ret.get_info()["path"] == url, ret.get_info() @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_dynamic_resource_url_with_many_static_routes( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, ) -> None: """Resolve different a DynamicResource when there are 250 PlainResources registered.""" @@ -289,7 +289,7 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ( ret.get_info()["formatter"] == "/api/server/dispatch/{customer}/update" @@ -297,11 +297,11 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_dynamic_resource_url_with_many_dynamic_routes( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, ) -> None: """Resolve different a DynamicResource when there are 250 DynamicResources registered.""" @@ -330,7 +330,7 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ( ret.get_info()["formatter"] == "/api/server/dispatch/{customer}/update" @@ -338,11 +338,11 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_dynamic_resource_url_with_many_dynamic_routes_with_common_prefix( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, ) -> None: """Resolve different a DynamicResource when there are 250 DynamicResources registered with the same common prefix.""" @@ -369,17 +369,17 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ret.get_info()["formatter"] == "/api/{customer}/update", ret.get_info() @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_gitapi( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, github_urls: list[str], ) -> None: @@ -417,7 +417,7 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: ret = await router.resolve(request) return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ( ret.get_info()["formatter"] @@ -426,11 +426,11 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_gitapi_subapps( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, github_urls: list[str], ) -> None: @@ -488,7 +488,7 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: ret = await router.resolve(request) return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ( ret.get_info()["formatter"] @@ -497,11 +497,11 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_gitapi_root( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, github_urls: list[str], ) -> None: @@ -524,17 +524,17 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: ret = await router.resolve(request) return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ret.get_info()["path"] == "/", ret.get_info() @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) def test_resolve_prefix_resources_many_prefix_many_plain( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, benchmark: BenchmarkFixture, ) -> None: """Resolve prefix resource (sub_app) whene 250 PlainResources registered and there are 250 subapps that shares the same sub_app path prefix.""" @@ -564,7 +564,7 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: ret = await router.resolve(request) return ret - ret = loop.run_until_complete(run_url_dispatcher_benchmark()) + ret = event_loop.run_until_complete(run_url_dispatcher_benchmark()) assert ret is not None assert ( ret.get_info()["path"] == "/api/path/to/plugin/249/deep/enough/sub/path" @@ -572,4 +572,4 @@ async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]: @benchmark def _run() -> None: - loop.run_until_complete(run_url_dispatcher_benchmark()) + event_loop.run_until_complete(run_url_dispatcher_benchmark()) diff --git a/tests/test_client_functional.py b/tests/test_client_functional.py index a7e229bfaa1..6c4196e4cb9 100644 --- a/tests/test_client_functional.py +++ b/tests/test_client_functional.py @@ -29,6 +29,7 @@ import pytest import trustme from multidict import MultiDict +from pytest_aiohttp import AiohttpClient, AiohttpServer from pytest_mock import MockerFixture from yarl import URL @@ -48,8 +49,7 @@ from aiohttp.client_reqrep import ClientRequest from aiohttp.connector import Connection from aiohttp.http_writer import StreamWriter -from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer -from aiohttp.test_utils import TestClient, TestServer, unused_port +from aiohttp.test_utils import TestClient, TestServer from aiohttp.typedefs import Handler, Query @@ -253,7 +253,7 @@ async def handler(request: web.Request) -> web.Response: assert 0 == len(client._session.connector._conns) -async def test_keepalive_timeout_async_sleep() -> None: +async def test_keepalive_timeout_async_sleep(unused_tcp_port: int) -> None: async def handler(request: web.Request) -> web.Response: body = await request.read() assert b"" == body @@ -265,17 +265,16 @@ async def handler(request: web.Request) -> web.Response: runner = web.AppRunner(app, tcp_keepalive=True, keepalive_timeout=0.001) await runner.setup() - port = unused_port() - site = web.TCPSite(runner, host="localhost", port=port) + site = web.TCPSite(runner, host="localhost", port=unused_tcp_port) await site.start() try: async with aiohttp.ClientSession() as sess: - resp1 = await sess.get(f"http://localhost:{port}/") + resp1 = await sess.get(f"http://localhost:{unused_tcp_port}/") await resp1.read() # wait for server keepalive_timeout await asyncio.sleep(0.01) - resp2 = await sess.get(f"http://localhost:{port}/") + resp2 = await sess.get(f"http://localhost:{unused_tcp_port}/") await resp2.read() finally: await asyncio.gather(runner.shutdown(), site.stop()) @@ -285,7 +284,7 @@ async def handler(request: web.Request) -> web.Response: sys.version_info[:2] == (3, 11), reason="https://github.com/pytest-dev/pytest/issues/10763", ) -async def test_keepalive_timeout_sync_sleep() -> None: +async def test_keepalive_timeout_sync_sleep(unused_tcp_port: int) -> None: async def handler(request: web.Request) -> web.Response: body = await request.read() assert b"" == body @@ -297,18 +296,17 @@ async def handler(request: web.Request) -> web.Response: runner = web.AppRunner(app, tcp_keepalive=True, keepalive_timeout=0.001) await runner.setup() - port = unused_port() - site = web.TCPSite(runner, host="localhost", port=port) + site = web.TCPSite(runner, host="localhost", port=unused_tcp_port) await site.start() try: async with aiohttp.ClientSession() as sess: - resp1 = await sess.get(f"http://localhost:{port}/") + resp1 = await sess.get(f"http://localhost:{unused_tcp_port}/") await resp1.read() # wait for server keepalive_timeout # time.sleep is a more challenging scenario than asyncio.sleep time.sleep(0.01) - resp2 = await sess.get(f"http://localhost:{port}/") + resp2 = await sess.get(f"http://localhost:{unused_tcp_port}/") await resp2.read() finally: await asyncio.gather(runner.shutdown(), site.stop()) @@ -3620,7 +3618,7 @@ async def handler(request: web.Request) -> web.Response: assert 1 == len(client.session.connector._conns) -async def test_server_close_keepalive_connection() -> None: +async def test_server_close_keepalive_connection(unused_tcp_port: int) -> None: loop = asyncio.get_event_loop() class Proto(asyncio.Protocol): @@ -3645,7 +3643,7 @@ def data_received(self, data: bytes) -> None: def connection_lost(self, exc: Optional[BaseException]) -> None: self.transp = None - server = await loop.create_server(Proto, "127.0.0.1", unused_port()) + server = await loop.create_server(Proto, "127.0.0.1", unused_tcp_port) addr = server.sockets[0].getsockname() @@ -3663,7 +3661,7 @@ def connection_lost(self, exc: Optional[BaseException]) -> None: await server.wait_closed() -async def test_handle_keepalive_on_closed_connection() -> None: +async def test_handle_keepalive_on_closed_connection(unused_tcp_port: int) -> None: loop = asyncio.get_event_loop() class Proto(asyncio.Protocol): @@ -3682,7 +3680,7 @@ def data_received(self, data: bytes) -> None: def connection_lost(self, exc: Optional[BaseException]) -> None: self.transp = None - server = await loop.create_server(Proto, "127.0.0.1", unused_port()) + server = await loop.create_server(Proto, "127.0.0.1", unused_tcp_port) addr = server.sockets[0].getsockname() diff --git a/tests/test_client_proto.py b/tests/test_client_proto.py index e5d62d1e467..93a9b9905c0 100644 --- a/tests/test_client_proto.py +++ b/tests/test_client_proto.py @@ -12,19 +12,19 @@ from aiohttp.http_parser import RawResponseMessage -async def test_force_close(loop: asyncio.AbstractEventLoop) -> None: +def test_force_close(event_loop: asyncio.AbstractEventLoop) -> 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=event_loop) proto.force_close() assert proto.should_close -async def test_oserror(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +def test_oserror(event_loop: asyncio.AbstractEventLoop) -> None: + proto = ResponseHandler(loop=event_loop) transport = mock.Mock() proto.connection_made(transport) proto.connection_lost(OSError()) @@ -33,8 +33,8 @@ async def test_oserror(loop: asyncio.AbstractEventLoop) -> None: assert isinstance(proto.exception(), ClientOSError) -async def test_pause_resume_on_error(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +def test_pause_resume_on_error(event_loop: asyncio.AbstractEventLoop) -> None: + proto = ResponseHandler(loop=event_loop) transport = mock.Mock() proto.connection_made(transport) @@ -45,8 +45,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) +def test_client_proto_bad_message(event_loop: asyncio.AbstractEventLoop) -> None: + proto = ResponseHandler(loop=event_loop) transport = mock.Mock() proto.connection_made(transport) proto.set_response_params() @@ -57,8 +57,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) +def test_uncompleted_message(event_loop: asyncio.AbstractEventLoop) -> None: + proto = ResponseHandler(loop=event_loop) transport = mock.Mock() proto.connection_made(transport) proto.set_response_params(read_until_eof=True) @@ -75,8 +75,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) +def test_data_received_after_close(event_loop: asyncio.AbstractEventLoop) -> None: + proto = ResponseHandler(loop=event_loop) transport = mock.Mock() proto.connection_made(transport) proto.set_response_params(read_until_eof=True) @@ -89,9 +89,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) @@ -123,9 +122,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): @@ -157,7 +155,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) @@ -194,23 +193,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) +def test_empty_data(event_loop: asyncio.AbstractEventLoop) -> None: + proto = ResponseHandler(loop=event_loop) proto.data_received(b"") # do nothing -async def test_schedule_timeout(loop: asyncio.AbstractEventLoop) -> None: - proto = ResponseHandler(loop=loop) +def test_schedule_timeout(event_loop: asyncio.AbstractEventLoop) -> None: + proto = ResponseHandler(loop=event_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) +def test_drop_timeout(event_loop: asyncio.AbstractEventLoop) -> None: + proto = ResponseHandler(loop=event_loop) proto.set_response_params(read_timeout=1) proto.start_timeout() assert proto._read_timeout_handle is not None @@ -218,8 +217,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) +def test_reschedule_timeout(event_loop: asyncio.AbstractEventLoop) -> None: + proto = ResponseHandler(loop=event_loop) proto.set_response_params(read_timeout=1) proto.start_timeout() assert proto._read_timeout_handle is not None @@ -229,8 +228,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) +def test_eof_received(event_loop: asyncio.AbstractEventLoop) -> None: + proto = ResponseHandler(loop=event_loop) proto.set_response_params(read_timeout=1) proto.start_timeout() assert proto._read_timeout_handle is not None @@ -238,14 +237,14 @@ 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 +def test_connection_lost_sets_transport_to_none( + event_loop: asyncio.AbstractEventLoop, 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=event_loop) proto.connection_made(mocker.Mock()) assert proto.transport is not None diff --git a/tests/test_client_request.py b/tests/test_client_request.py index e1e8e3d9992..e68b249364d 100644 --- a/tests/test_client_request.py +++ b/tests/test_client_request.py @@ -51,17 +51,17 @@ def remove_done_callback(self, cb: Callable[[], None]) -> None: @pytest.fixture -def make_request(loop: asyncio.AbstractEventLoop) -> Iterator[_RequestMaker]: +def make_request(event_loop: asyncio.AbstractEventLoop) -> Iterator[_RequestMaker]: request = None def maker(method: str, url: str, **kwargs: Any) -> ClientRequest: nonlocal request - request = ClientRequest(method, URL(url), loop=loop, **kwargs) + request = ClientRequest(method, URL(url), loop=event_loop, **kwargs) return request yield maker if request is not None: - loop.run_until_complete(request.close()) + event_loop.run_until_complete(request.close()) @pytest.fixture @@ -71,11 +71,11 @@ def buf() -> bytearray: @pytest.fixture def protocol( - loop: asyncio.AbstractEventLoop, transport: asyncio.Transport + event_loop: asyncio.AbstractEventLoop, transport: asyncio.Transport ) -> BaseProtocol: protocol = mock.Mock() protocol.transport = transport - protocol._drain_helper.return_value = loop.create_future() + protocol._drain_helper.return_value = event_loop.create_future() protocol._drain_helper.return_value.set_result(None) return protocol @@ -588,18 +588,18 @@ def test_gen_netloc_no_port(make_request: _RequestMaker) -> None: ) -def test_cookie_coded_value_preserved(loop: asyncio.AbstractEventLoop) -> None: +def test_cookie_coded_value_preserved(event_loop: asyncio.AbstractEventLoop) -> None: """Verify the coded value of a cookie is preserved.""" # https://github.com/aio-libs/aiohttp/pull/1453 - req = ClientRequest("get", URL("http://python.org"), loop=loop) + req = ClientRequest("get", URL("http://python.org"), loop=event_loop) req.update_cookies(cookies=SimpleCookie('ip-cookie="second"; Domain=127.0.0.1;')) assert req.headers["COOKIE"] == 'ip-cookie="second"' -async def test_connection_header( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: - req = ClientRequest("get", URL("http://python.org"), loop=loop) +async def test_connection_header(conn: mock.Mock) -> None: + req = ClientRequest( + "get", URL("http://python.org"), loop=asyncio.get_running_loop() + ) req.headers.clear() req.version = HttpVersion11 @@ -627,65 +627,67 @@ async def test_connection_header( assert not req.headers.get("CONNECTION") -async def test_no_content_length( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: - req = ClientRequest("get", URL("http://python.org"), loop=loop) +async def test_no_content_length(conn: mock.Mock) -> None: + req = ClientRequest( + "get", URL("http://python.org"), loop=asyncio.get_running_loop() + ) resp = await req.send(conn) assert req.headers.get("CONTENT-LENGTH") is None await req.close() resp.close() -async def test_no_content_length_head( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: - req = ClientRequest("head", URL("http://python.org"), loop=loop) +async def test_no_content_length_head(conn: mock.Mock) -> None: + req = ClientRequest( + "head", URL("http://python.org"), loop=asyncio.get_running_loop() + ) resp = await req.send(conn) assert req.headers.get("CONTENT-LENGTH") is None await req.close() resp.close() -async def test_content_type_auto_header_get( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: - req = ClientRequest("get", URL("http://python.org"), loop=loop) +async def test_content_type_auto_header_get(conn: mock.Mock) -> None: + req = ClientRequest( + "get", URL("http://python.org"), loop=asyncio.get_running_loop() + ) resp = await req.send(conn) assert "CONTENT-TYPE" not in req.headers resp.close() await req.close() -async def test_content_type_auto_header_form( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_content_type_auto_header_form(conn: mock.Mock) -> None: req = ClientRequest( - "post", URL("http://python.org"), data={"hey": "you"}, loop=loop + "post", + URL("http://python.org"), + data={"hey": "you"}, + loop=asyncio.get_running_loop(), ) resp = await req.send(conn) assert "application/x-www-form-urlencoded" == req.headers.get("CONTENT-TYPE") resp.close() -async def test_content_type_auto_header_bytes( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: - req = ClientRequest("post", URL("http://python.org"), data=b"hey you", loop=loop) +async def test_content_type_auto_header_bytes(conn: mock.Mock) -> None: + req = ClientRequest( + "post", + URL("http://python.org"), + data=b"hey you", + loop=asyncio.get_running_loop(), + ) resp = await req.send(conn) assert "application/octet-stream" == req.headers.get("CONTENT-TYPE") resp.close() -async def test_content_type_skip_auto_header_bytes( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_content_type_skip_auto_header_bytes(conn: mock.Mock) -> None: req = ClientRequest( "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) @@ -693,14 +695,12 @@ async def test_content_type_skip_auto_header_bytes( resp.close() -async def test_content_type_skip_auto_header_form( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_content_type_skip_auto_header_form(conn: mock.Mock) -> None: req = ClientRequest( "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) @@ -708,30 +708,26 @@ async def test_content_type_skip_auto_header_form( resp.close() -async def test_content_type_auto_header_content_length_no_skip( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_content_type_auto_header_content_length_no_skip(conn: mock.Mock) -> None: with io.BytesIO(b"hey") as file_handle: req = ClientRequest( "post", 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" resp.close() -async def test_urlencoded_formdata_charset( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_urlencoded_formdata_charset(conn: mock.Mock) -> None: req = ClientRequest( "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) @@ -740,9 +736,7 @@ async def test_urlencoded_formdata_charset( ) -async def test_formdata_boundary_from_headers( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_formdata_boundary_from_headers(conn: mock.Mock) -> None: boundary = "some_boundary" file_path = pathlib.Path(__file__).parent / "aiohttp.png" with file_path.open("rb") as f: @@ -751,17 +745,20 @@ async def test_formdata_boundary_from_headers( URL("http://python.org"), data={"aiohttp.png": f}, headers={"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) assert req.body._boundary == boundary.encode() -async def test_post_data(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> None: +async def test_post_data(conn: mock.Mock) -> None: for meth in ClientRequest.POST_METHODS: req = ClientRequest( - meth, URL("http://python.org/"), data={"life": "42"}, loop=loop + meth, + URL("http://python.org/"), + data={"life": "42"}, + loop=asyncio.get_running_loop(), ) resp = await req.send(conn) assert "/" == req.url.path @@ -771,16 +768,16 @@ async def test_post_data(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> No resp.close() -async def test_pass_falsy_data(loop: asyncio.AbstractEventLoop) -> None: +async def test_pass_falsy_data() -> None: with mock.patch("aiohttp.client_reqrep.ClientRequest.update_body_from_data") as m: - req = ClientRequest("post", URL("http://python.org/"), data={}, loop=loop) + req = ClientRequest( + "post", URL("http://python.org/"), data={}, loop=asyncio.get_running_loop() + ) m.assert_called_once_with({}) await req.close() -async def test_pass_falsy_data_file( - loop: asyncio.AbstractEventLoop, tmp_path: pathlib.Path -) -> None: +async def test_pass_falsy_data_file(tmp_path: pathlib.Path) -> None: testfile = (tmp_path / "tmpfile").open("w+b") testfile.write(b"data") testfile.seek(0) @@ -790,7 +787,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() @@ -798,20 +795,26 @@ 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) -> None: +async def test_get_with_data() -> None: for meth in ClientRequest.GET_METHODS: req = ClientRequest( - meth, URL("http://python.org/"), data={"life": "42"}, loop=loop + meth, + URL("http://python.org/"), + data={"life": "42"}, + loop=asyncio.get_running_loop(), ) assert "/" == req.url.path assert b"life=42" == req.body._value await req.close() -async def test_bytes_data(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> None: +async def test_bytes_data(conn: mock.Mock) -> None: for meth in ClientRequest.POST_METHODS: req = ClientRequest( - meth, URL("http://python.org/"), data=b"binary data", loop=loop + meth, + URL("http://python.org/"), + data=b"binary data", + loop=asyncio.get_running_loop(), ) resp = await req.send(conn) assert "/" == req.url.path @@ -823,12 +826,13 @@ async def test_bytes_data(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> N @pytest.mark.usefixtures("parametrize_zlib_backend") -async def test_content_encoding( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, -) -> None: +async def test_content_encoding(conn: mock.Mock) -> None: req = ClientRequest( - "post", URL("http://python.org/"), data="foo", compress="deflate", loop=loop + "post", + URL("http://python.org/"), + data="foo", + compress="deflate", + loop=asyncio.get_running_loop(), ) with mock.patch("aiohttp.client_reqrep.StreamWriter") as m_writer: m_writer.return_value.write_headers = make_mocked_coro() @@ -840,11 +844,12 @@ async def test_content_encoding( resp.close() -async def test_content_encoding_dont_set_headers_if_no_body( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_content_encoding_dont_set_headers_if_no_body(conn: mock.Mock) -> None: req = ClientRequest( - "post", URL("http://python.org/"), compress="deflate", loop=loop + "post", + URL("http://python.org/"), + compress="deflate", + loop=asyncio.get_running_loop(), ) with mock.patch("aiohttp.client_reqrep.http"): resp = await req.send(conn) @@ -855,16 +860,13 @@ async def test_content_encoding_dont_set_headers_if_no_body( @pytest.mark.usefixtures("parametrize_zlib_backend") -async def test_content_encoding_header( - loop: asyncio.AbstractEventLoop, - conn: mock.Mock, -) -> None: +async def test_content_encoding_header(conn: mock.Mock) -> None: req = ClientRequest( "post", URL("http://python.org/"), data="foo", headers={"Content-Encoding": "deflate"}, - loop=loop, + loop=asyncio.get_running_loop(), ) with mock.patch("aiohttp.client_reqrep.StreamWriter") as m_writer: m_writer.return_value.write_headers = make_mocked_coro() @@ -876,9 +878,7 @@ async def test_content_encoding_header( resp.close() -async def test_compress_and_content_encoding( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_compress_and_content_encoding(conn: mock.Mock) -> None: with pytest.raises(ValueError): ClientRequest( "post", @@ -886,16 +886,16 @@ async def test_compress_and_content_encoding( data="foo", headers={"content-encoding": "deflate"}, compress="deflate", - loop=loop, + loop=asyncio.get_running_loop(), ) -async def test_chunked(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> None: +async def test_chunked(conn: mock.Mock) -> None: req = ClientRequest( "post", URL("http://python.org/"), headers={"TRANSFER-ENCODING": "gzip"}, - loop=loop, + loop=asyncio.get_running_loop(), ) resp = await req.send(conn) assert "gzip" == req.headers["TRANSFER-ENCODING"] @@ -903,12 +903,12 @@ async def test_chunked(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> None resp.close() -async def test_chunked2(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> None: +async def test_chunked2(conn: mock.Mock) -> None: req = ClientRequest( "post", URL("http://python.org/"), headers={"Transfer-encoding": "chunked"}, - loop=loop, + loop=asyncio.get_running_loop(), ) resp = await req.send(conn) assert "chunked" == req.headers["TRANSFER-ENCODING"] @@ -916,15 +916,13 @@ async def test_chunked2(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> Non resp.close() -async def test_chunked_empty_body( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_chunked_empty_body(conn: mock.Mock) -> None: """Ensure write_bytes is called even if the body is empty.""" req = ClientRequest( "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: @@ -935,10 +933,10 @@ async def test_chunked_empty_body( resp.close() -async def test_chunked_explicit( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: - req = ClientRequest("post", URL("http://python.org/"), chunked=True, loop=loop) +async def test_chunked_explicit(conn: mock.Mock) -> None: + req = ClientRequest( + "post", URL("http://python.org/"), chunked=True, loop=asyncio.get_running_loop() + ) with mock.patch("aiohttp.client_reqrep.StreamWriter") as m_writer: m_writer.return_value.write_headers = make_mocked_coro() resp = await req.send(conn) @@ -949,43 +947,41 @@ async def test_chunked_explicit( resp.close() -async def test_chunked_length(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> None: +async def test_chunked_length(conn: mock.Mock) -> None: with pytest.raises(ValueError): ClientRequest( "post", URL("http://python.org/"), headers={"CONTENT-LENGTH": "1000"}, chunked=True, - loop=loop, + loop=asyncio.get_running_loop(), ) -async def test_chunked_transfer_encoding( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_chunked_transfer_encoding(conn: mock.Mock) -> None: with pytest.raises(ValueError): ClientRequest( "post", URL("http://python.org/"), headers={"TRANSFER-ENCODING": "chunked"}, chunked=True, - loop=loop, + loop=asyncio.get_running_loop(), ) -async def test_file_upload_not_chunked(loop: asyncio.AbstractEventLoop) -> None: +async def test_file_upload_not_chunked() -> None: file_path = pathlib.Path(__file__).parent / "aiohttp.png" with file_path.open("rb") as f: - req = ClientRequest("post", URL("http://python.org/"), data=f, loop=loop) + req = ClientRequest( + "post", URL("http://python.org/"), data=f, loop=asyncio.get_running_loop() + ) assert not req.chunked assert req.headers["CONTENT-LENGTH"] == str(file_path.stat().st_size) await req.close() @pytest.mark.usefixtures("parametrize_zlib_backend") -async def test_precompressed_data_stays_intact( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_precompressed_data_stays_intact() -> None: data = ZLibBackend.compress(b"foobar") req = ClientRequest( "post", @@ -993,7 +989,7 @@ async def test_precompressed_data_stays_intact( data=data, headers={"CONTENT-ENCODING": "deflate"}, compress=False, - loop=loop, + loop=asyncio.get_running_loop(), ) assert not req.compress assert not req.chunked @@ -1001,28 +997,39 @@ async def test_precompressed_data_stays_intact( await req.close() -async def test_file_upload_not_chunked_seek(loop: asyncio.AbstractEventLoop) -> None: +async def test_file_upload_not_chunked_seek() -> None: file_path = pathlib.Path(__file__).parent / "aiohttp.png" with file_path.open("rb") as f: f.seek(100) - req = ClientRequest("post", URL("http://python.org/"), data=f, loop=loop) + req = ClientRequest( + "post", URL("http://python.org/"), data=f, loop=asyncio.get_running_loop() + ) assert req.headers["CONTENT-LENGTH"] == str(file_path.stat().st_size - 100) await req.close() -async def test_file_upload_force_chunked(loop: asyncio.AbstractEventLoop) -> None: +async def test_file_upload_force_chunked() -> None: file_path = pathlib.Path(__file__).parent / "aiohttp.png" with file_path.open("rb") as f: req = ClientRequest( - "post", URL("http://python.org/"), data=f, chunked=True, loop=loop + "post", + URL("http://python.org/"), + data=f, + chunked=True, + loop=asyncio.get_running_loop(), ) assert req.chunked assert "CONTENT-LENGTH" not in req.headers await req.close() -async def test_expect100(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> None: - req = ClientRequest("get", URL("http://python.org/"), expect100=True, loop=loop) +async def test_expect100(conn: mock.Mock) -> None: + req = ClientRequest( + "get", + URL("http://python.org/"), + expect100=True, + loop=asyncio.get_running_loop(), + ) resp = await req.send(conn) assert "100-continue" == req.headers["EXPECT"] assert req._continue is not None @@ -1030,11 +1037,12 @@ async def test_expect100(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> No resp.close() -async def test_expect_100_continue_header( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_expect_100_continue_header(conn: mock.Mock) -> None: req = ClientRequest( - "get", URL("http://python.org/"), headers={"expect": "100-continue"}, loop=loop + "get", + URL("http://python.org/"), + headers={"expect": "100-continue"}, + loop=asyncio.get_running_loop(), ) resp = await req.send(conn) assert "100-continue" == req.headers["EXPECT"] @@ -1043,14 +1051,14 @@ async def test_expect_100_continue_header( resp.close() -async def test_data_stream( - loop: asyncio.AbstractEventLoop, buf: bytearray, conn: mock.Mock -) -> None: +async def test_data_stream(buf: bytearray, conn: mock.Mock) -> None: async def gen() -> AsyncIterator[bytes]: yield b"binary data" yield b" result" - req = ClientRequest("POST", URL("http://python.org/"), data=gen(), loop=loop) + req = ClientRequest( + "POST", URL("http://python.org/"), data=gen(), loop=asyncio.get_running_loop() + ) assert req.chunked assert req.headers["TRANSFER-ENCODING"] == "chunked" original_write_bytes = req.write_bytes @@ -1071,15 +1079,13 @@ async def _mock_write_bytes(writer: AbstractStreamWriter, conn: mock.Mock) -> No await req.close() -async def test_data_file( - loop: asyncio.AbstractEventLoop, buf: bytearray, conn: mock.Mock -) -> None: +async def test_data_file(buf: bytearray, conn: mock.Mock) -> None: with io.BufferedReader(io.BytesIO(b"*" * 2)) as file_handle: # type: ignore[arg-type] req = ClientRequest( "POST", URL("http://python.org/"), data=file_handle, - loop=loop, + loop=asyncio.get_running_loop(), ) assert req.chunked assert isinstance(req.body, payload.BufferedReaderPayload) @@ -1094,9 +1100,8 @@ async def test_data_file( await req.close() -async def test_data_stream_exc( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_data_stream_exc(conn: mock.Mock) -> None: + loop = asyncio.get_running_loop() fut = loop.create_future() async def gen() -> AsyncIterator[bytes]: @@ -1123,9 +1128,8 @@ async def throw_exc() -> None: await req.close() -async def test_data_stream_exc_chain( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_data_stream_exc_chain(conn: mock.Mock) -> None: + loop = asyncio.get_running_loop() fut = loop.create_future() async def gen() -> AsyncIterator[None]: @@ -1155,15 +1159,17 @@ async def throw_exc() -> None: await req.close() -async def test_data_stream_continue( - loop: asyncio.AbstractEventLoop, buf: bytearray, conn: mock.Mock -) -> None: +async def test_data_stream_continue(buf: bytearray, conn: mock.Mock) -> None: async def gen() -> AsyncIterator[bytes]: yield b"binary data" yield b" result" req = ClientRequest( - "POST", URL("http://python.org/"), data=gen(), expect100=True, loop=loop + "POST", + URL("http://python.org/"), + data=gen(), + expect100=True, + loop=asyncio.get_running_loop(), ) assert req.chunked @@ -1172,7 +1178,7 @@ async def coro() -> None: assert req._continue is not None req._continue.set_result(1) - t = loop.create_task(coro()) + t = asyncio.get_running_loop().create_task(coro()) resp = await req.send(conn) assert req._writer is not None @@ -1185,9 +1191,8 @@ async def coro() -> None: resp.close() -async def test_data_continue( - loop: asyncio.AbstractEventLoop, buf: bytearray, conn: mock.Mock -) -> None: +async def test_data_continue(buf: bytearray, conn: mock.Mock) -> None: + loop = asyncio.get_running_loop() req = ClientRequest( "POST", URL("http://python.org/"), data=b"data", expect100=True, loop=loop ) @@ -1209,14 +1214,14 @@ async def coro() -> None: resp.close() -async def test_close( - loop: asyncio.AbstractEventLoop, buf: bytearray, conn: mock.Mock -) -> None: +async def test_close(buf: bytearray, conn: mock.Mock) -> None: async def gen() -> AsyncIterator[bytes]: await asyncio.sleep(0.00001) yield b"result" - req = ClientRequest("POST", URL("http://python.org/"), data=gen(), loop=loop) + req = ClientRequest( + "POST", URL("http://python.org/"), data=gen(), loop=asyncio.get_running_loop() + ) resp = await req.send(conn) await req.close() assert buf.split(b"\r\n\r\n", 1)[1] == b"6\r\nresult\r\n0\r\n\r\n" @@ -1224,11 +1229,11 @@ async def gen() -> AsyncIterator[bytes]: resp.close() -async def test_bad_version(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> None: +async def test_bad_version(conn: mock.Mock) -> None: req = ClientRequest( "GET", URL("http://python.org"), - loop=loop, + loop=asyncio.get_running_loop(), headers={"Connection": "Close"}, version=("1", "1\r\nInjected-Header: not allowed"), # type: ignore[arg-type] ) @@ -1237,15 +1242,16 @@ async def test_bad_version(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> await req.send(conn) -async def test_custom_response_class( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: +async def test_custom_response_class(conn: mock.Mock) -> None: class CustomResponse(ClientResponse): async def read(self) -> bytes: return b"customized!" req = ClientRequest( - "GET", URL("http://python.org/"), response_class=CustomResponse, loop=loop + "GET", + URL("http://python.org/"), + response_class=CustomResponse, + loop=asyncio.get_running_loop(), ) resp = await req.send(conn) assert await resp.read() == b"customized!" @@ -1253,10 +1259,10 @@ async def read(self) -> bytes: resp.close() -async def test_oserror_on_write_bytes( - loop: asyncio.AbstractEventLoop, conn: mock.Mock -) -> None: - req = ClientRequest("POST", URL("http://python.org/"), loop=loop) +async def test_oserror_on_write_bytes(conn: mock.Mock) -> None: + req = ClientRequest( + "POST", URL("http://python.org/"), loop=asyncio.get_running_loop() + ) writer = WriterMock() writer.write.side_effect = OSError @@ -1269,8 +1275,10 @@ async def test_oserror_on_write_bytes( @pytest.mark.skipif(sys.version_info < (3, 11), reason="Needs Task.cancelling()") -async def test_cancel_close(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> None: - req = ClientRequest("get", URL("http://python.org"), loop=loop) +async def test_cancel_close(conn: mock.Mock) -> None: + req = ClientRequest( + "get", URL("http://python.org"), loop=asyncio.get_running_loop() + ) req._writer = asyncio.Future() # type: ignore[assignment] t = asyncio.create_task(req.close()) @@ -1284,8 +1292,10 @@ async def test_cancel_close(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> await t -async def test_terminate(loop: asyncio.AbstractEventLoop, conn: mock.Mock) -> None: - req = ClientRequest("get", URL("http://python.org"), loop=loop) +async def test_terminate(conn: mock.Mock) -> None: + req = ClientRequest( + "get", URL("http://python.org"), loop=asyncio.get_running_loop() + ) async def _mock_write_bytes(*args: object, **kwargs: object) -> None: # Ensure the task is scheduled @@ -1312,13 +1322,14 @@ async def _mock_write_bytes(*args: object, **kwargs: object) -> None: def test_terminate_with_closed_loop( - loop: asyncio.AbstractEventLoop, conn: mock.Mock + event_loop: asyncio.AbstractEventLoop, + conn: mock.Mock, ) -> None: req = resp = writer = None async def go() -> None: nonlocal req, resp, writer - req = ClientRequest("get", URL("http://python.org"), loop=loop) + req = ClientRequest("get", URL("http://python.org"), loop=event_loop) async def _mock_write_bytes(*args: object, **kwargs: object) -> None: # Ensure the task is scheduled @@ -1335,9 +1346,9 @@ async def _mock_write_bytes(*args: object, **kwargs: object) -> None: await asyncio.sleep(0.05) - loop.run_until_complete(go()) + event_loop.run_until_complete(go()) - loop.close() + event_loop.close() assert req is not None req.terminate() assert req._writer is None @@ -1347,17 +1358,17 @@ async def _mock_write_bytes(*args: object, **kwargs: object) -> None: resp.close() -def test_terminate_without_writer(loop: asyncio.AbstractEventLoop) -> None: - req = ClientRequest("get", URL("http://python.org"), loop=loop) +async def test_terminate_without_writer() -> None: + req = ClientRequest( + "get", URL("http://python.org"), loop=asyncio.get_running_loop() + ) assert req._writer is None req.terminate() 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): @@ -1413,23 +1424,25 @@ async def create_connection( conn.close() -def test_bad_fingerprint(loop: asyncio.AbstractEventLoop) -> None: +def test_bad_fingerprint() -> None: with pytest.raises(ValueError): Fingerprint(b"invalid") -def test_insecure_fingerprint_md5(loop: asyncio.AbstractEventLoop) -> None: +def test_insecure_fingerprint_md5() -> None: with pytest.raises(ValueError): Fingerprint(hashlib.md5(b"foo").digest()) -def test_insecure_fingerprint_sha1(loop: asyncio.AbstractEventLoop) -> None: +def test_insecure_fingerprint_sha1() -> None: with pytest.raises(ValueError): Fingerprint(hashlib.sha1(b"foo").digest()) -def test_loose_cookies_types(loop: asyncio.AbstractEventLoop) -> None: - req = ClientRequest("get", URL("http://python.org"), loop=loop) +async def test_loose_cookies_types() -> None: + req = ClientRequest( + "get", URL("http://python.org"), loop=asyncio.get_running_loop() + ) morsel: "Morsel[str]" = Morsel() morsel.set(key="string", val="Another string", coded_val="really") diff --git a/tests/test_client_response.py b/tests/test_client_response.py index 75d3ee0d4b3..41865a236d4 100644 --- a/tests/test_client_response.py +++ b/tests/test_client_response.py @@ -85,7 +85,7 @@ def test_del(session: ClientSession) -> None: connection.release.assert_called_with() -def test_close(loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: +def test_close(event_loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -94,7 +94,7 @@ def test_close(loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) response._closed = False @@ -106,17 +106,17 @@ def test_close(loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: def test_wait_for_100_1( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: response = ClientResponse( "get", URL("http://python.org"), - continue100=loop.create_future(), + continue100=event_loop.create_future(), request_info=mock.Mock(), writer=WriterMock(), timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) assert response._continue is not None @@ -124,7 +124,7 @@ def test_wait_for_100_1( def test_wait_for_100_2( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: response = ClientResponse( "get", @@ -134,14 +134,14 @@ def test_wait_for_100_2( writer=WriterMock(), timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) assert response._continue is None response.close() -def test_repr(loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: +def test_repr(event_loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -150,7 +150,7 @@ def test_repr(loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) response.status = 200 @@ -191,9 +191,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -219,9 +218,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -242,7 +240,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -267,9 +266,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 @@ -282,7 +279,7 @@ def run(conn: Connection) -> None: continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, ) response._closed = False @@ -293,9 +290,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: response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -304,7 +299,7 @@ async def test_response_eof( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, ) response._closed = False @@ -316,9 +311,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: response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -327,7 +320,7 @@ async def test_response_eof_upgraded( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, ) @@ -339,9 +332,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: response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -350,7 +341,7 @@ async def test_response_eof_after_connection_detach( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, ) response._closed = False @@ -362,7 +353,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -390,9 +382,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -423,9 +414,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" response = ClientResponse( "get", @@ -455,9 +445,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -487,9 +476,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" response = ClientResponse( "get", @@ -520,9 +508,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: response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -531,7 +517,7 @@ async def test_get_encoding_body_none( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, ) @@ -548,9 +534,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -578,7 +563,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -606,9 +592,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -636,9 +621,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -666,9 +650,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: response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -677,7 +659,7 @@ async def test_json_custom_loader( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, ) h = {"Content-Type": "application/json;charset=cp1251"} @@ -691,9 +673,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: response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -702,7 +682,7 @@ async def test_json_invalid_content_type( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, ) h = {"Content-Type": "data/octet-stream"} @@ -717,9 +697,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: response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -728,7 +706,7 @@ async def test_json_no_content( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=asyncio.get_running_loop(), session=session, ) h = {"Content-Type": "application/json"} @@ -739,9 +717,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() response = ClientResponse( "get", URL("http://def-cl-resp.org"), @@ -771,7 +748,7 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": def test_get_encoding_unknown( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: response = ClientResponse( "get", @@ -781,7 +758,7 @@ def test_get_encoding_unknown( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) @@ -1138,9 +1115,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.Mock() trace.send_response_chunk_received = make_mocked_coro() response_method = "get" @@ -1180,7 +1156,7 @@ def side_effect(*args: object, **kwargs: object) -> "asyncio.Future[bytes]": def test_response_cookies( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: response = ClientResponse( "get", @@ -1190,7 +1166,7 @@ def test_response_cookies( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) cookies = response.cookies @@ -1199,7 +1175,7 @@ def test_response_cookies( def test_response_real_url( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: url = URL("http://def-cl-resp.org/#urlfragment") response = ClientResponse( @@ -1210,7 +1186,7 @@ def test_response_real_url( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) assert response.url == url.with_fragment(None) @@ -1218,7 +1194,7 @@ def test_response_real_url( def test_response_links_comma_separated( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: url = URL("http://def-cl-resp.org/") response = ClientResponse( @@ -1229,7 +1205,7 @@ def test_response_links_comma_separated( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) h = ( @@ -1249,7 +1225,7 @@ def test_response_links_comma_separated( def test_response_links_multiple_headers( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: url = URL("http://def-cl-resp.org/") response = ClientResponse( @@ -1260,7 +1236,7 @@ def test_response_links_multiple_headers( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) h = ( @@ -1275,7 +1251,7 @@ def test_response_links_multiple_headers( def test_response_links_no_rel( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: url = URL("http://def-cl-resp.org/") response = ClientResponse( @@ -1286,7 +1262,7 @@ def test_response_links_no_rel( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) h = (("Link", ""),) @@ -1297,7 +1273,7 @@ def test_response_links_no_rel( def test_response_links_quoted( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: url = URL("http://def-cl-resp.org/") response = ClientResponse( @@ -1308,7 +1284,7 @@ def test_response_links_quoted( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) h = (("Link", '; rel="home-page"'),) @@ -1319,7 +1295,7 @@ def test_response_links_quoted( def test_response_links_relative( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: url = URL("http://def-cl-resp.org/") response = ClientResponse( @@ -1330,7 +1306,7 @@ def test_response_links_relative( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) h = (("Link", "; rel=rel"),) @@ -1341,7 +1317,7 @@ def test_response_links_relative( def test_response_links_empty( - loop: asyncio.AbstractEventLoop, session: ClientSession + event_loop: asyncio.AbstractEventLoop, session: ClientSession ) -> None: url = URL("http://def-cl-resp.org/") response = ClientResponse( @@ -1352,7 +1328,7 @@ def test_response_links_empty( continue100=None, timer=TimerNoop(), traces=[], - loop=loop, + loop=event_loop, session=session, ) response._headers = CIMultiDictProxy(CIMultiDict()) diff --git a/tests/test_client_session.py b/tests/test_client_session.py index 974d330a3c9..54ac0c78f59 100644 --- a/tests/test_client_session.py +++ b/tests/test_client_session.py @@ -21,6 +21,7 @@ import pytest from multidict import CIMultiDict, MultiDict +from pytest_aiohttp import AiohttpClient, AiohttpServer from pytest_mock import MockerFixture from yarl import URL @@ -32,7 +33,6 @@ from aiohttp.connector import BaseConnector, Connection, TCPConnector, UnixConnector from aiohttp.cookiejar import CookieJar from aiohttp.http import RawResponseMessage -from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer from aiohttp.test_utils import make_mocked_coro from aiohttp.tracing import Trace @@ -48,22 +48,23 @@ class _Params(TypedDict): @pytest.fixture def connector( - loop: asyncio.AbstractEventLoop, create_mocked_conn: Callable[[], ResponseHandler] + event_loop: asyncio.AbstractEventLoop, + create_mocked_conn: Callable[[], ResponseHandler], ) -> Iterator[BaseConnector]: async def make_conn() -> BaseConnector: return BaseConnector() key = ConnectionKey("localhost", 80, False, True, None, None, None) - conn = loop.run_until_complete(make_conn()) + conn = event_loop.run_until_complete(make_conn()) proto = create_mocked_conn() conn._conns[key] = deque([(proto, 123)]) yield conn - loop.run_until_complete(conn.close()) + event_loop.run_until_complete(conn.close()) @pytest.fixture def create_session( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> Iterator[Callable[..., Awaitable[ClientSession]]]: session = None @@ -74,15 +75,15 @@ async def maker(*args: Any, **kwargs: Any) -> ClientSession: yield maker if session is not None: - loop.run_until_complete(session.close()) + event_loop.run_until_complete(session.close()) @pytest.fixture def session( # type: ignore[misc] create_session: Callable[..., Awaitable[ClientSession]], - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> ClientSession: - return loop.run_until_complete(create_session()) + return event_loop.run_until_complete(create_session()) @pytest.fixture @@ -323,7 +324,6 @@ async def test_closed(session: ClientSession) -> None: async def test_connector( create_session: Callable[..., Awaitable[ClientSession]], - loop: asyncio.AbstractEventLoop, mocker: MockerFixture, ) -> None: connector = TCPConnector() @@ -338,7 +338,6 @@ async def test_connector( async def test_create_connector( create_session: Callable[..., Awaitable[ClientSession]], - loop: asyncio.AbstractEventLoop, mocker: MockerFixture, ) -> None: session = await create_session() @@ -348,7 +347,7 @@ async def test_create_connector( assert m.called -def test_connector_loop(loop: asyncio.AbstractEventLoop) -> None: +def test_connector_loop(event_loop: asyncio.AbstractEventLoop) -> None: with contextlib.ExitStack() as stack: another_loop = asyncio.new_event_loop() stack.enter_context(contextlib.closing(another_loop)) @@ -363,13 +362,13 @@ async def make_connector() -> TCPConnector: async def make_sess() -> ClientSession: return ClientSession(connector=connector) - loop.run_until_complete(make_sess()) + event_loop.run_until_complete(make_sess()) expected = "Session and connector have to use same event loop" assert str(ctx.value).startswith(expected) another_loop.run_until_complete(connector.close()) -def test_detach(loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: +def test_detach(event_loop: asyncio.AbstractEventLoop, session: ClientSession) -> None: conn = session.connector assert conn is not None try: @@ -379,7 +378,7 @@ def test_detach(loop: asyncio.AbstractEventLoop, session: ClientSession) -> None assert session.closed assert not conn.closed finally: - loop.run_until_complete(conn.close()) + event_loop.run_until_complete(conn.close()) async def test_request_closed_session(session: ClientSession) -> None: @@ -408,7 +407,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) @@ -424,9 +424,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) @@ -449,8 +448,8 @@ async def test_del_debug( async def test_borrow_connector_loop( connector: BaseConnector, create_session: Callable[..., Awaitable[ClientSession]], - loop: asyncio.AbstractEventLoop, ) -> None: + loop = asyncio.get_running_loop() async with ClientSession(connector=connector) as session: assert session._loop is loop @@ -654,9 +653,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 jar = mock.Mock() @@ -712,7 +709,7 @@ async def handler(_: web.Request) -> web.Response: assert resp.request_info.headers.get("Cookie", "") == "name=val=foobar" -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() @@ -730,7 +727,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") @@ -779,9 +776,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}) @@ -859,9 +854,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() @@ -993,9 +986,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() @@ -1040,9 +1031,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() @@ -1174,9 +1163,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 3b1bd00b093..fc6239c890f 100644 --- a/tests/test_client_ws.py +++ b/tests/test_client_ws.py @@ -21,9 +21,7 @@ from aiohttp.test_utils import make_mocked_coro -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,7 @@ 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 +198,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 +210,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 +221,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 +232,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 +243,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 +254,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 +265,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 +276,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 +287,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 +298,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 +344,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 +357,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.Mock() WebSocketWriter.return_value = writer @@ -405,9 +383,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 = { @@ -420,7 +396,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() @@ -438,9 +414,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 @@ -456,7 +430,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() @@ -473,9 +447,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 = { @@ -488,7 +460,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.Mock() WebSocketWriter.return_value = writer @@ -508,9 +480,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 = { @@ -523,7 +493,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() @@ -548,7 +518,6 @@ async def test_send_data_after_close( exc: Type[Exception], ws_key: str, key_data: bytes, - loop: asyncio.AbstractEventLoop, ) -> None: mresp = mock.Mock() mresp.status = 101 @@ -561,7 +530,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") @@ -579,9 +548,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 = { @@ -594,7 +561,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() @@ -608,9 +575,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 = { @@ -623,7 +588,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.Mock() @@ -643,7 +608,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(), @@ -652,7 +617,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 @@ -660,9 +625,7 @@ async def test_receive_runtime_err(loop: asyncio.AbstractEventLoop) -> None: await resp.receive() -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 = { @@ -673,7 +636,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): @@ -684,7 +647,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 @@ -698,7 +661,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( @@ -709,7 +672,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 @@ -723,7 +686,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) @@ -735,9 +698,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 = { @@ -750,7 +711,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( @@ -761,9 +722,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 = { @@ -777,7 +736,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 = WebSocketWriter.return_value = mock.Mock() send_frame = writer.send_frame = make_mocked_coro() @@ -807,7 +766,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 @@ -820,7 +779,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( @@ -831,9 +790,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 = { @@ -847,7 +804,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( @@ -858,9 +815,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 = { @@ -874,7 +829,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( @@ -886,7 +841,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 @@ -900,16 +855,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 = { @@ -921,7 +874,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 3e871d8d29a..9cddcef7c9d 100644 --- a/tests/test_client_ws_functional.py +++ b/tests/test_client_ws_functional.py @@ -5,6 +5,7 @@ from unittest import mock import pytest +from pytest_aiohttp import AiohttpClient, AiohttpServer import aiohttp from aiohttp import ( @@ -19,7 +20,6 @@ from aiohttp._websocket.reader import WebSocketDataQueue from aiohttp.client_ws import ClientWSTimeout from aiohttp.http import WSCloseCode -from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer if sys.version_info >= (3, 11): import asyncio as async_timeout @@ -929,10 +929,11 @@ 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 + loop = asyncio.get_running_loop() async def handler(request: web.Request) -> NoReturn: nonlocal ping_received @@ -1263,9 +1264,7 @@ 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__.""" async def handler(request: web.Request) -> NoReturn: @@ -1274,6 +1273,7 @@ async def handler(request: web.Request) -> NoReturn: await ws.close() assert False + loop = asyncio.get_running_loop() app = web.Application() app.router.add_route("GET", "/", handler) diff --git a/tests/test_connector.py b/tests/test_connector.py index c4019df3cdf..6eaf9ab4c2b 100644 --- a/tests/test_connector.py +++ b/tests/test_connector.py @@ -26,6 +26,7 @@ from unittest import mock import pytest +from pytest_aiohttp import AiohttpClient, AiohttpServer from pytest_mock import MockerFixture from yarl import URL @@ -48,8 +49,7 @@ TCPConnector, _DNSCacheTable, ) -from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer -from aiohttp.test_utils import make_mocked_coro, unused_port +from aiohttp.test_utils import make_mocked_coro from aiohttp.tracing import Trace @@ -79,7 +79,7 @@ def ssl_key() -> ConnectionKey: # type: ignore[misc] @pytest.fixture def unix_server( - loop: asyncio.AbstractEventLoop, unix_sockname: str + event_loop: asyncio.AbstractEventLoop, unix_sockname: str ) -> Iterator[Callable[[web.Application], Awaitable[None]]]: runners = [] @@ -93,7 +93,7 @@ async def go(app: web.Application) -> None: yield go for runner in runners: - loop.run_until_complete(runner.cleanup()) + event_loop.run_until_complete(runner.cleanup()) @pytest.fixture @@ -134,7 +134,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() @@ -156,7 +157,8 @@ async def test_connection_del(loop: asyncio.AbstractEventLoop) -> None: exc_handler.assert_called_with(loop, msg) -def test_connection_del_loop_debug(loop: asyncio.AbstractEventLoop) -> None: +async def test_connection_del_loop_debug() -> None: + loop = asyncio.get_running_loop() connector = mock.Mock() key = mock.Mock() protocol = mock.Mock() @@ -177,15 +179,17 @@ def test_connection_del_loop_debug(loop: asyncio.AbstractEventLoop) -> None: exc_handler.assert_called_with(loop, msg) -def test_connection_del_loop_closed(loop: asyncio.AbstractEventLoop) -> None: +def test_connection_del_loop_closed( + event_loop: asyncio.AbstractEventLoop, +) -> None: connector = mock.Mock() key = mock.Mock() protocol = mock.Mock() - loop.set_debug(True) - conn = Connection(connector, key, protocol, loop=loop) + event_loop.set_debug(True) + conn = Connection(connector, key, protocol, loop=event_loop) exc_handler = mock.Mock() - loop.set_exception_handler(exc_handler) - loop.close() + event_loop.set_exception_handler(exc_handler) + event_loop.close() with pytest.warns(ResourceWarning): del conn @@ -195,7 +199,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) @@ -221,9 +226,8 @@ 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 -) -> None: +async def test_del_with_scheduled_cleanup(key: ConnectionKey) -> None: # type: ignore[misc] + loop = asyncio.get_running_loop() loop.set_debug(True) conn = aiohttp.BaseConnector(keepalive_timeout=0.01) transp = create_mocked_conn(loop) @@ -252,19 +256,20 @@ async def test_del_with_scheduled_cleanup( # type: ignore[misc] sys.implementation.name != "cpython", reason="CPython GC is required for the test" ) def test_del_with_closed_loop( # type: ignore[misc] - loop: asyncio.AbstractEventLoop, key: ConnectionKey + event_loop: asyncio.AbstractEventLoop, + key: ConnectionKey, ) -> None: async def make_conn() -> aiohttp.BaseConnector: return aiohttp.BaseConnector() - conn = loop.run_until_complete(make_conn()) - transp = create_mocked_conn(loop) + conn = event_loop.run_until_complete(make_conn()) + transp = create_mocked_conn(event_loop) conn._conns[key] = deque([(transp, 123)]) conns_impl = conn._conns exc_handler = mock.Mock() - loop.set_exception_handler(exc_handler) - loop.close() + event_loop.set_exception_handler(exc_handler) + event_loop.close() with pytest.warns(ResourceWarning): del conn @@ -275,11 +280,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 @@ -294,7 +299,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: @@ -316,7 +321,8 @@ async def test_close(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() assert await conn._get(key, []) is None @@ -329,7 +335,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) assert await conn._get(key, []) is None @@ -348,7 +355,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) assert await conn._get(key, []) is None @@ -367,7 +375,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) assert await conn._get(key, []) is None @@ -380,7 +389,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) assert await conn._get(key, []) is None @@ -426,7 +436,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) @@ -444,12 +455,10 @@ 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 -) -> None: +async def test_release_ssl_transport(ssl_key: ConnectionKey) -> None: # type: ignore[misc] 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) @@ -477,9 +486,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() @@ -492,7 +499,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() @@ -511,7 +518,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() @@ -526,7 +533,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() @@ -540,9 +547,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() @@ -558,7 +563,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) @@ -586,21 +591,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 @@ -608,9 +609,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) @@ -624,9 +624,11 @@ async def test__release_acquired_per_host3( async def test_tcp_connector_certificate_error( - loop: asyncio.AbstractEventLoop, start_connection: mock.AsyncMock + start_connection: mock.AsyncMock, ) -> None: - req = ClientRequest("GET", URL("https://127.0.0.1:443"), loop=loop) + req = ClientRequest( + "GET", URL("https://127.0.0.1:443"), loop=asyncio.get_running_loop() + ) conn = aiohttp.TCPConnector() with mock.patch.object( @@ -647,7 +649,7 @@ async def test_tcp_connector_certificate_error( async def test_tcp_connector_server_hostname_default( - loop: asyncio.AbstractEventLoop, start_connection: mock.AsyncMock + start_connection: mock.AsyncMock, ) -> None: conn = aiohttp.TCPConnector() @@ -656,7 +658,9 @@ async def test_tcp_connector_server_hostname_default( ) as create_connection: create_connection.return_value = mock.Mock(), mock.Mock() - req = ClientRequest("GET", URL("https://127.0.0.1:443"), loop=loop) + req = ClientRequest( + "GET", URL("https://127.0.0.1:443"), loop=asyncio.get_running_loop() + ) with closing(await conn.connect(req, [], ClientTimeout())): assert create_connection.call_args.kwargs["server_hostname"] == "127.0.0.1" @@ -665,7 +669,7 @@ async def test_tcp_connector_server_hostname_default( async def test_tcp_connector_server_hostname_override( - loop: asyncio.AbstractEventLoop, start_connection: mock.AsyncMock + start_connection: mock.AsyncMock, ) -> None: conn = aiohttp.TCPConnector() @@ -675,7 +679,10 @@ async def test_tcp_connector_server_hostname_override( create_connection.return_value = mock.Mock(), mock.Mock() req = ClientRequest( - "GET", URL("https://127.0.0.1:443"), loop=loop, server_hostname="localhost" + "GET", + URL("https://127.0.0.1:443"), + loop=asyncio.get_running_loop(), + server_hostname="localhost", ) with closing(await conn.connect(req, [], ClientTimeout())): @@ -684,9 +691,8 @@ async def test_tcp_connector_server_hostname_override( await conn.close() -async def test_tcp_connector_multiple_hosts_errors( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_multiple_hosts_errors() -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector() ip1 = "192.168.1.1" @@ -854,8 +860,9 @@ def get_extra_info(param: str) -> object: [0.1, 0.25, None], ) async def test_tcp_connector_happy_eyeballs( - loop: asyncio.AbstractEventLoop, happy_eyeballs_delay: Optional[float] + happy_eyeballs_delay: Optional[float], ) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector(happy_eyeballs_delay=happy_eyeballs_delay) ip1 = "dead::beef::" @@ -940,7 +947,8 @@ async def create_connection( await conn.close() -async def test_tcp_connector_interleave(loop: asyncio.AbstractEventLoop) -> None: +async def test_tcp_connector_interleave() -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector(interleave=2) ip1 = "192.168.1.1" @@ -1032,9 +1040,8 @@ async def create_connection( await conn.close() -async def test_tcp_connector_family_is_respected( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_tcp_connector_family_is_respected() -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector(family=socket.AF_INET) ip1 = "dead::beef::" @@ -1118,10 +1125,8 @@ async def create_connection( ("https://mocked.host"), ], ) -async def test_tcp_connector_multiple_hosts_one_timeout( - loop: asyncio.AbstractEventLoop, - request_url: str, -) -> None: +async def test_tcp_connector_multiple_hosts_one_timeout(request_url: str) -> None: + loop = asyncio.get_running_loop() conn = aiohttp.TCPConnector() ip1 = "192.168.1.1" @@ -1230,7 +1235,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) @@ -1253,7 +1258,9 @@ 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( + event_loop: asyncio.AbstractEventLoop, +) -> Callable[[], Awaitable[List[str]]]: async def coro() -> List[str]: # simulates a network operation await asyncio.sleep(0) @@ -1263,7 +1270,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: conn = aiohttp.TCPConnector(use_dns_cache=True, ttl_dns_cache=10) @@ -1276,7 +1283,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: conn = aiohttp.TCPConnector(use_dns_cache=True, ttl_dns_cache=10) @@ -1289,7 +1296,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: conn = aiohttp.TCPConnector(use_dns_cache=False) @@ -1307,8 +1314,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: conn = aiohttp.TCPConnector(use_dns_cache=True, ttl_dns_cache=10) m_resolver().resolve.return_value = dns_response() @@ -1325,9 +1333,8 @@ async def test_tcp_connector_dns_throttle_requests( 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: conn = aiohttp.TCPConnector(use_dns_cache=True, ttl_dns_cache=10) e = Exception() @@ -1345,8 +1352,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: conn = aiohttp.TCPConnector(use_dns_cache=True, ttl_dns_cache=10) m_resolver().resolve.return_value = dns_response() @@ -1366,7 +1374,7 @@ async def test_tcp_connector_dns_throttle_requests_cancelled_when_close( @pytest.fixture def dns_response_error( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> Callable[[], Awaitable[NoReturn]]: async def coro() -> NoReturn: # simulates a network operation @@ -1377,9 +1385,9 @@ async def coro() -> NoReturn: async def test_tcp_connector_cancel_dns_error_captured( - loop: asyncio.AbstractEventLoop, dns_response_error: Callable[[], Awaitable[NoReturn]], ) -> None: + loop = asyncio.get_running_loop() exception_handler_called = False def exception_handler(loop: asyncio.AbstractEventLoop, context: object) -> None: @@ -1410,7 +1418,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() @@ -1457,7 +1465,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() @@ -1514,8 +1522,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.Mock(side_effect=make_mocked_coro(mock.Mock())) @@ -1550,7 +1559,7 @@ async def test_tcp_connector_dns_tracing_throttle_requests( await conn.close() -async def test_dns_error(loop: asyncio.AbstractEventLoop) -> None: +async def test_dns_error() -> None: connector = aiohttp.TCPConnector() with mock.patch.object( connector, @@ -1559,7 +1568,9 @@ async def test_dns_error(loop: asyncio.AbstractEventLoop) -> None: spec_set=True, side_effect=OSError("dont take it serious"), ): - req = ClientRequest("GET", URL("http://www.python.org"), loop=loop) + req = ClientRequest( + "GET", URL("http://www.python.org"), loop=asyncio.get_running_loop() + ) with pytest.raises(aiohttp.ClientConnectorError): await connector.connect(req, [], ClientTimeout()) @@ -1567,9 +1578,7 @@ async def test_dns_error(loop: asyncio.AbstractEventLoop) -> None: 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 @@ -1578,13 +1587,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) @@ -1594,8 +1601,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() @@ -1609,9 +1617,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) @@ -1619,17 +1625,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 @@ -1637,7 +1641,8 @@ async def test_release_not_opened( await conn.close() -async def test_connect(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> None: +async def test_connect(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -1659,7 +1664,8 @@ async def test_connect(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> N await conn.close() -async def test_connect_tracing(loop: asyncio.AbstractEventLoop) -> None: +async def test_connect_tracing() -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_connection_create_start = mock.Mock(side_effect=make_mocked_coro(mock.Mock())) @@ -1700,9 +1706,8 @@ async def test_connect_tracing(loop: asyncio.AbstractEventLoop) -> None: "on_connection_create_end", ], ) -async def test_exception_during_connetion_create_tracing( - loop: asyncio.AbstractEventLoop, signal: str -) -> None: +async def test_exception_during_connetion_create_tracing(signal: str) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_signal = mock.AsyncMock(side_effect=asyncio.CancelledError) @@ -1734,9 +1739,8 @@ async def test_exception_during_connetion_create_tracing( assert key not in conn._acquired_per_host -async def test_exception_during_connection_queued_tracing( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_exception_during_connection_queued_tracing() -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_signal = mock.AsyncMock(side_effect=asyncio.CancelledError) @@ -1775,9 +1779,8 @@ async def test_exception_during_connection_queued_tracing( await conn.close() -async def test_exception_during_connection_reuse_tracing( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_exception_during_connection_reuse_tracing() -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_signal = mock.AsyncMock(side_effect=asyncio.CancelledError) @@ -1816,9 +1819,8 @@ async def test_exception_during_connection_reuse_tracing( assert key not in conn._acquired_per_host -async def test_cancellation_during_waiting_for_free_connection( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_cancellation_during_waiting_for_free_connection() -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() waiter_wait_stated_future = loop.create_future() @@ -1860,7 +1862,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) -> None: +async def test_close_during_connect() -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -1925,9 +1928,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: - proto = create_mocked_conn(loop) + proto = create_mocked_conn(asyncio.get_running_loop()) transport = proto.transport testset: DefaultDict[ConnectionKey, Deque[Tuple[ResponseHandler, float]]] = ( defaultdict(deque) @@ -1952,7 +1955,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]]] = ( @@ -1973,7 +1976,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]]] = ( @@ -1997,9 +2001,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: +async def test_cleanup_closed(mocker: MockerFixture) -> None: + loop = asyncio.get_running_loop() if not hasattr(loop, "__dict__"): pytest.skip("can not override loop attributes") @@ -2028,9 +2031,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() @@ -2042,7 +2043,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 @@ -2052,7 +2053,7 @@ async def test_tcp_connector_ctor(loop: asyncio.AbstractEventLoop) -> None: await conn.close() -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"} @@ -2062,9 +2063,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 @@ -2072,17 +2071,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", @@ -2121,9 +2120,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") @@ -2208,8 +2205,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)]) @@ -2224,9 +2221,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 @@ -2234,7 +2229,7 @@ async def test_close_cancels_cleanup_handle( assert conn._cleanup_handle is None -async def test_close_cancels_resolve_host(loop: asyncio.AbstractEventLoop) -> None: +async def test_close_cancels_resolve_host() -> None: cancelled = False async def delay_resolve(*args: object, **kwargs: object) -> None: @@ -2248,7 +2243,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> None: conn = aiohttp.TCPConnector() req = ClientRequest( - "GET", URL("http://localhost:80"), loop=loop, response_class=mock.Mock() + "GET", + URL("http://localhost:80"), + loop=asyncio.get_running_loop(), + response_class=mock.Mock(), ) with mock.patch.object(conn._resolver, "resolve", delay_resolve): t = asyncio.create_task(conn.connect(req, [], ClientTimeout())) @@ -2267,9 +2265,7 @@ async def delay_resolve(*args: object, **kwargs: object) -> None: await t -async def test_multiple_dns_resolution_requests_success( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_multiple_dns_resolution_requests_success() -> None: """Verify that multiple DNS resolution requests are handled correctly.""" async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: @@ -2289,7 +2285,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: conn = aiohttp.TCPConnector(force_close=True) req = ClientRequest( - "GET", URL("http://localhost:80"), loop=loop, response_class=mock.Mock() + "GET", + URL("http://localhost:80"), + loop=asyncio.get_running_loop(), + response_class=mock.Mock(), ) with ( mock.patch.object(conn._resolver, "resolve", delay_resolve), @@ -2329,9 +2328,7 @@ async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: await task3 -async def test_multiple_dns_resolution_requests_failure( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_multiple_dns_resolution_requests_failure() -> None: """Verify that DNS resolution failure for multiple requests is handled correctly.""" async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: @@ -2342,7 +2339,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: conn = aiohttp.TCPConnector(force_close=True) req = ClientRequest( - "GET", URL("http://localhost:80"), loop=loop, response_class=mock.Mock() + "GET", + URL("http://localhost:80"), + loop=asyncio.get_running_loop(), + response_class=mock.Mock(), ) with ( mock.patch.object(conn._resolver, "resolve", delay_resolve), @@ -2382,9 +2382,7 @@ async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: await task3 -async def test_multiple_dns_resolution_requests_cancelled( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_multiple_dns_resolution_requests_cancelled() -> None: """Verify that DNS resolution cancellation does not affect other tasks.""" async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: @@ -2395,7 +2393,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: conn = aiohttp.TCPConnector(force_close=True) req = ClientRequest( - "GET", URL("http://localhost:80"), loop=loop, response_class=mock.Mock() + "GET", + URL("http://localhost:80"), + loop=asyncio.get_running_loop(), + response_class=mock.Mock(), ) with ( mock.patch.object(conn._resolver, "resolve", delay_resolve), @@ -2434,9 +2435,7 @@ async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: assert len(conn._resolve_host_tasks) == 0 -async def test_multiple_dns_resolution_requests_first_cancelled( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_multiple_dns_resolution_requests_first_cancelled() -> None: """Verify that first DNS resolution cancellation does not make other resolutions fail.""" async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: @@ -2456,7 +2455,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: conn = aiohttp.TCPConnector(force_close=True) req = ClientRequest( - "GET", URL("http://localhost:80"), loop=loop, response_class=mock.Mock() + "GET", + URL("http://localhost:80"), + loop=asyncio.get_running_loop(), + response_class=mock.Mock(), ) with ( mock.patch.object(conn._resolver, "resolve", delay_resolve), @@ -2497,9 +2499,7 @@ async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: assert len(conn._resolve_host_tasks) == 0 -async def test_multiple_dns_resolution_requests_first_fails_second_successful( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_multiple_dns_resolution_requests_first_fails_second_successful() -> None: """Verify that first DNS resolution fails the first time and is successful the second time.""" attempt = 0 @@ -2524,7 +2524,10 @@ async def delay_resolve(*args: object, **kwargs: object) -> List[ResolveResult]: conn = aiohttp.TCPConnector(force_close=True) req = ClientRequest( - "GET", URL("http://localhost:80"), loop=loop, response_class=mock.Mock() + "GET", + URL("http://localhost:80"), + loop=asyncio.get_running_loop(), + response_class=mock.Mock(), ) with ( mock.patch.object(conn._resolver, "resolve", delay_resolve), @@ -2577,7 +2580,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() @@ -2590,25 +2593,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 == { "", @@ -2619,9 +2618,8 @@ async def test_base_connector_allows_high_level_protocols( } -async def test_connect_with_limit( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_connect_with_limit(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -2663,9 +2661,8 @@ async def f() -> None: await conn.close() -async def test_connect_queued_operation_tracing( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_connect_queued_operation_tracing(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_connection_queued_start = mock.Mock(side_effect=make_mocked_coro(mock.Mock())) @@ -2710,9 +2707,8 @@ async def f() -> None: await conn.close() -async def test_connect_reuseconn_tracing( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_connect_reuseconn_tracing(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() session = mock.Mock() trace_config_ctx = mock.Mock() on_connection_reuseconn = mock.Mock(side_effect=make_mocked_coro(mock.Mock())) @@ -2742,9 +2738,8 @@ async def test_connect_reuseconn_tracing( await conn.close() -async def test_connect_with_limit_and_limit_per_host( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_connect_with_limit_and_limit_per_host(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -2777,9 +2772,8 @@ async def f() -> None: await conn.close() -async def test_connect_with_no_limit_and_limit_per_host( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_connect_with_no_limit_and_limit_per_host(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -2810,9 +2804,8 @@ async def f() -> None: await conn.close() -async def test_connect_with_no_limits( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_connect_with_no_limits(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -2843,9 +2836,8 @@ async def f() -> None: await conn.close() -async def test_connect_with_limit_cancelled( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_connect_with_limit_cancelled(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -2870,9 +2862,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( @@ -2891,7 +2881,8 @@ async def check_with_exc(err: Exception) -> None: await check_with_exc(asyncio.TimeoutError()) -async def test_connect_with_limit_concurrent(loop: asyncio.AbstractEventLoop) -> None: +async def test_connect_with_limit_concurrent() -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.should_close = False proto.is_connected.return_value = True @@ -2951,7 +2942,8 @@ async def f(start: bool = True) -> None: assert max_connections == num_connections -async def test_connect_waiters_cleanup(loop: asyncio.AbstractEventLoop) -> None: +async def test_connect_waiters_cleanup() -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -2971,9 +2963,8 @@ async def test_connect_waiters_cleanup(loop: asyncio.AbstractEventLoop) -> None: await conn.close() -async def test_connect_waiters_cleanup_key_error( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_connect_waiters_cleanup_key_error() -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -2999,9 +2990,8 @@ async def test_connect_waiters_cleanup_key_error( await conn.close() -async def test_close_with_acquired_connection( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_close_with_acquired_connection(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3025,51 +3015,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() @@ -3115,7 +3102,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" @@ -3138,9 +3126,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() @@ -3194,9 +3181,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() @@ -3209,16 +3194,19 @@ 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(loop: asyncio.AbstractEventLoop) -> None: +async def test_unix_connector_not_found() -> None: connector = aiohttp.UnixConnector("/" + uuid.uuid4().hex) - req = ClientRequest("GET", URL("http://www.python.org"), loop=loop) + req = ClientRequest( + "GET", URL("http://www.python.org"), loop=asyncio.get_running_loop() + ) with pytest.raises(aiohttp.ClientConnectorError): await connector.connect(req, [], ClientTimeout()) @pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="requires UNIX sockets") -async def test_unix_connector_permission(loop: asyncio.AbstractEventLoop) -> None: +async def test_unix_connector_permission() -> None: + loop = asyncio.get_running_loop() m = make_mocked_coro(raise_exception=PermissionError()) with mock.patch.object(loop, "create_unix_connection", m): connector = aiohttp.UnixConnector("/" + uuid.uuid4().hex) @@ -3275,16 +3263,14 @@ async def test_default_use_dns_cache() -> None: await conn.close() -async def test_resolver_not_called_with_address_is_ip( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_resolver_not_called_with_address_is_ip(unused_tcp_port: int) -> None: resolver = mock.MagicMock() connector = aiohttp.TCPConnector(resolver=resolver) req = ClientRequest( "GET", - URL(f"http://127.0.0.1:{unused_port()}"), - loop=loop, + URL(f"http://127.0.0.1:{unused_tcp_port}"), + loop=asyncio.get_running_loop(), response_class=mock.Mock(), ) @@ -3297,7 +3283,7 @@ async def test_resolver_not_called_with_address_is_ip( async def test_tcp_connector_raise_connector_ssl_error( - aiohttp_server: AiohttpServer, ssl_ctx: ssl.SSLContext + aiohttp_server: AiohttpServer, ssl_ctx: ssl.SSLContext, unused_tcp_port: int ) -> None: async def handler(request: web.Request) -> NoReturn: assert False @@ -3307,8 +3293,7 @@ async def handler(request: web.Request) -> NoReturn: srv = await aiohttp_server(app, ssl=ssl_ctx) - port = unused_port() - conn = aiohttp.TCPConnector(local_addr=("127.0.0.1", port)) + conn = aiohttp.TCPConnector(local_addr=("127.0.0.1", unused_tcp_port)) session = aiohttp.ClientSession(connector=conn) url = srv.make_url("/") @@ -3342,6 +3327,7 @@ async def test_tcp_connector_do_not_raise_connector_ssl_error( ssl_ctx: ssl.SSLContext, client_ssl_ctx: ssl.SSLContext, host: str, + unused_tcp_port: int, ) -> None: async def handler(request: web.Request) -> web.Response: return web.Response() @@ -3350,8 +3336,7 @@ async def handler(request: web.Request) -> web.Response: app.router.add_get("/", handler) srv = await aiohttp_server(app, ssl=ssl_ctx) - port = unused_port() - conn = aiohttp.TCPConnector(local_addr=("127.0.0.1", port)) + conn = aiohttp.TCPConnector(local_addr=("127.0.0.1", unused_tcp_port)) # resolving something.localhost with the real DNS resolver does not work on macOS, so we have a stub. async def _resolve_host( @@ -3402,6 +3387,7 @@ async def _resolve_host( async def test_tcp_connector_uses_provided_local_addr( aiohttp_server: AiohttpServer, + unused_tcp_port: int, ) -> None: async def handler(request: web.Request) -> web.Response: return web.Response() @@ -3410,8 +3396,7 @@ async def handler(request: web.Request) -> web.Response: app.router.add_get("/", handler) srv = await aiohttp_server(app) - port = unused_port() - conn = aiohttp.TCPConnector(local_addr=("127.0.0.1", port)) + conn = aiohttp.TCPConnector(local_addr=("127.0.0.1", unused_tcp_port)) session = aiohttp.ClientSession(connector=conn) url = srv.make_url("/") @@ -3421,7 +3406,8 @@ async def handler(request: web.Request) -> web.Response: first_conn = next(iter(conn._conns.values()))[0][0] assert first_conn.transport is not None - assert first_conn.transport.get_extra_info("sockname") == ("127.0.0.1", port) + sockname = first_conn.transport.get_extra_info("sockname") + assert sockname == ("127.0.0.1", unused_tcp_port) r.close() await session.close() await conn.close() @@ -3631,7 +3617,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", @@ -3660,9 +3646,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", @@ -3715,9 +3699,8 @@ async def resolve_response() -> List[ResolveResult]: await connector.close() -async def test_connector_does_not_remove_needed_waiters( - loop: asyncio.AbstractEventLoop, key: ConnectionKey -) -> None: +async def test_connector_does_not_remove_needed_waiters(key: ConnectionKey) -> None: + loop = asyncio.get_running_loop() proto = create_mocked_conn(loop) proto.is_connected.return_value = True @@ -3799,10 +3782,9 @@ def test_connect() -> Literal[True]: assert raw_response_list == [True, True] -async def test_tcp_connector_socket_factory( - loop: asyncio.AbstractEventLoop, start_connection: mock.AsyncMock -) -> None: +async def test_tcp_connector_socket_factory(start_connection: mock.AsyncMock) -> 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 diff --git a/tests/test_cookiejar.py b/tests/test_cookiejar.py index 1f78c5abba9..511439a9286 100644 --- a/tests/test_cookiejar.py +++ b/tests/test_cookiejar.py @@ -187,7 +187,6 @@ async def test_constructor_with_expired( def test_save_load( tmp_path: Path, - loop: asyncio.AbstractEventLoop, cookies_to_send: SimpleCookie, cookies_to_receive: SimpleCookie, ) -> None: @@ -208,9 +207,7 @@ def test_save_load( assert jar_test == cookies_to_receive -async def test_update_cookie_with_unicode_domain( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_update_cookie_with_unicode_domain() -> None: cookies = ( "idna-domain-first=first; Domain=xn--9caa.com; Path=/;", "idna-domain-second=second; Domain=xn--9caa.com; Path=/;", @@ -227,9 +224,7 @@ async def test_update_cookie_with_unicode_domain( assert jar_test == SimpleCookie(" ".join(cookies)) -async def test_filter_cookie_with_unicode_domain( - loop: asyncio.AbstractEventLoop, -) -> None: +async def test_filter_cookie_with_unicode_domain() -> None: jar = CookieJar() jar.update_cookies( SimpleCookie("idna-domain-first=first; Domain=xn--9caa.com; Path=/; ") @@ -238,7 +233,7 @@ async def test_filter_cookie_with_unicode_domain( assert len(jar.filter_cookies(URL("http://xn--9caa.com"))) == 1 -async def test_filter_cookies_str_deprecated(loop: asyncio.AbstractEventLoop) -> None: +async def test_filter_cookies_str_deprecated() -> None: jar = CookieJar() with pytest.deprecated_call( match="The method accepts yarl.URL instances only, got ", @@ -301,7 +296,6 @@ async def test_filter_cookies_str_deprecated(loop: asyncio.AbstractEventLoop) -> ), ) async def test_filter_cookies_with_domain_path_lookup_multilevelpath( - loop: asyncio.AbstractEventLoop, url: str, expected_cookies: Set[str], ) -> None: @@ -336,7 +330,7 @@ async def test_filter_cookies_with_domain_path_lookup_multilevelpath( assert c in expected_cookies -async def test_domain_filter_ip_cookie_send(loop: asyncio.AbstractEventLoop) -> None: +async def test_domain_filter_ip_cookie_send() -> None: jar = CookieJar() cookies = SimpleCookie( "shared-cookie=first; " @@ -397,7 +391,7 @@ async def test_domain_filter_ip_cookie_receive( ), ) async def test_quotes_correctly_based_on_input( - loop: asyncio.AbstractEventLoop, cookies: str, expected: str, quote_bool: bool + cookies: str, expected: str, quote_bool: bool ) -> None: jar = CookieJar(unsafe=True, quote_cookie=quote_bool) jar.update_cookies(SimpleCookie(cookies)) @@ -405,7 +399,7 @@ async def test_quotes_correctly_based_on_input( assert cookies_sent == expected -async def test_ignore_domain_ending_with_dot(loop: asyncio.AbstractEventLoop) -> None: +async def test_ignore_domain_ending_with_dot() -> None: jar = CookieJar(unsafe=True) jar.update_cookies( SimpleCookie("cookie=val; Domain=example.com.;"), URL("http://www.example.com") diff --git a/tests/test_flowcontrol_streams.py b/tests/test_flowcontrol_streams.py index 9e21f786610..60965c1ea23 100644 --- a/tests/test_flowcontrol_streams.py +++ b/tests/test_flowcontrol_streams.py @@ -14,9 +14,9 @@ def protocol() -> BaseProtocol: @pytest.fixture def stream( - loop: asyncio.AbstractEventLoop, protocol: BaseProtocol + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol ) -> streams.StreamReader: - return streams.StreamReader(protocol, limit=1, loop=loop) + return streams.StreamReader(protocol, limit=1, loop=event_loop) class TestFlowControlStreamReader: diff --git a/tests/test_formdata.py b/tests/test_formdata.py index 73977f4497a..14d2919b466 100644 --- a/tests/test_formdata.py +++ b/tests/test_formdata.py @@ -2,10 +2,10 @@ from unittest import mock import pytest +from pytest_aiohttp import AiohttpClient from aiohttp import FormData, web from aiohttp.http_writer import StreamWriter -from aiohttp.pytest_plugin import AiohttpClient @pytest.fixture diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 8adc33f53fc..b8193667c74 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -283,8 +283,8 @@ def test_is_ip_address_invalid_type() -> None: # ----------------------------------- TimeoutHandle ------------------- -def test_timeout_handle(loop: asyncio.AbstractEventLoop) -> None: - handle = helpers.TimeoutHandle(loop, 10.2) +def test_timeout_handle(event_loop: asyncio.AbstractEventLoop) -> None: + handle = helpers.TimeoutHandle(event_loop, 10.2) cb = mock.Mock() handle.register(cb) assert cb == handle._callbacks[0][0] @@ -292,11 +292,11 @@ def test_timeout_handle(loop: asyncio.AbstractEventLoop) -> None: assert not handle._callbacks -def test_when_timeout_smaller_second(loop: asyncio.AbstractEventLoop) -> None: +def test_when_timeout_smaller_second(event_loop: asyncio.AbstractEventLoop) -> None: timeout = 0.1 - timer = loop.time() + timeout + timer = event_loop.time() + timeout - handle = helpers.TimeoutHandle(loop, timeout) + handle = helpers.TimeoutHandle(event_loop, timeout) assert handle is not None start_handle = handle.start() assert start_handle is not None @@ -308,12 +308,12 @@ def test_when_timeout_smaller_second(loop: asyncio.AbstractEventLoop) -> None: def test_when_timeout_smaller_second_with_low_threshold( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> None: timeout = 0.1 - timer = loop.time() + timeout + timer = event_loop.time() + timeout - handle = helpers.TimeoutHandle(loop, timeout, 0.01) + handle = helpers.TimeoutHandle(event_loop, timeout, 0.01) assert handle is not None start_handle = handle.start() assert start_handle is not None @@ -324,8 +324,8 @@ def test_when_timeout_smaller_second_with_low_threshold( assert when == ceil(timer) -def test_timeout_handle_cb_exc(loop: asyncio.AbstractEventLoop) -> None: - handle = helpers.TimeoutHandle(loop, 10.2) +def test_timeout_handle_cb_exc(event_loop: asyncio.AbstractEventLoop) -> None: + handle = helpers.TimeoutHandle(event_loop, 10.2) cb = mock.Mock() handle.register(cb) cb.side_effect = ValueError() @@ -401,22 +401,20 @@ async def task_with_timeout() -> None: assert task.cancelling() == 1 -def test_timer_context_no_task(loop: asyncio.AbstractEventLoop) -> None: +def test_timer_context_no_task(event_loop: asyncio.AbstractEventLoop) -> None: with pytest.raises(RuntimeError): - with helpers.TimerContext(loop): + with helpers.TimerContext(event_loop): 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 @@ -426,9 +424,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) @@ -445,7 +443,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() @@ -457,7 +455,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() @@ -485,7 +483,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 @@ -493,9 +491,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() @@ -729,14 +725,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) @@ -744,15 +740,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 6bb06159f21..475b7a8d050 100644 --- a/tests/test_http_parser.py +++ b/tests/test_http_parser.py @@ -58,14 +58,14 @@ def _gen_ids(parsers: Iterable[Type[HttpParser[Any]]]) -> List[str]: @pytest.fixture(params=REQUEST_PARSERS, ids=_gen_ids(REQUEST_PARSERS)) def parser( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol, request: pytest.FixtureRequest, ) -> HttpRequestParser: # Parser implementations return request.param( # type: ignore[no-any-return] protocol, - loop, + event_loop, 2**16, max_line_size=8190, max_field_size=8190, @@ -80,14 +80,14 @@ def request_cls(request: pytest.FixtureRequest) -> Type[HttpRequestParser]: @pytest.fixture(params=RESPONSE_PARSERS, ids=_gen_ids(RESPONSE_PARSERS)) def response( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol, request: pytest.FixtureRequest, ) -> HttpResponseParser: # Parser implementations return request.param( # type: ignore[no-any-return] protocol, - loop, + event_loop, 2**16, max_line_size=8190, max_field_size=8190, @@ -139,13 +139,13 @@ def test_reject_obsolete_line_folding(parser: HttpRequestParser) -> None: @pytest.mark.skipif(NO_EXTENSIONS, reason="Only tests C parser.") def test_invalid_character( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol, request: pytest.FixtureRequest, ) -> None: parser = HttpRequestParserC( protocol, - loop, + event_loop, 2**16, max_line_size=8190, max_field_size=8190, @@ -163,13 +163,13 @@ def test_invalid_character( @pytest.mark.skipif(NO_EXTENSIONS, reason="Only tests C parser.") def test_invalid_linebreak( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol, request: pytest.FixtureRequest, ) -> None: parser = HttpRequestParserC( protocol, - loop, + event_loop, 2**16, max_line_size=8190, max_field_size=8190, @@ -230,11 +230,11 @@ def test_bad_headers(parser: HttpRequestParser, hdr: str) -> None: def test_unpaired_surrogate_in_header_py( - loop: asyncio.AbstractEventLoop, protocol: BaseProtocol + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol ) -> None: parser = HttpRequestParserPy( protocol, - loop, + event_loop, 2**16, max_line_size=8190, max_field_size=8190, @@ -258,12 +258,12 @@ def test_content_length_transfer_encoding(parser: HttpRequestParser) -> None: def test_bad_chunked_py( - loop: asyncio.AbstractEventLoop, protocol: BaseProtocol + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol ) -> None: """Test that invalid chunked encoding doesn't allow content-length to be used.""" parser = HttpRequestParserPy( protocol, - loop, + event_loop, 2**16, max_line_size=8190, max_field_size=8190, @@ -280,11 +280,13 @@ def test_bad_chunked_py( "HttpRequestParserC" not in dir(aiohttp.http_parser), reason="C based HTTP parser not available", ) -def test_bad_chunked_c(loop: asyncio.AbstractEventLoop, protocol: BaseProtocol) -> None: +def test_bad_chunked_c( + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol +) -> None: """C parser behaves differently. Maybe we should align them later.""" parser = HttpRequestParserC( protocol, - loop, + event_loop, 2**16, max_line_size=8190, max_field_size=8190, @@ -1178,11 +1180,11 @@ 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, protocol: BaseProtocol + protocol: BaseProtocol, ) -> None: response = HttpResponseParserPy( protocol, - loop, + asyncio.get_running_loop(), 2**16, max_line_size=8190, max_field_size=8190, @@ -1200,11 +1202,11 @@ async def test_http_response_parser_bad_chunked_strict_py( reason="C based HTTP parser not available", ) async def test_http_response_parser_bad_chunked_strict_c( - loop: asyncio.AbstractEventLoop, protocol: BaseProtocol + protocol: BaseProtocol, ) -> None: response = HttpResponseParserC( protocol, - loop, + asyncio.get_running_loop(), 2**16, max_line_size=8190, max_field_size=8190, @@ -1338,11 +1340,11 @@ def test_parse_chunked_payload_chunk_extension(parser: HttpRequestParser) -> Non def test_parse_no_length_or_te_on_post( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol, request_cls: Type[HttpRequestParser], ) -> None: - parser = request_cls(protocol, loop, limit=2**16) + parser = request_cls(protocol, event_loop, limit=2**16) text = b"POST /test HTTP/1.1\r\n\r\n" msg, payload = parser.feed_data(text)[0][0] @@ -1350,11 +1352,11 @@ def test_parse_no_length_or_te_on_post( def test_parse_payload_response_without_body( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol, response_cls: Type[HttpResponseParser], ) -> None: - parser = response_cls(protocol, loop, 2**16, response_with_body=False) + parser = response_cls(protocol, event_loop, 2**16, response_with_body=False) text = b"HTTP/1.1 200 Ok\r\ncontent-length: 10\r\n\r\n" msg, payload = parser.feed_data(text)[0][0] @@ -1532,13 +1534,13 @@ async def test_parse_chunked_payload_split_chunks(response: HttpResponseParser) @pytest.mark.skipif(NO_EXTENSIONS, reason="Only tests C parser.") async def test_parse_chunked_payload_with_lf_in_extensions_c_parser( - loop: asyncio.AbstractEventLoop, protocol: BaseProtocol + protocol: BaseProtocol, ) -> None: """Test the C-parser with a chunked payload that has a LF in the chunk extensions.""" # The C parser will raise a BadHttpMessage from feed_data parser = HttpRequestParserC( protocol, - loop, + asyncio.get_running_loop(), 2**16, max_line_size=8190, max_field_size=8190, @@ -1554,14 +1556,14 @@ async def test_parse_chunked_payload_with_lf_in_extensions_c_parser( async def test_parse_chunked_payload_with_lf_in_extensions_py_parser( - loop: asyncio.AbstractEventLoop, protocol: BaseProtocol + protocol: BaseProtocol, ) -> None: """Test the py-parser with a chunked payload that has a LF in the chunk extensions.""" # The py parser will not raise the BadHttpMessage directly, but instead # it will set the exception on the StreamReader. parser = HttpRequestParserPy( protocol, - loop, + asyncio.get_running_loop(), 2**16, max_line_size=8190, max_field_size=8190, @@ -1649,12 +1651,12 @@ def test_parse_uri_utf8_percent_encoded(parser: HttpRequestParser) -> None: reason="C based HTTP parser not available", ) def test_parse_bad_method_for_c_parser_raises( - loop: asyncio.AbstractEventLoop, protocol: BaseProtocol + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol ) -> None: payload = b"GET1 /test HTTP/1.1\r\n\r\n" parser = HttpRequestParserC( protocol, - loop, + event_loop, 2**16, max_line_size=8190, max_field_size=8190, diff --git a/tests/test_http_writer.py b/tests/test_http_writer.py index 4e0ca4b13ea..2ec0f0820dd 100644 --- a/tests/test_http_writer.py +++ b/tests/test_http_writer.py @@ -56,7 +56,7 @@ def writelines(chunks: Iterable[bytes]) -> None: @pytest.fixture -def protocol(loop: asyncio.AbstractEventLoop, transport: asyncio.Transport) -> Any: # type: ignore[misc] +def protocol(transport: asyncio.Transport) -> Any: # type: ignore[misc] return mock.create_autospec( BaseProtocol, spec_set=True, instance=True, transport=transport ) @@ -85,9 +85,9 @@ def decode_chunked(chunked: Union[bytes, bytearray]) -> bytes: def test_payloadwriter_properties( transport: asyncio.Transport, protocol: BaseProtocol, - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> None: - writer = http.StreamWriter(protocol, loop) + writer = http.StreamWriter(protocol, event_loop) assert writer.protocol == protocol assert writer.transport == transport @@ -95,9 +95,8 @@ def test_payloadwriter_properties( async def test_write_payload_eof( transport: asyncio.Transport, protocol: BaseProtocol, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) await msg.write(b"data1") await msg.write(b"data2") @@ -111,9 +110,8 @@ async def test_write_payload_chunked( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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() @@ -125,9 +123,8 @@ async def test_write_payload_chunked_multiple( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -139,9 +136,8 @@ async def test_write_payload_chunked_multiple( async def test_write_payload_length( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -156,9 +152,8 @@ async def test_write_payload_length( async def test_write_large_payload_deflate_compression_data_in_eof( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write(b"data" * 4096) @@ -183,9 +178,8 @@ async def test_write_large_payload_deflate_compression_data_in_eof( async def test_write_large_payload_deflate_compression_data_in_eof_all_zlib( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write(b"data" * 4096) @@ -217,9 +211,8 @@ async def test_write_large_payload_deflate_compression_data_in_eof_all_zlib( async def test_write_large_payload_deflate_compression_data_in_eof_writelines( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write(b"data" * 4096) @@ -245,9 +238,8 @@ async def test_write_large_payload_deflate_compression_data_in_eof_writelines( async def test_write_large_payload_deflate_compression_data_in_eof_writelines_all_zlib( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") await msg.write(b"data" * 4096) @@ -280,9 +272,8 @@ 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, ) -> 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") @@ -296,9 +287,8 @@ async def test_write_payload_chunked_filter( async def test_write_payload_chunked_filter_multiple_chunks( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -317,10 +307,9 @@ async def test_write_payload_chunked_filter_multiple_chunks( async def test_write_payload_deflate_compression( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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() @@ -335,9 +324,8 @@ async def test_write_payload_deflate_compression( async def test_write_payload_deflate_compression_all_zlib( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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() @@ -352,10 +340,9 @@ async def test_write_payload_deflate_compression_all_zlib( async def test_write_payload_deflate_compression_chunked( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -371,9 +358,8 @@ async def test_write_payload_deflate_compression_chunked( async def test_write_payload_deflate_compression_chunked_all_zlib( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -391,10 +377,9 @@ async def test_write_payload_deflate_compression_chunked_all_zlib( async def test_write_payload_deflate_compression_chunked_writelines( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -412,9 +397,8 @@ async def test_write_payload_deflate_compression_chunked_writelines( async def test_write_payload_deflate_compression_chunked_writelines_all_zlib( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -431,9 +415,8 @@ async def test_write_payload_deflate_and_chunked( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -450,9 +433,8 @@ async def test_write_payload_deflate_and_chunked_all_zlib( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -467,10 +449,9 @@ async def test_write_payload_deflate_and_chunked_all_zlib( async def test_write_payload_deflate_compression_chunked_data_in_eof( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -486,9 +467,8 @@ async def test_write_payload_deflate_compression_chunked_data_in_eof( async def test_write_payload_deflate_compression_chunked_data_in_eof_all_zlib( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -506,10 +486,9 @@ async def test_write_payload_deflate_compression_chunked_data_in_eof_all_zlib( async def test_write_payload_deflate_compression_chunked_data_in_eof_writelines( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -527,9 +506,8 @@ async def test_write_payload_deflate_compression_chunked_data_in_eof_writelines( async def test_write_payload_deflate_compression_chunked_data_in_eof_writelines_all_zlib( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -545,9 +523,8 @@ async def test_write_payload_deflate_compression_chunked_data_in_eof_writelines_ async def test_write_large_payload_deflate_compression_chunked_data_in_eof( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -572,9 +549,8 @@ async def test_write_large_payload_deflate_compression_chunked_data_in_eof( async def test_write_large_payload_deflate_compression_chunked_data_in_eof_all_zlib( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -601,9 +577,8 @@ async def test_write_large_payload_deflate_compression_chunked_data_in_eof_all_z async def test_write_large_payload_deflate_compression_chunked_data_in_eof_writelines( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -630,9 +605,8 @@ async def test_write_large_payload_deflate_compression_chunked_data_in_eof_write async def test_write_large_payload_deflate_compression_chunked_data_in_eof_writelines_all_zlib( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_compression("deflate") msg.enable_chunking() @@ -657,9 +631,8 @@ async def test_write_large_payload_deflate_compression_chunked_data_in_eof_write async def test_write_payload_deflate_compression_chunked_connection_lost( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -676,9 +649,8 @@ async def test_write_payload_deflate_compression_chunked_connection_lost( async def test_write_payload_deflate_compression_chunked_connection_lost_all_zlib( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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") @@ -695,9 +667,8 @@ async def test_write_payload_bytes_memoryview( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) mv = memoryview(b"abcd") @@ -712,9 +683,8 @@ async def test_write_payload_short_ints_memoryview( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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])) @@ -733,9 +703,8 @@ async def test_write_payload_2d_shape_memoryview( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.enable_chunking() mv = memoryview(b"ABCDEF") @@ -752,9 +721,8 @@ async def test_write_payload_slicing_long_memoryview( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) msg.length = 4 mv = memoryview(b"ABCDEF") @@ -770,9 +738,8 @@ async def test_write_payload_slicing_long_memoryview( async def test_write_drain( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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 @@ -785,10 +752,11 @@ async def test_write_drain( async def test_write_calls_callback( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: on_chunk_sent = make_mocked_coro() - msg = http.StreamWriter(protocol, loop, on_chunk_sent=on_chunk_sent) + msg = http.StreamWriter( + protocol, asyncio.get_running_loop(), on_chunk_sent=on_chunk_sent + ) chunk = b"1" await msg.write(chunk) assert on_chunk_sent.called @@ -798,10 +766,11 @@ async def test_write_calls_callback( async def test_write_eof_calls_callback( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: on_chunk_sent = make_mocked_coro() - msg = http.StreamWriter(protocol, loop, on_chunk_sent=on_chunk_sent) + msg = http.StreamWriter( + protocol, asyncio.get_running_loop(), on_chunk_sent=on_chunk_sent + ) chunk = b"1" await msg.write_eof(chunk=chunk) assert on_chunk_sent.called @@ -811,9 +780,8 @@ async def test_write_eof_calls_callback( async def test_write_to_closing_transport( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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] @@ -825,14 +793,13 @@ async def test_write_to_closing_transport( async def test_write_to_closed_transport( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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 @@ -846,9 +813,8 @@ async def test_write_to_closed_transport( async def test_drain( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> None: - msg = http.StreamWriter(protocol, loop) + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) await msg.drain() assert protocol._drain_helper.called # type: ignore[attr-defined] @@ -856,9 +822,8 @@ async def test_drain( async def test_drain_no_transport( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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] @@ -867,9 +832,8 @@ async def test_drain_no_transport( async def test_write_headers_prevents_injection( protocol: BaseProtocol, transport: asyncio.Transport, - loop: asyncio.AbstractEventLoop, ) -> 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): @@ -882,9 +846,8 @@ async def test_write_headers_prevents_injection( async def test_set_eof_after_write_headers( protocol: BaseProtocol, transport: mock.Mock, - loop: asyncio.AbstractEventLoop, ) -> 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"}) await msg.write_headers(status_line, good_headers) diff --git a/tests/test_loop.py b/tests/test_loop.py deleted file mode 100644 index f71a5e6a140..00000000000 --- a/tests/test_loop.py +++ /dev/null @@ -1,60 +0,0 @@ -import asyncio -import platform -import threading - -import pytest - -from aiohttp import web -from aiohttp.test_utils import AioHTTPTestCase, loop_context - - -@pytest.mark.skipif( - platform.system() == "Windows", reason="the test is not valid for Windows" -) -async def test_subprocess_co(loop: asyncio.AbstractEventLoop) -> None: - proc = await asyncio.create_subprocess_shell( - "exit 0", - stdin=asyncio.subprocess.DEVNULL, - stdout=asyncio.subprocess.DEVNULL, - stderr=asyncio.subprocess.DEVNULL, - ) - await proc.wait() - - -class TestCase(AioHTTPTestCase): - on_startup_called: bool - - async def get_application(self) -> web.Application: - app = web.Application() - app.on_startup.append(self.on_startup_hook) - return app - - async def on_startup_hook(self, app: web.Application) -> None: - self.on_startup_called = True - - async def test_on_startup_hook(self) -> None: - self.assertTrue(self.on_startup_called) - - -def test_default_loop(loop: asyncio.AbstractEventLoop) -> None: - assert asyncio.get_event_loop_policy().get_event_loop() is loop - - -def test_setup_loop_non_main_thread() -> None: - child_exc = None - - def target() -> None: - try: - with loop_context() as loop: - assert asyncio.get_event_loop_policy().get_event_loop() is loop - loop.run_until_complete(test_subprocess_co(loop)) - except Exception as exc: - nonlocal child_exc - child_exc = exc - - # Ensures setup_test_loop can be called by pytest-xdist in non-main thread. - t = threading.Thread(target=target) - t.start() - t.join() - - assert child_exc is None diff --git a/tests/test_proxy_functional.py b/tests/test_proxy_functional.py index 8ba37b248c6..de70a97b31c 100644 --- a/tests/test_proxy_functional.py +++ b/tests/test_proxy_functional.py @@ -20,6 +20,7 @@ import proxy import pytest +from pytest_aiohttp import AiohttpRawServer, AiohttpServer from pytest_mock import MockerFixture from yarl import URL @@ -27,7 +28,6 @@ from aiohttp import ClientResponse, web from aiohttp.client import _RequestOptions from aiohttp.client_exceptions import ClientConnectionError -from aiohttp.pytest_plugin import AiohttpRawServer, AiohttpServer ASYNCIO_SUPPORTS_TLS_IN_TLS = sys.version_info >= (3, 11) @@ -140,7 +140,6 @@ async def handler(request: web.Request) -> web.Response: # Filter out the warning from # https://github.com/abhinavsingh/proxy.py/blob/30574fd0414005dfa8792a6e797023e862bdcf43/proxy/common/utils.py#L226 # otherwise this test will fail because the proxy will die with an error. -@pytest.mark.usefixtures("loop") async def test_secure_https_proxy_absolute_path( client_ssl_ctx: ssl.SSLContext, secure_proxy_url: URL, @@ -165,7 +164,6 @@ async def test_secure_https_proxy_absolute_path( @pytest.mark.parametrize("web_server_endpoint_type", ("https",)) -@pytest.mark.usefixtures("loop") @pytest.mark.skipif( ASYNCIO_SUPPORTS_TLS_IN_TLS, reason="asyncio on this python supports TLS in TLS" ) @@ -270,7 +268,6 @@ async def test_uvloop_secure_https_proxy( @pytest.fixture def proxy_test_server( aiohttp_raw_server: AiohttpRawServer, - loop: asyncio.AbstractEventLoop, monkeypatch: pytest.MonkeyPatch, ) -> Callable[[], Awaitable[mock.Mock]]: # Handle all proxy requests and imitate remote server response. @@ -440,7 +437,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" @@ -462,7 +458,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" @@ -486,7 +481,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 @@ -556,7 +550,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() proxy = await proxy_test_server() @@ -656,7 +649,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" @@ -680,7 +672,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" @@ -704,7 +695,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_pytest_plugin.py b/tests/test_pytest_plugin.py deleted file mode 100644 index 348348f673a..00000000000 --- a/tests/test_pytest_plugin.py +++ /dev/null @@ -1,347 +0,0 @@ -import os -import platform -import warnings - -import pytest - -from aiohttp import pytest_plugin - -pytest_plugins: str = "pytester" - -CONFTEST: str = """ -pytest_plugins = 'aiohttp.pytest_plugin' -""" - - -IS_PYPY = platform.python_implementation() == "PyPy" - - -def test_aiohttp_plugin(testdir: pytest.Testdir) -> None: - testdir.makepyfile( - """\ -import pytest -from unittest import mock - -from aiohttp import web - -value = web.AppKey('value', str) - - -async def hello(request): - return web.Response(body=b'Hello, world') - - -async def create_app(): - app = web.Application() - app.router.add_route('GET', '/', hello) - return app - - -async def test_hello(aiohttp_client) -> None: - client = await aiohttp_client(await create_app()) - resp = await client.get('/') - assert resp.status == 200 - text = await resp.text() - assert 'Hello, world' in text - - -async def test_hello_from_app(aiohttp_client) -> None: - app = web.Application() - app.router.add_get('/', hello) - client = await aiohttp_client(app) - resp = await client.get('/') - assert resp.status == 200 - text = await resp.text() - assert 'Hello, world' in text - - -async def test_hello_with_loop(aiohttp_client) -> None: - client = await aiohttp_client(await create_app()) - resp = await client.get('/') - assert resp.status == 200 - text = await resp.text() - assert 'Hello, world' in text - - -async def test_noop() -> None: - pass - - -async def previous(request): - if request.method == 'POST': - with pytest.deprecated_call(): # FIXME: this isn't actually called - request.app[value] = (await request.post())['value'] - return web.Response(body=b'thanks for the data') - else: - v = request.app.get(value, 'unknown') - return web.Response(body='value: {}'.format(v).encode()) - - -def create_stateful_app(): - app = web.Application() - app.router.add_route('*', '/', previous) - return app - - -@pytest.fixture -def cli(loop, aiohttp_client): - return loop.run_until_complete(aiohttp_client(create_stateful_app())) - - -def test_noncoro() -> None: - assert True - - -async def test_failed_to_create_client(aiohttp_client) -> None: - - def make_app(): - raise RuntimeError() - - with pytest.raises(RuntimeError): - await aiohttp_client(make_app()) - - -async def test_custom_port_aiohttp_client(aiohttp_client, aiohttp_unused_port): - port = aiohttp_unused_port() - client = await aiohttp_client(await create_app(), - server_kwargs={'port': port}) - assert client.port == port - resp = await client.get('/') - assert resp.status == 200 - text = await resp.text() - assert 'Hello, world' in text - - -async def test_custom_port_test_server(aiohttp_server, aiohttp_unused_port): - app = await create_app() - port = aiohttp_unused_port() - server = await aiohttp_server(app, port=port) - assert server.port == port -""" - ) - testdir.makeconftest(CONFTEST) - result = testdir.runpytest("-p", "no:sugar", "--aiohttp-loop=pyloop") - result.assert_outcomes(passed=8) - - -def test_warning_checks(testdir: pytest.Testdir) -> None: - testdir.makepyfile( - """\ - -async def foobar(): - return 123 - -async def test_good() -> None: - v = await foobar() - assert v == 123 - -async def test_bad() -> None: - foobar() -""" - ) - testdir.makeconftest(CONFTEST) - result = testdir.runpytest( - "-p", "no:sugar", "-s", "-W", "default", "--aiohttp-loop=pyloop" - ) - expected_outcomes = ( - {"failed": 0, "passed": 2} - if IS_PYPY and bool(os.environ.get("PYTHONASYNCIODEBUG")) - else {"failed": 1, "passed": 1} - ) - # Under PyPy "coroutine 'foobar' was never awaited" does not happen. - result.assert_outcomes(**expected_outcomes) - - -def test_aiohttp_plugin_async_fixture( - testdir: pytest.Testdir, capsys: pytest.CaptureFixture[str] -) -> None: - testdir.makepyfile( - """\ -import pytest - -from aiohttp import web - - -async def hello(request): - return web.Response(body=b'Hello, world') - - -def create_app(): - app = web.Application() - app.router.add_route('GET', '/', hello) - return app - - -@pytest.fixture -async def cli(aiohttp_client, loop): - client = await aiohttp_client(create_app()) - return client - - -@pytest.fixture -async def foo(): - return 42 - - -@pytest.fixture -async def bar(request): - # request should be accessible in async fixtures if needed - return request.function - - -async def test_hello(cli, loop) -> None: - resp = await cli.get('/') - assert resp.status == 200 - - -def test_foo(loop, foo) -> None: - assert foo == 42 - - -def test_foo_without_loop(foo) -> None: - # will raise an error because there is no loop - pass - - -def test_bar(loop, bar) -> None: - assert bar is test_bar -""" - ) - testdir.makeconftest(CONFTEST) - result = testdir.runpytest("-p", "no:sugar", "--aiohttp-loop=pyloop") - result.assert_outcomes(passed=3, errors=1) - result.stdout.fnmatch_lines( - "*Asynchronous fixtures must depend on the 'loop' fixture " - "or be used in tests depending from it." - ) - - -def test_aiohttp_plugin_async_gen_fixture(testdir: pytest.Testdir) -> None: - testdir.makepyfile( - """\ -import pytest -from unittest import mock - -from aiohttp import web - - -canary = mock.Mock() - - -async def hello(request): - return web.Response(body=b'Hello, world') - - -def create_app(): - app = web.Application() - app.router.add_route('GET', '/', hello) - return app - - -@pytest.fixture -async def cli(aiohttp_client, loop): - yield await aiohttp_client(create_app()) - canary() - - -async def test_hello(cli) -> None: - resp = await cli.get('/') - assert resp.status == 200 - - -def test_finalized() -> None: - assert canary.called is True -""" - ) - testdir.makeconftest(CONFTEST) - result = testdir.runpytest("-p", "no:sugar", "--aiohttp-loop=pyloop") - result.assert_outcomes(passed=2) - - -def test_warnings_propagated(recwarn: pytest.WarningsRecorder) -> None: - with pytest_plugin._runtime_warning_context(): - warnings.warn("test warning is propagated") - assert len(recwarn) == 1 - message = recwarn[0].message - assert isinstance(message, UserWarning) - assert message.args == ("test warning is propagated",) - - -def test_aiohttp_client_cls_fixture_custom_client_used(testdir: pytest.Testdir) -> None: - testdir.makepyfile( - """ -import pytest -from aiohttp.web import Application -from aiohttp.test_utils import TestClient - - -class CustomClient(TestClient): - pass - - -@pytest.fixture -def aiohttp_client_cls(): - return CustomClient - - -async def test_hello(aiohttp_client) -> None: - client = await aiohttp_client(Application()) - assert isinstance(client, CustomClient) - -""" - ) - testdir.makeconftest(CONFTEST) - result = testdir.runpytest() - result.assert_outcomes(passed=1) - - -def test_aiohttp_client_cls_fixture_factory(testdir: pytest.Testdir) -> None: - testdir.makeconftest( - CONFTEST - + """ - -def pytest_configure(config): - config.addinivalue_line("markers", "rest: RESTful API tests") - config.addinivalue_line("markers", "graphql: GraphQL API tests") - -""" - ) - testdir.makepyfile( - """ -import pytest -from aiohttp.web import Application -from aiohttp.test_utils import TestClient - - -class RESTfulClient(TestClient): - pass - - -class GraphQLClient(TestClient): - pass - - -@pytest.fixture -def aiohttp_client_cls(request): - if request.node.get_closest_marker('rest') is not None: - return RESTfulClient - elif request.node.get_closest_marker('graphql') is not None: - return GraphQLClient - return TestClient - - -@pytest.mark.rest -async def test_rest(aiohttp_client) -> None: - client = await aiohttp_client(Application()) - assert isinstance(client, RESTfulClient) - - -@pytest.mark.graphql -async def test_graphql(aiohttp_client) -> None: - client = await aiohttp_client(Application()) - assert isinstance(client, GraphQLClient) - -""" - ) - result = testdir.runpytest() - result.assert_outcomes(passed=2) diff --git a/tests/test_resolver.py b/tests/test_resolver.py index b2c8645e835..b1f966011c8 100644 --- a/tests/test_resolver.py +++ b/tests/test_resolver.py @@ -139,9 +139,7 @@ async def fake(*args: Any, **kwargs: Any) -> Tuple[str, int]: @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") -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"] @@ -159,9 +157,7 @@ async def test_async_resolver_positive_ipv4_lookup( @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") -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"] @@ -183,7 +179,7 @@ async def test_async_resolver_positive_link_local_ipv6_lookup( @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") -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) @@ -194,7 +190,7 @@ async def test_async_resolver_multiple_replies(loop: asyncio.AbstractEventLoop) @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") -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() @@ -203,9 +199,7 @@ async def test_async_resolver_negative_lookup(loop: asyncio.AbstractEventLoop) - @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") -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() @@ -308,29 +302,31 @@ 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") -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: +def test_default_loop_for_threaded_resolver() -> None: + async def create_resolver() -> ThreadedResolver: + """Create resolver in async context.""" + return ThreadedResolver() + + loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) - resolver = ThreadedResolver() + resolver = loop.run_until_complete(create_resolver()) assert resolver._loop is loop + loop.close() @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") -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() @@ -346,9 +342,7 @@ async def test_async_resolver_ipv6_positive_lookup( @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") -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") @@ -360,9 +354,7 @@ async def test_async_resolver_error_messages_passed( @pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required") -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([]) @@ -374,7 +366,7 @@ async def test_async_resolver_error_messages_passed_no_hosts( 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_run_app.py b/tests/test_run_app.py index af71612ae19..04565acbfe0 100644 --- a/tests/test_run_app.py +++ b/tests/test_run_app.py @@ -76,32 +76,32 @@ def skip_if_on_windows() -> None: @pytest.fixture def patched_loop( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> Iterator[asyncio.AbstractEventLoop]: server = mock.create_autospec(asyncio.Server, spec_set=True, instance=True) server.wait_closed.return_value = None unix_server = mock.create_autospec(asyncio.Server, spec_set=True, instance=True) unix_server.wait_closed.return_value = None with mock.patch.object( - loop, "create_server", autospec=True, spec_set=True, return_value=server + event_loop, "create_server", autospec=True, spec_set=True, return_value=server ): with mock.patch.object( - loop, + event_loop, "create_unix_server", autospec=True, spec_set=True, return_value=unix_server, ): - asyncio.set_event_loop(loop) - yield loop + asyncio.set_event_loop(event_loop) + yield event_loop -def stopper(loop: asyncio.AbstractEventLoop) -> Callable[[], None]: +def stopper(event_loop: asyncio.AbstractEventLoop) -> Callable[[], None]: def raiser() -> NoReturn: raise KeyboardInterrupt def f(*args: object) -> None: - loop.call_soon(raiser) + event_loop.call_soon(raiser) return f @@ -537,7 +537,9 @@ def test_run_app_custom_backlog(patched_loop: asyncio.AbstractEventLoop) -> None ) -def test_run_app_custom_backlog_unix(patched_loop: asyncio.AbstractEventLoop) -> None: +def test_run_app_custom_backlog_unix( + patched_loop: asyncio.AbstractEventLoop, +) -> None: app = web.Application() web.run_app( app, @@ -591,7 +593,9 @@ def test_run_app_https_unix_socket( @pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="requires UNIX sockets") @skip_if_no_abstract_paths -def test_run_app_abstract_linux_socket(patched_loop: asyncio.AbstractEventLoop) -> None: +def test_run_app_abstract_linux_socket( + patched_loop: asyncio.AbstractEventLoop, +) -> None: sock_path = b"\x00" + uuid4().hex.encode("ascii") app = web.Application() web.run_app( @@ -887,7 +891,9 @@ async def on_startup(app: web.Application) -> None: assert task.cancelled() -def test_run_app_cancels_done_tasks(patched_loop: asyncio.AbstractEventLoop) -> None: +def test_run_app_cancels_done_tasks( + patched_loop: asyncio.AbstractEventLoop, +) -> None: app = web.Application() task = None @@ -906,7 +912,9 @@ async def on_startup(app: web.Application) -> None: assert task.done() -def test_run_app_cancels_failed_tasks(patched_loop: asyncio.AbstractEventLoop) -> None: +def test_run_app_cancels_failed_tasks( + patched_loop: asyncio.AbstractEventLoop, +) -> None: app = web.Application() task = None @@ -996,7 +1004,9 @@ async def init() -> web.Application: assert count == 3 -def test_run_app_raises_exception(patched_loop: asyncio.AbstractEventLoop) -> None: +def test_run_app_raises_exception( + patched_loop: asyncio.AbstractEventLoop, +) -> None: async def context(app: web.Application) -> AsyncIterator[None]: raise RuntimeError("foo") yield # type: ignore[unreachable] # pragma: no cover diff --git a/tests/test_streams.py b/tests/test_streams.py index 4305f892eea..00e2dc5084b 100644 --- a/tests/test_streams.py +++ b/tests/test_streams.py @@ -1132,8 +1132,8 @@ async def test_empty_stream_reader_iter_chunks() -> None: @pytest.fixture -async def buffer(loop: asyncio.AbstractEventLoop) -> streams.DataQueue[bytes]: - return streams.DataQueue(loop) +async def buffer() -> streams.DataQueue[bytes]: + return streams.DataQueue(asyncio.get_running_loop()) class TestDataQueue: diff --git a/tests/test_test_utils.py b/tests/test_test_utils.py index 20f4f2540ec..f3f16b71f7a 100644 --- a/tests/test_test_utils.py +++ b/tests/test_test_utils.py @@ -7,18 +7,17 @@ import pytest from multidict import CIMultiDict, CIMultiDictProxy +from pytest_aiohttp import AiohttpClient from yarl import URL import aiohttp from aiohttp import web -from aiohttp.pytest_plugin import AiohttpClient from aiohttp.test_utils import ( AioHTTPTestCase, RawTestServer, TestClient, TestServer, get_port_socket, - loop_context, make_mocked_request, ) @@ -60,13 +59,6 @@ async def cookie_handler(request: web.Request) -> web.Response: return app -# these exist to test the pytest scenario -@pytest.fixture -def loop() -> Iterator[asyncio.AbstractEventLoop]: - with loop_context() as loop: - yield loop - - @pytest.fixture def app() -> web.Application: return _create_example_app() @@ -74,16 +66,16 @@ def app() -> web.Application: @pytest.fixture def test_client( - loop: asyncio.AbstractEventLoop, app: web.Application + event_loop: asyncio.AbstractEventLoop, app: web.Application ) -> Iterator[_TestClient]: async def make_client() -> TestClient[web.Request, web.Application]: return TestClient(TestServer(app)) - client = loop.run_until_complete(make_client()) + client = event_loop.run_until_complete(make_client()) - loop.run_until_complete(client.start_server()) + event_loop.run_until_complete(client.start_server()) yield client - loop.run_until_complete(client.close()) + event_loop.run_until_complete(client.close()) async def test_aiohttp_client_close_is_idempotent() -> None: @@ -95,6 +87,21 @@ async def test_aiohttp_client_close_is_idempotent() -> None: await client.close() +class TestCaseStartup(AioHTTPTestCase): + on_startup_called: bool + + async def get_application(self) -> web.Application: + app = web.Application() + app.on_startup.append(self.on_startup_hook) + return app + + async def on_startup_hook(self, app: web.Application) -> None: + self.on_startup_called = True + + async def test_on_startup_hook(self) -> None: + self.assertTrue(self.on_startup_called) + + class TestAioHTTPTestCase(AioHTTPTestCase): async def get_application(self) -> web.Application: return _create_example_app() @@ -121,19 +128,19 @@ async def test_get_route() -> None: await test_get_route() -def test_get_route(loop: asyncio.AbstractEventLoop, test_client: _TestClient) -> None: +def test_get_route( + event_loop: asyncio.AbstractEventLoop, test_client: _TestClient +) -> None: async def test_get_route() -> None: resp = await test_client.request("GET", "/") assert resp.status == 200 text = await resp.text() assert _hello_world_str == text - loop.run_until_complete(test_get_route()) + event_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() @@ -144,9 +151,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) @@ -157,18 +162,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 @@ -268,7 +269,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() @@ -287,9 +288,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 @@ -300,9 +299,7 @@ async def test_server_make_url_yarl_compatibility( make_url(URL("http://foo.com")) -def test_testcase_no_app( - testdir: pytest.Testdir, loop: asyncio.AbstractEventLoop -) -> None: +def test_testcase_no_app(testdir: pytest.Testdir) -> None: testdir.makepyfile( """ from aiohttp.test_utils import AioHTTPTestCase @@ -338,9 +335,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: @@ -351,7 +346,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: @@ -362,9 +357,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] @@ -387,9 +380,8 @@ 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: + loop = asyncio.get_running_loop() app = _create_example_app() server = TestServer(app, host=hostname, loop=loop) async with server: @@ -399,8 +391,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 01eb686fd3c..69571c161fe 100644 --- a/tests/test_urldispatch.py +++ b/tests/test_urldispatch.py @@ -1172,17 +1172,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_app.py b/tests/test_web_app.py index 62d69efb528..e4cfdc4a792 100644 --- a/tests/test_web_app.py +++ b/tests/test_web_app.py @@ -3,9 +3,9 @@ from unittest import mock import pytest +from pytest_aiohttp import AiohttpClient from aiohttp import log, web -from aiohttp.pytest_plugin import AiohttpClient from aiohttp.test_utils import make_mocked_coro from aiohttp.typedefs import Handler diff --git a/tests/test_web_exceptions.py b/tests/test_web_exceptions.py index c7e156ad875..89cf8110e13 100644 --- a/tests/test_web_exceptions.py +++ b/tests/test_web_exceptions.py @@ -4,10 +4,10 @@ from typing import Mapping, NoReturn import pytest +from pytest_aiohttp import AiohttpClient from yarl import URL from aiohttp import web -from aiohttp.pytest_plugin import AiohttpClient def test_all_http_exceptions_exported() -> None: diff --git a/tests/test_web_functional.py b/tests/test_web_functional.py index ffa27ec8acf..aedd3301c3d 100644 --- a/tests/test_web_functional.py +++ b/tests/test_web_functional.py @@ -19,6 +19,7 @@ import pytest from multidict import CIMultiDictProxy, MultiDict +from pytest_aiohttp import AiohttpClient, AiohttpServer from pytest_mock import MockerFixture from yarl import URL @@ -35,7 +36,6 @@ from aiohttp.abc import AbstractResolver, ResolveResult from aiohttp.compression_utils import ZLibBackend, ZLibCompressObjProtocol from aiohttp.hdrs import CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING -from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer from aiohttp.test_utils import make_mocked_coro from aiohttp.typedefs import Handler, Middleware from aiohttp.web_protocol import RequestHandler diff --git a/tests/test_web_log.py b/tests/test_web_log.py index 6456735de4a..33e73d6ecdf 100644 --- a/tests/test_web_log.py +++ b/tests/test_web_log.py @@ -7,11 +7,11 @@ from unittest import mock import pytest +from pytest_aiohttp import AiohttpClient, AiohttpRawServer, AiohttpServer import aiohttp from aiohttp import web from aiohttp.abc import AbstractAccessLogger, AbstractAsyncAccessLogger -from aiohttp.pytest_plugin import AiohttpClient, AiohttpRawServer, AiohttpServer from aiohttp.test_utils import make_mocked_request from aiohttp.typedefs import Handler from aiohttp.web_log import AccessLogger diff --git a/tests/test_web_middleware.py b/tests/test_web_middleware.py index 5b8f1c78166..43a6fed800e 100644 --- a/tests/test_web_middleware.py +++ b/tests/test_web_middleware.py @@ -2,10 +2,10 @@ from typing import Awaitable, Callable, Iterable, NoReturn import pytest +from pytest_aiohttp import AiohttpClient from yarl import URL from aiohttp import web, web_app -from aiohttp.pytest_plugin import AiohttpClient from aiohttp.test_utils import TestClient from aiohttp.typedefs import Handler, Middleware @@ -14,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") @@ -42,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") @@ -66,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") @@ -115,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") @@ -165,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") @@ -440,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") @@ -470,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") @@ -498,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_request.py b/tests/test_web_request.py index 932e3efd02d..99244d4fd28 100644 --- a/tests/test_web_request.py +++ b/tests/test_web_request.py @@ -9,12 +9,12 @@ import pytest from multidict import CIMultiDict, CIMultiDictProxy, MultiDict +from pytest_aiohttp import AiohttpClient from yarl import URL from aiohttp import ETag, HttpVersion, web from aiohttp.base_protocol import BaseProtocol from aiohttp.http_parser import RawRequestMessage -from aiohttp.pytest_plugin import AiohttpClient from aiohttp.streams import StreamReader from aiohttp.test_utils import make_mocked_request diff --git a/tests/test_web_runner.py b/tests/test_web_runner.py index 8da4867372a..2c395be75bc 100644 --- a/tests/test_web_runner.py +++ b/tests/test_web_runner.py @@ -23,9 +23,9 @@ def app() -> web.Application: @pytest.fixture def make_runner( - loop: asyncio.AbstractEventLoop, app: web.Application + event_loop: asyncio.AbstractEventLoop, app: web.Application ) -> Iterator[_RunnerMaker]: - asyncio.set_event_loop(loop) + asyncio.set_event_loop(event_loop) runners = [] def go(handle_signals: bool = False, **kwargs: Any) -> web.AppRunner: @@ -35,7 +35,7 @@ def go(handle_signals: bool = False, **kwargs: Any) -> web.AppRunner: yield go for runner in runners: - loop.run_until_complete(runner.cleanup()) + event_loop.run_until_complete(runner.cleanup()) async def test_site_for_nonfrozen_app(make_runner: _RunnerMaker) -> None: @@ -231,7 +231,7 @@ async def test_named_pipe_runner_wrong_loop( platform.system() != "Windows", reason="Proactor Event loop present only in Windows" ) async def test_named_pipe_runner_proactor_loop( - proactor_loop: asyncio.AbstractEventLoop, app: web.Application, pipe_name: str + proactor_event_loop: asyncio.AbstractEventLoop, app: web.Application, pipe_name: str ) -> None: runner = web.AppRunner(app) await runner.setup() diff --git a/tests/test_web_sendfile.py b/tests/test_web_sendfile.py index 3d919f44c1e..2d09da22083 100644 --- a/tests/test_web_sendfile.py +++ b/tests/test_web_sendfile.py @@ -11,7 +11,7 @@ def test_using_gzip_if_header_present_and_file_available( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> None: request = make_mocked_request( "GET", @@ -33,14 +33,14 @@ def test_using_gzip_if_header_present_and_file_available( file_sender._path = filepath file_sender._sendfile = make_mocked_coro(None) # type: ignore[method-assign] - loop.run_until_complete(file_sender.prepare(request)) + event_loop.run_until_complete(file_sender.prepare(request)) assert not filepath.open.called assert gz_filepath.open.called def test_gzip_if_header_not_present_and_file_available( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> None: request = make_mocked_request("GET", "http://python.org/logo.png", headers={}) @@ -60,14 +60,14 @@ def test_gzip_if_header_not_present_and_file_available( file_sender._path = filepath file_sender._sendfile = make_mocked_coro(None) # type: ignore[method-assign] - loop.run_until_complete(file_sender.prepare(request)) + event_loop.run_until_complete(file_sender.prepare(request)) assert filepath.open.called assert not gz_filepath.open.called def test_gzip_if_header_not_present_and_file_not_available( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> None: request = make_mocked_request("GET", "http://python.org/logo.png", headers={}) @@ -85,14 +85,14 @@ def test_gzip_if_header_not_present_and_file_not_available( file_sender._path = filepath file_sender._sendfile = make_mocked_coro(None) # type: ignore[method-assign] - loop.run_until_complete(file_sender.prepare(request)) + event_loop.run_until_complete(file_sender.prepare(request)) assert filepath.open.called assert not gz_filepath.open.called def test_gzip_if_header_present_and_file_not_available( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> None: request = make_mocked_request( "GET", "http://python.org/logo.png", headers={hdrs.ACCEPT_ENCODING: "gzip"} @@ -112,13 +112,13 @@ def test_gzip_if_header_present_and_file_not_available( file_sender._path = filepath file_sender._sendfile = make_mocked_coro(None) # type: ignore[method-assign] - loop.run_until_complete(file_sender.prepare(request)) + event_loop.run_until_complete(file_sender.prepare(request)) assert filepath.open.called assert not gz_filepath.open.called -def test_status_controlled_by_user(loop: asyncio.AbstractEventLoop) -> None: +def test_status_controlled_by_user(event_loop: asyncio.AbstractEventLoop) -> None: request = make_mocked_request("GET", "http://python.org/logo.png", headers={}) filepath = mock.create_autospec(Path, spec_set=True) @@ -131,6 +131,6 @@ def test_status_controlled_by_user(loop: asyncio.AbstractEventLoop) -> None: file_sender._path = filepath file_sender._sendfile = make_mocked_coro(None) # type: ignore[method-assign] - loop.run_until_complete(file_sender.prepare(request)) + event_loop.run_until_complete(file_sender.prepare(request)) assert file_sender._status == 203 diff --git a/tests/test_web_sendfile_functional.py b/tests/test_web_sendfile_functional.py index eaef4930d09..274d011cd4d 100644 --- a/tests/test_web_sendfile_functional.py +++ b/tests/test_web_sendfile_functional.py @@ -8,11 +8,11 @@ import pytest from _pytest.fixtures import SubRequest +from pytest_aiohttp import AiohttpClient, AiohttpServer import aiohttp from aiohttp import web from aiohttp.compression_utils import ZLibBackend -from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer from aiohttp.typedefs import PathLike try: @@ -61,19 +61,21 @@ def hello_txt( @pytest.fixture def loop_with_mocked_native_sendfile( - loop: asyncio.AbstractEventLoop, + event_loop: asyncio.AbstractEventLoop, ) -> Iterator[asyncio.AbstractEventLoop]: def sendfile(transport: object, fobj: object, offset: int, count: int) -> NoReturn: if count == 0: raise ValueError("count must be a positive integer (got 0)") raise NotImplementedError - with mock.patch.object(loop, "sendfile", sendfile): - yield loop + with mock.patch.object(event_loop, "sendfile", sendfile): + yield event_loop @pytest.fixture(params=["sendfile", "no_sendfile"], ids=["sendfile", "no_sendfile"]) -def sender(request: SubRequest, loop: asyncio.AbstractEventLoop) -> Iterator[_Sender]: +def sender( + request: SubRequest, event_loop: asyncio.AbstractEventLoop +) -> Iterator[_Sender]: sendfile_mock = None def maker(path: PathLike, chunk_size: int = 256 * 1024) -> web.FileResponse: @@ -85,7 +87,7 @@ def maker(path: PathLike, chunk_size: int = 256 * 1024) -> web.FileResponse: if request.param == "no_sendfile": with mock.patch.object( - loop, + event_loop, "sendfile", autospec=True, spec_set=True, diff --git a/tests/test_web_server.py b/tests/test_web_server.py index d4a678468ea..bd26c6c9238 100644 --- a/tests/test_web_server.py +++ b/tests/test_web_server.py @@ -5,10 +5,10 @@ from unittest import mock import pytest +from pytest_aiohttp import AiohttpClient, AiohttpRawServer from aiohttp import client, web from aiohttp.http_exceptions import BadHttpMethod, BadStatusLine -from aiohttp.pytest_plugin import AiohttpClient, AiohttpRawServer async def test_simple_server( @@ -46,10 +46,9 @@ 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, ) -> None: # disable debug mode not to print traceback - loop.set_debug(False) + asyncio.get_running_loop().set_debug(False) exc = RuntimeError("custom runtime error") @@ -75,14 +74,13 @@ 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, ) -> 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) @@ -122,14 +120,13 @@ 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, ) -> 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) @@ -153,7 +150,6 @@ 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, ) -> None: exc = BadHttpMethod(b"\x16\x03\x03\x01F\x01".decode(), "error") request_count = 0 @@ -165,7 +161,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) @@ -186,14 +182,13 @@ 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, ) -> 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) @@ -213,7 +208,7 @@ async def handler(request: web.BaseRequest) -> NoReturn: async def test_raw_server_handler_timeout( aiohttp_raw_server: AiohttpRawServer, aiohttp_client: AiohttpClient ) -> None: - loop = asyncio.get_event_loop() + loop = asyncio.get_running_loop() loop.set_debug(True) exc = asyncio.TimeoutError("error") @@ -236,7 +231,7 @@ async def test_raw_server_do_not_swallow_exceptions( async def handler(request: web.BaseRequest) -> NoReturn: raise asyncio.CancelledError() - 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) @@ -257,7 +252,7 @@ class UnexpectedException(BaseException): async def handler(request: web.BaseRequest) -> NoReturn: raise UnexpectedException() - loop = asyncio.get_event_loop() + loop = asyncio.get_running_loop() loop.set_debug(True) server = await aiohttp_raw_server(handler) cli = await aiohttp_client(server) @@ -277,7 +272,7 @@ async def handler(request: web.BaseRequest) -> MyResponse: resp = MyResponse(text=str(request.rel_url)) return resp - 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) @@ -298,7 +293,7 @@ async def test_raw_server_not_http_exception_debug( 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) @@ -318,10 +313,9 @@ async def handler(request: web.BaseRequest) -> NoReturn: async def test_raw_server_html_exception( aiohttp_raw_server: AiohttpRawServer, aiohttp_client: AiohttpClient, - loop: asyncio.AbstractEventLoop, ) -> None: # disable debug mode not to print traceback - loop.set_debug(False) + asyncio.get_running_loop().set_debug(False) exc = RuntimeError("custom runtime error") @@ -356,7 +350,7 @@ async def test_raw_server_html_exception_debug( 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) diff --git a/tests/test_web_urldispatcher.py b/tests/test_web_urldispatcher.py index f06022e3ec4..8fdc51e7d55 100644 --- a/tests/test_web_urldispatcher.py +++ b/tests/test_web_urldispatcher.py @@ -9,9 +9,9 @@ import pytest import yarl +from pytest_aiohttp import AiohttpClient from aiohttp import web -from aiohttp.pytest_plugin import AiohttpClient from aiohttp.web_urldispatcher import Resource, SystemRoute diff --git a/tests/test_web_websocket.py b/tests/test_web_websocket.py index 139d5fa073e..3d0ddedda56 100644 --- a/tests/test_web_websocket.py +++ b/tests/test_web_websocket.py @@ -27,7 +27,7 @@ def __call__( @pytest.fixture -def app(loop: asyncio.AbstractEventLoop) -> web.Application: +def app(event_loop: asyncio.AbstractEventLoop) -> 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() @@ -412,9 +412,8 @@ 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: + loop = asyncio.get_running_loop() req = make_request("GET", "/") ws = web.WebSocketResponse() await ws.prepare(req) @@ -433,9 +432,8 @@ 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: + loop = asyncio.get_running_loop() req = make_request("GET", "/") ws = web.WebSocketResponse() await ws.prepare(req) @@ -457,9 +455,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) @@ -468,7 +464,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) @@ -479,9 +475,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) @@ -491,7 +485,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) @@ -509,9 +503,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) @@ -520,7 +512,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) @@ -535,9 +527,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) @@ -545,7 +535,7 @@ async def test_receive_timeouterror( assert len(req.transport.close.mock_calls) == 0 # type: ignore[attr-defined] ws._reader = mock.Mock() - res = loop.create_future() + res = asyncio.get_running_loop().create_future() res.set_exception(asyncio.TimeoutError()) ws._reader.read = make_mocked_coro(res) diff --git a/tests/test_web_websocket_functional.py b/tests/test_web_websocket_functional.py index 6bdd5808362..6ff0034157a 100644 --- a/tests/test_web_websocket_functional.py +++ b/tests/test_web_websocket_functional.py @@ -8,16 +8,14 @@ from unittest import mock import pytest +from pytest_aiohttp import AiohttpClient, AiohttpServer import aiohttp from aiohttp import WSServerHandshakeError, web from aiohttp.http import WSCloseCode, WSMsgType -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) @@ -31,9 +29,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) @@ -62,9 +58,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: assert resp.data == expected_value -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) @@ -90,9 +84,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: assert "ValueError was raised" in data -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) @@ -115,9 +107,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: assert data["test"] == expected_value -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) @@ -142,10 +132,8 @@ async def handler(request: web.Request) -> web.WebSocketResponse: assert resp.data == expected_value -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() @@ -177,10 +165,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() @@ -213,10 +199,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() @@ -250,10 +234,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: @@ -294,9 +276,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: @@ -334,9 +314,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: @@ -378,9 +356,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: Optional[web.WebSocketResponse] = None async def handler(request: web.Request) -> web.WebSocketResponse: @@ -409,10 +385,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() @@ -440,10 +414,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() @@ -468,10 +440,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() @@ -495,10 +465,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) @@ -531,10 +499,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() @@ -557,10 +523,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")) @@ -580,10 +544,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")) @@ -604,10 +566,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")) @@ -639,9 +599,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")) @@ -669,9 +629,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: @@ -697,9 +655,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: @@ -725,9 +681,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) @@ -747,9 +701,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) @@ -767,9 +719,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 @@ -811,9 +761,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 @@ -846,7 +794,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.""" @@ -875,7 +823,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.""" @@ -902,10 +850,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() @@ -935,10 +881,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() @@ -972,9 +916,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): @@ -1001,9 +943,7 @@ async def handler(request: web.Request) -> web.StreamResponse: assert data == "OK" -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) @@ -1022,9 +962,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse: await ws.receive_str() -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) @@ -1042,9 +980,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}) @@ -1070,9 +1006,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) @@ -1115,8 +1051,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() diff --git a/tests/test_websocket_data_queue.py b/tests/test_websocket_data_queue.py index 96810df0a6d..9c8992d76e9 100644 --- a/tests/test_websocket_data_queue.py +++ b/tests/test_websocket_data_queue.py @@ -15,9 +15,9 @@ def protocol() -> BaseProtocol: @pytest.fixture def buffer( - loop: asyncio.AbstractEventLoop, protocol: BaseProtocol + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol ) -> WebSocketDataQueue: - return WebSocketDataQueue(protocol, limit=1, loop=loop) + return WebSocketDataQueue(protocol, limit=1, loop=event_loop) class TestWebSocketDataQueue: diff --git a/tests/test_websocket_parser.py b/tests/test_websocket_parser.py index 808cac3380a..23f45bd5e59 100644 --- a/tests/test_websocket_parser.py +++ b/tests/test_websocket_parser.py @@ -113,23 +113,23 @@ def build_close_frame( @pytest.fixture() -def protocol(loop: asyncio.AbstractEventLoop) -> BaseProtocol: +def protocol(event_loop: asyncio.AbstractEventLoop) -> BaseProtocol: transport = mock.Mock(spec_set=asyncio.Transport) - protocol = BaseProtocol(loop) + protocol = BaseProtocol(event_loop) protocol.connection_made(transport) return protocol @pytest.fixture() -def out(loop: asyncio.AbstractEventLoop) -> WebSocketDataQueue: - return WebSocketDataQueue(mock.Mock(_reading_paused=False), 2**16, loop=loop) +def out(event_loop: asyncio.AbstractEventLoop) -> WebSocketDataQueue: + return WebSocketDataQueue(mock.Mock(_reading_paused=False), 2**16, loop=event_loop) @pytest.fixture() def out_low_limit( - loop: asyncio.AbstractEventLoop, protocol: BaseProtocol + event_loop: asyncio.AbstractEventLoop, protocol: BaseProtocol ) -> WebSocketDataQueue: - return WebSocketDataQueue(protocol, 16, loop=loop) + return WebSocketDataQueue(protocol, 16, loop=event_loop) @pytest.fixture() diff --git a/tests/test_worker.py b/tests/test_worker.py index afaf9814e44..2a29c20476a 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -53,9 +53,9 @@ class UvloopWorker(BaseTestWorker, base_worker.GunicornUVLoopWebWorker): @pytest.fixture(params=PARAMS) def worker( - request: SubRequest, loop: asyncio.AbstractEventLoop + request: SubRequest, event_loop: asyncio.AbstractEventLoop ) -> base_worker.GunicornWebWorker: - asyncio.set_event_loop(loop) + asyncio.set_event_loop(event_loop) ret = request.param() ret.notify = mock.Mock() return ret # type: ignore[no-any-return] @@ -73,7 +73,7 @@ def test_init_process(worker: base_worker.GunicornWebWorker) -> None: def test_run( - worker: base_worker.GunicornWebWorker, loop: asyncio.AbstractEventLoop + worker: base_worker.GunicornWebWorker, event_loop: asyncio.AbstractEventLoop ) -> None: worker.log = mock.Mock() worker.cfg = mock.Mock() @@ -82,15 +82,15 @@ def test_run( worker.cfg.graceful_timeout = 100 worker.sockets = [] - worker.loop = loop + worker.loop = event_loop with pytest.raises(SystemExit): worker.run() worker.log.exception.assert_not_called() - assert loop.is_closed() + assert event_loop.is_closed() def test_run_async_factory( - worker: base_worker.GunicornWebWorker, loop: asyncio.AbstractEventLoop + worker: base_worker.GunicornWebWorker, event_loop: asyncio.AbstractEventLoop ) -> None: worker.log = mock.Mock() worker.cfg = mock.Mock() @@ -105,28 +105,28 @@ async def make_app() -> web.Application: worker.wsgi = make_app - worker.loop = loop + worker.loop = event_loop worker.alive = False with pytest.raises(SystemExit): worker.run() worker.log.exception.assert_not_called() - assert loop.is_closed() + assert event_loop.is_closed() def test_run_not_app( - worker: base_worker.GunicornWebWorker, loop: asyncio.AbstractEventLoop + worker: base_worker.GunicornWebWorker, event_loop: asyncio.AbstractEventLoop ) -> None: worker.log = mock.Mock() worker.cfg = mock.Mock() worker.cfg.access_log_format = ACCEPTABLE_LOG_FORMAT - worker.loop = loop + worker.loop = event_loop worker.wsgi = "not-app" worker.alive = False with pytest.raises(SystemExit): worker.run() worker.log.exception.assert_called_with("Exception in gunicorn worker") - assert loop.is_closed() + assert event_loop.is_closed() def test_handle_abort(worker: base_worker.GunicornWebWorker) -> None: @@ -205,7 +205,6 @@ 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, ) -> None: worker.ppid = 0 @@ -213,7 +212,7 @@ async def test__run_ok_parent_changed( 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 +224,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