Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backport tests 3.10 #8341

Draft
wants to merge 1 commit into
base: 3.10
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 35 additions & 1 deletion tests/test_client_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import ssl
import sys
import time
from typing import Any, AsyncIterator
from typing import Any, AsyncIterator, Type
from unittest import mock

import pytest
Expand All @@ -21,6 +21,7 @@
from aiohttp import Fingerprint, ServerFingerprintMismatch, hdrs, web
from aiohttp.abc import AbstractResolver
from aiohttp.client_exceptions import (
InvalidURL,
InvalidUrlClientError,
InvalidUrlRedirectClientError,
NonHttpUrlClientError,
Expand Down Expand Up @@ -3623,3 +3624,36 @@ async def not_ok_handler(request):
"/ok", timeout=aiohttp.ClientTimeout(total=0.01)
) as resp_ok:
assert 200 == resp_ok.status


async def test_request_with_wrong_ssl_type(aiohttp_client: AiohttpClient) -> None:
app = web.Application()
session = await aiohttp_client(app)

with pytest.raises(TypeError, match="ssl should be SSLContext, Fingerprint, .*"):
await session.get("/", ssl=42) # type: ignore[arg-type]


@pytest.mark.parametrize(
("value", "exc_type"),
[(42, TypeError), ("InvalidUrl", InvalidURL)],
)
async def test_request_with_wrong_proxy(
aiohttp_client: AiohttpClient, value: Any, exc_type: Type[Exception]
) -> None:
app = web.Application()
session = await aiohttp_client(app)

with pytest.raises(exc_type):
await session.get("/", proxy=value) # type: ignore[arg-type]


async def test_raise_for_status_is_none(aiohttp_client: AiohttpClient) -> None:
async def handler(_: web.Request) -> web.Response:
return web.Response()

app = web.Application()
app.router.add_get("/", handler)
session = await aiohttp_client(app, raise_for_status=None) # type: ignore[arg-type]

await session.get("/")
21 changes: 21 additions & 0 deletions tests/test_client_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from http.cookies import SimpleCookie
from typing import Any, List
from unittest import mock
from uuid import uuid4

import pytest
from multidict import CIMultiDict, MultiDict
Expand Down Expand Up @@ -895,3 +896,23 @@ async def test_instantiation_with_invalid_timeout_value(loop):
ClientSession(timeout=1)
# should not have "Unclosed client session" warning
assert not logs


@pytest.mark.parametrize(
("outer_name", "inner_name"),
[
("skip_auto_headers", "_skip_auto_headers"),
("auth", "_default_auth"),
("json_serialize", "_json_serialize"),
("connector_owner", "_connector_owner"),
("raise_for_status", "_raise_for_status"),
("trust_env", "_trust_env"),
("trace_configs", "_trace_configs"),
],
)
async def test_properties(
session: ClientSession, outer_name: str, inner_name: str
) -> None:
value = uuid4()
setattr(session, inner_name, value)
assert value == getattr(session, outer_name)
9 changes: 9 additions & 0 deletions tests/test_client_ws_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import aiohttp
from aiohttp import hdrs, web
from aiohttp.http import WSCloseCode
from aiohttp.pytest_plugin import AiohttpClient

if sys.version_info >= (3, 11):
import asyncio as async_timeout
Expand Down Expand Up @@ -835,3 +836,11 @@ async def handler(request):
assert "answer" == msg.data

await resp.close()


async def test_ws_connect_with_wrong_ssl_type(aiohttp_client: AiohttpClient) -> None:
app = web.Application()
session = await aiohttp_client(app)

with pytest.raises(TypeError, match="ssl should be SSLContext, .*"):
await session.ws_connect("/", ssl=42)
2 changes: 1 addition & 1 deletion tests/test_test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ async def test_test_client_props(loop) -> None:

async def test_test_client_raw_server_props(loop) -> None:
async def hello(request):
return web.Response(body=_hello_world_bytes)
return web.Response() # pragma: no cover

client = _TestClient(_RawTestServer(hello, host="127.0.0.1", loop=loop), loop=loop)
assert client.host == "127.0.0.1"
Expand Down
2 changes: 1 addition & 1 deletion tests/test_web_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ def test_app_run_middlewares() -> None:

@web.middleware
async def middleware(request: web.Request, handler: Handler) -> web.StreamResponse:
return await handler(request)
return await handler(request) # pragma: no cover

root = web.Application(middlewares=[middleware])
sub = web.Application()
Expand Down
118 changes: 94 additions & 24 deletions tests/test_web_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import pytest

from aiohttp import web
from aiohttp.abc import AbstractAccessLogger
from aiohttp.test_utils import get_unused_port_socket


Expand All @@ -16,7 +17,7 @@ def app():


@pytest.fixture
def make_runner(loop, app):
def make_runner(loop: Any, app: Any):
asyncio.set_event_loop(loop)
runners = []

Expand All @@ -30,7 +31,7 @@ def go(**kwargs):
loop.run_until_complete(runner.cleanup())


async def test_site_for_nonfrozen_app(make_runner) -> None:
async def test_site_for_nonfrozen_app(make_runner: Any) -> None:
runner = make_runner()
with pytest.raises(RuntimeError):
web.TCPSite(runner)
Expand All @@ -40,7 +41,7 @@ async def test_site_for_nonfrozen_app(make_runner) -> None:
@pytest.mark.skipif(
platform.system() == "Windows", reason="the test is not valid for Windows"
)
async def test_runner_setup_handle_signals(make_runner) -> None:
async def test_runner_setup_handle_signals(make_runner: Any) -> None:
runner = make_runner(handle_signals=True)
await runner.setup()
assert signal.getsignal(signal.SIGTERM) is not signal.SIG_DFL
Expand All @@ -51,15 +52,15 @@ async def test_runner_setup_handle_signals(make_runner) -> None:
@pytest.mark.skipif(
platform.system() == "Windows", reason="the test is not valid for Windows"
)
async def test_runner_setup_without_signal_handling(make_runner) -> None:
async def test_runner_setup_without_signal_handling(make_runner: Any) -> None:
runner = make_runner(handle_signals=False)
await runner.setup()
assert signal.getsignal(signal.SIGTERM) is signal.SIG_DFL
await runner.cleanup()
assert signal.getsignal(signal.SIGTERM) is signal.SIG_DFL


async def test_site_double_added(make_runner) -> None:
async def test_site_double_added(make_runner: Any) -> None:
_sock = get_unused_port_socket("127.0.0.1")
runner = make_runner()
await runner.setup()
Expand All @@ -71,7 +72,7 @@ async def test_site_double_added(make_runner) -> None:
assert len(runner.sites) == 1


async def test_site_stop_not_started(make_runner) -> None:
async def test_site_stop_not_started(make_runner: Any) -> None:
runner = make_runner()
await runner.setup()
site = web.TCPSite(runner)
Expand All @@ -81,21 +82,21 @@ async def test_site_stop_not_started(make_runner) -> None:
assert len(runner.sites) == 0


async def test_custom_log_format(make_runner) -> None:
async def test_custom_log_format(make_runner: Any) -> None:
runner = make_runner(access_log_format="abc")
await runner.setup()
assert runner.server._kwargs["access_log_format"] == "abc"


async def test_unreg_site(make_runner) -> None:
async def test_unreg_site(make_runner: Any) -> None:
runner = make_runner()
await runner.setup()
site = web.TCPSite(runner)
with pytest.raises(RuntimeError):
runner._unreg_site(site)


async def test_app_property(make_runner, app) -> None:
async def test_app_property(make_runner: Any, app: Any) -> None:
runner = make_runner()
assert runner.app is app

Expand All @@ -105,7 +106,83 @@ def test_non_app() -> None:
web.AppRunner(object())


async def test_addresses(make_runner, unix_sockname) -> None:
def test_app_handler_args() -> None:
app = web.Application(handler_args={"test": True})
runner = web.AppRunner(app)
assert runner._kwargs == {"access_log_class": web.AccessLogger, "test": True}


async def test_app_handler_args_failure() -> None:
app = web.Application(handler_args={"unknown_parameter": 5})
runner = web.AppRunner(app)
await runner.setup()
assert runner._server
rh = runner._server()
assert rh._timeout_ceil_threshold == 5
await runner.cleanup()
assert app


@pytest.mark.parametrize(
("value", "expected"),
(
(2, 2),
(None, 5),
("2", 2),
),
)
async def test_app_handler_args_ceil_threshold(value: Any, expected: Any) -> None:
app = web.Application(handler_args={"timeout_ceil_threshold": value})
runner = web.AppRunner(app)
await runner.setup()
assert runner._server
rh = runner._server()
assert rh._timeout_ceil_threshold == expected
await runner.cleanup()
assert app


async def test_app_make_handler_access_log_class_bad_type1() -> None:
class Logger:
pass

app = web.Application()

with pytest.raises(TypeError):
web.AppRunner(app, access_log_class=Logger)


async def test_app_make_handler_access_log_class_bad_type2() -> None:
class Logger:
pass

app = web.Application(handler_args={"access_log_class": Logger})

with pytest.raises(TypeError):
web.AppRunner(app)


async def test_app_make_handler_access_log_class1() -> None:
class Logger(AbstractAccessLogger):
def log(self, request, response, time):
"""Pass log method."""

app = web.Application()
runner = web.AppRunner(app, access_log_class=Logger)
assert runner._kwargs["access_log_class"] is Logger


async def test_app_make_handler_access_log_class2() -> None:
class Logger(AbstractAccessLogger):
def log(self, request, response, time):
"""Pass log method."""

app = web.Application(handler_args={"access_log_class": Logger})
runner = web.AppRunner(app)
assert runner._kwargs["access_log_class"] is Logger


async def test_addresses(make_runner: Any, unix_sockname: Any) -> None:
_sock = get_unused_port_socket("127.0.0.1")
runner = make_runner()
await runner.setup()
Expand All @@ -121,7 +198,9 @@ async def test_addresses(make_runner, unix_sockname) -> None:
@pytest.mark.skipif(
platform.system() != "Windows", reason="Proactor Event loop present only in Windows"
)
async def test_named_pipe_runner_wrong_loop(app, selector_loop, pipe_name) -> None:
async def test_named_pipe_runner_wrong_loop(
app: Any, selector_loop: Any, pipe_name: Any
) -> None:
runner = web.AppRunner(app)
await runner.setup()
with pytest.raises(RuntimeError):
Expand All @@ -131,15 +210,17 @@ async def test_named_pipe_runner_wrong_loop(app, selector_loop, pipe_name) -> No
@pytest.mark.skipif(
platform.system() != "Windows", reason="Proactor Event loop present only in Windows"
)
async def test_named_pipe_runner_proactor_loop(proactor_loop, app, pipe_name) -> None:
async def test_named_pipe_runner_proactor_loop(
proactor_loop: Any, app: Any, pipe_name: Any
) -> None:
runner = web.AppRunner(app)
await runner.setup()
pipe = web.NamedPipeSite(runner, pipe_name)
await pipe.start()
await runner.cleanup()


async def test_tcpsite_default_host(make_runner):
async def test_tcpsite_default_host(make_runner: Any) -> None:
runner = make_runner()
await runner.setup()
site = web.TCPSite(runner)
Expand Down Expand Up @@ -185,17 +266,6 @@ async def shutdown():
assert spy.called, "run_app() should work after asyncio.run()."


async def test_app_handler_args_failure() -> None:
app = web.Application(handler_args={"unknown_parameter": 5})
runner = web.AppRunner(app)
await runner.setup()
assert runner._server
rh = runner._server()
assert rh._timeout_ceil_threshold == 5
await runner.cleanup()
assert app


@pytest.mark.parametrize(
("value", "expected"),
(
Expand Down
6 changes: 3 additions & 3 deletions tests/test_web_urldispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ async def test_handler_metadata_persistence() -> None:

async def async_handler(request: web.Request) -> web.Response:
"""Doc"""
return web.Response()
return web.Response() # pragma: no cover

def sync_handler(request):
"""Doc"""
Expand Down Expand Up @@ -579,7 +579,7 @@ def test_reuse_last_added_resource(path: str) -> None:
app = web.Application()

async def handler(request: web.Request) -> web.Response:
return web.Response()
return web.Response() # pragma: no cover

app.router.add_get(path, handler, name="a")
app.router.add_post(path, handler, name="a")
Expand All @@ -591,7 +591,7 @@ def test_resource_raw_match() -> None:
app = web.Application()

async def handler(request: web.Request) -> web.Response:
return web.Response()
return web.Response() # pragma: no cover

route = app.router.add_get("/a", handler, name="a")
assert route.resource is not None
Expand Down