Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .coveragerc.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ exclude_also = [
'assert False',
': \.\.\.(\s*#.*)?$',
'^ +\.\.\.$',
'pytest.fail\('
]
23 changes: 2 additions & 21 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from uuid import uuid4

import pytest
import trustme
from multidict import CIMultiDict
from yarl import URL

Expand All @@ -38,16 +39,6 @@
from aiohttp.http import WS_KEY, HttpVersion11
from aiohttp.test_utils import get_unused_port_socket, loop_context

try:
import trustme

# Check if the CA is available in runtime, MacOS on Py3.10 fails somehow
trustme.CA()

TRUSTME: bool = True
except ImportError:
TRUSTME = False


def pytest_configure(config: pytest.Config) -> None:
# On Windows with Python 3.10/3.11, proxy.py's threaded mode can leave
Expand Down Expand Up @@ -122,8 +113,6 @@ def blockbuster(request: pytest.FixtureRequest) -> Iterator[None]:

@pytest.fixture
def tls_certificate_authority() -> trustme.CA:
if not TRUSTME:
pytest.xfail("trustme is not supported")
return trustme.CA()


Expand Down Expand Up @@ -213,8 +202,6 @@ def unix_sockname(
# Ref: https://unix.stackexchange.com/a/367012/27133

sock_file_name = "unix.sock"
unique_prefix = f"{uuid4()!s}-"
unique_prefix_len = len(unique_prefix.encode())

root_tmp_dir = Path("/tmp").resolve()
os_tmp_dir = Path(os.getenv("TMPDIR", "/tmp")).resolve()
Expand Down Expand Up @@ -249,7 +236,7 @@ def assert_sock_fits(sock_path: str) -> None:
unique_paths = [p for n, p in enumerate(paths) if p not in paths[:n]]
paths_num = len(unique_paths)

for num, tmp_dir_path in enumerate(paths, 1):
for num, tmp_dir_path in enumerate(paths, 1): # pragma: no branch
with make_tmp_dir(tmp_dir_path) as tmps:
tmpd = Path(tmps).resolve()
sock_path = str(tmpd / sock_file_name)
Expand All @@ -261,12 +248,6 @@ def assert_sock_fits(sock_path: str) -> None:
assert_sock_fits(sock_path)

if sock_path_len <= max_sock_len:
if max_sock_len - sock_path_len >= unique_prefix_len:
# If we're lucky to have extra space in the path,
# let's also make it more unique
sock_path = str(tmpd / "".join((unique_prefix, sock_file_name)))
# Double-checking it:
assert_sock_fits(sock_path)
yield sock_path
return

Expand Down
4 changes: 2 additions & 2 deletions tests/test_classbasedview.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async def get(self) -> web.StreamResponse:
async def test_render_unknown_method() -> None:
class MyView(View):
async def get(self) -> web.StreamResponse:
return web.Response(text="OK")
assert False

options = get

Expand All @@ -43,7 +43,7 @@ async def get(self) -> web.StreamResponse:
async def test_render_unsupported_method() -> None:
class MyView(View):
async def get(self) -> web.StreamResponse:
return web.Response(text="OK")
assert False

options = delete = get

Expand Down
8 changes: 4 additions & 4 deletions tests/test_client_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
import brotlicffi as brotli
except ImportError:
import brotli
except ImportError:
brotli = None # pragma: no cover
except ImportError: # pragma: no cover
brotli = None

try:
from backports.zstd import ZstdCompressor
Expand Down Expand Up @@ -397,7 +397,7 @@ async def handler(request: web.Request) -> web.Response:
client = await aiohttp_client(app)

async def data_gen() -> AsyncIterator[bytes]:
for _ in range(2):
for _ in range(2): # pragma: no branch
yield b"just data"
await asyncio.sleep(0.1)

Expand Down Expand Up @@ -430,7 +430,7 @@ async def handler(request: web.Request) -> web.Response:
client = await aiohttp_client(app)

async def data_gen() -> AsyncIterator[bytes]:
for _ in range(2):
for _ in range(2): # pragma: no branch
yield b"just data"
await asyncio.sleep(0.1)

Expand Down
6 changes: 2 additions & 4 deletions tests/test_client_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,10 +633,8 @@ async def test_request_middleware_overrides_session_middleware_with_specific(
request_middleware_called = False

async def handler(request: web.Request) -> web.Response:
auth_header = request.headers.get("Authorization")
if auth_header:
return web.Response(text=f"Auth: {auth_header}")
return web.Response(text="No auth")
auth_header = request.headers["Authorization"]
return web.Response(text=f"Auth: {auth_header}")

async def session_middleware(
request: ClientRequest, handler: ClientHandlerType
Expand Down
4 changes: 2 additions & 2 deletions tests/test_client_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -629,8 +629,8 @@ async def create_connection(
session._connector, "_release", autospec=True, spec_set=True
):
with pytest.raises(UnexpectedException):
async with session.request("get", "http://example.com") as resp:
await resp.text()
async with session.request("get", "http://example.com"):
pass

# normally called during garbage collection. triggers an exception
# if the connection wasn't already closed
Expand Down
17 changes: 5 additions & 12 deletions tests/test_client_ws_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ async def handler(request: web.Request) -> NoReturn:

with pytest.raises(WSMessageTypeError):
await resp.receive_bytes()
await resp.close()
await resp.close()


async def test_recv_bytes_after_close(aiohttp_client: AiohttpClient) -> None:
Expand All @@ -97,7 +97,7 @@ async def handler(request: web.Request) -> NoReturn:
match=f"Received message {WSMsgType.CLOSE}:.+ is not WSMsgType.BINARY",
):
await resp.receive_bytes()
await resp.close()
await resp.close()


async def test_send_recv_bytes(aiohttp_client: AiohttpClient) -> None:
Expand Down Expand Up @@ -142,8 +142,7 @@ async def handler(request: web.Request) -> NoReturn:

with pytest.raises(WSMessageTypeError):
await resp.receive_str()

await resp.close()
await resp.close()


async def test_recv_text_after_close(aiohttp_client: AiohttpClient) -> None:
Expand All @@ -164,7 +163,7 @@ async def handler(request: web.Request) -> NoReturn:
match=f"Received message {WSMsgType.CLOSE}:.+ is not WSMsgType.TEXT",
):
await resp.receive_str()
await resp.close()
await resp.close()


async def test_send_recv_json(aiohttp_client: AiohttpClient) -> None:
Expand Down Expand Up @@ -1151,13 +1150,7 @@ async def handler(request: web.Request) -> web.WebSocketResponse:

async def test_send_recv_compress_wbit_error(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)

msg = await ws.receive_bytes()
await ws.send_bytes(msg + b"/answer")
await ws.close()
return ws
assert False

app = web.Application()
app.router.add_route("GET", "/", handler)
Expand Down
14 changes: 1 addition & 13 deletions tests/test_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,6 @@ async def test_del(loop: asyncio.AbstractEventLoop, key: ConnectionKey) -> None:
"connections": mock.ANY,
"message": "Unclosed connector",
}
if loop.get_debug():
msg["source_traceback"] = mock.ANY
exc_handler.assert_called_with(loop, msg)


Expand Down Expand Up @@ -2118,9 +2116,6 @@ async def test_cleanup3(loop: asyncio.AbstractEventLoop, key: ConnectionKey) ->
async def test_cleanup_closed(
loop: asyncio.AbstractEventLoop, mocker: MockerFixture
) -> None:
if not hasattr(loop, "__dict__"):
pytest.skip("can not override loop attributes")

m = mocker.spy(loop, "call_at")
conn = aiohttp.BaseConnector(enable_cleanup_closed=True)

Expand Down Expand Up @@ -4121,10 +4116,7 @@ async def _resolve_host(
first_conn = next(iter(conn._conns.values()))[0][0]

assert first_conn.transport is not None
try:
_sslcontext = first_conn.transport._ssl_protocol._sslcontext # type: ignore[attr-defined]
except AttributeError:
_sslcontext = first_conn.transport._sslcontext # type: ignore[attr-defined]
_sslcontext = first_conn.transport._ssl_protocol._sslcontext # type: ignore[attr-defined]

assert _sslcontext is client_ssl_ctx
r.close()
Expand Down Expand Up @@ -4531,10 +4523,6 @@ async def await_connection_and_check_waiters() -> None:
connection.close()

async def allow_connection_and_add_dummy_waiter() -> None:
# `asyncio.gather` may execute coroutines not in order.
# Skip one event loop run cycle in such a case.
if connection_key not in connector._waiters:
await asyncio.sleep(0)
list(connector._waiters[connection_key])[0].set_result(None)
del connector._waiters[connection_key]
connector._waiters[connection_key][dummy_waiter] = None
Expand Down
2 changes: 1 addition & 1 deletion tests/test_http_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
import brotlicffi as brotli
except ImportError:
import brotli
except ImportError:
except ImportError: # pragma: no cover
brotli = None

try:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def test_import_time(pytester: pytest.Pytester) -> None:
finally:
if old_path is None:
os.environ.pop("PYTHONPATH")
else:
else: # pragma: no cover
os.environ["PYTHONPATH"] = old_path

assert best_time_ms < IMPORT_TIME_THRESHOLD_MS
2 changes: 1 addition & 1 deletion tests/test_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def target() -> None:
with loop_context() as loop:
assert asyncio.get_event_loop() is loop
loop.run_until_complete(test_subprocess_co(loop))
except Exception as exc:
except Exception as exc: # pragma: no cover
nonlocal child_exc
child_exc = exc

Expand Down
2 changes: 1 addition & 1 deletion tests/test_multipart.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ async def test_read_incomplete_body_chunked(self) -> None:
obj = aiohttp.BodyPartReader(BOUNDARY, d, stream)
result = b""
with pytest.raises(ValueError):
for _ in range(4):
for _ in range(4): # pragma: no branch
result += await obj.read_chunk(7)
assert b"Hello, World!\r\n-" == result

Expand Down
8 changes: 3 additions & 5 deletions tests/test_payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
assert False

async def write(self, writer: AbstractStreamWriter) -> None:
pass
"""Dummy write."""


def test_register_type(registry: payload.PayloadRegistry) -> None:
Expand Down Expand Up @@ -146,17 +146,15 @@ def test_string_io_payload() -> None:

def test_async_iterable_payload_default_content_type() -> None:
async def gen() -> AsyncIterator[bytes]:
return
yield b"abc" # type: ignore[unreachable] # pragma: no cover
yield b"abc" # pragma: no cover

p = payload.AsyncIterablePayload(gen())
assert p.content_type == "application/octet-stream"


def test_async_iterable_payload_explicit_content_type() -> None:
async def gen() -> AsyncIterator[bytes]:
return
yield b"abc" # type: ignore[unreachable] # pragma: no cover
yield b"abc" # pragma: no cover

p = payload.AsyncIterablePayload(gen(), content_type="application/custom")
assert p.content_type == "application/custom"
Expand Down
18 changes: 2 additions & 16 deletions tests/test_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import gc
import ipaddress
import socket
from collections.abc import Awaitable, Callable, Collection, Generator, Iterable
from collections.abc import Awaitable, Callable, Collection, Generator
from ipaddress import ip_address
from typing import Any, NamedTuple
from unittest.mock import Mock, create_autospec, patch
Expand All @@ -21,7 +21,7 @@
import aiodns

getaddrinfo = hasattr(aiodns.DNSResolver, "getaddrinfo")
except ImportError:
except ImportError: # pragma: no cover
aiodns = None # type: ignore[assignment]
getaddrinfo = False

Expand Down Expand Up @@ -110,11 +110,6 @@ def __init__(self, host: str) -> None:
self.service = None


class FakeQueryResult:
def __init__(self, host: str) -> None:
self.host = host


async def fake_aiodns_getaddrinfo_ipv4_result(
hosts: Collection[str],
) -> FakeAIODNSAddrInfoIPv4Result:
Expand All @@ -133,10 +128,6 @@ async def fake_aiodns_getnameinfo_ipv6_result(
return FakeAIODNSNameInfoIPv6Result(host)


async def fake_query_result(result: Iterable[str]) -> list[FakeQueryResult]:
return [FakeQueryResult(host=h) for h in result]


def fake_addrinfo(hosts: Collection[str]) -> Callable[..., Awaitable[_AddrInfo4]]:
async def fake(*args: Any, **kwargs: Any) -> _AddrInfo4:
if not hosts:
Expand Down Expand Up @@ -440,11 +431,6 @@ def test_aio_dns_is_default() -> None:
assert DefaultResolver is AsyncResolver


@pytest.mark.skipif(getaddrinfo, reason="aiodns <3.2.0 required")
def test_threaded_resolver_is_default() -> None:
assert DefaultResolver is ThreadedResolver


@pytest.mark.skipif(not getaddrinfo, reason="aiodns >=3.2.0 required")
async def test_dns_resolver_manager_sharing(
dns_resolver_manager: _DNSResolverManager,
Expand Down
Loading
Loading