forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_aiohttp_compat.py
55 lines (41 loc) · 1.64 KB
/
test_aiohttp_compat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""Test the aiohttp compatibility shim."""
import asyncio
from contextlib import suppress
from aiohttp import client, web, web_protocol, web_server
import pytest
from homeassistant.helpers.aiohttp_compat import CancelOnDisconnectRequestHandler
@pytest.mark.allow_hosts(["127.0.0.1"])
async def test_handler_cancellation(socket_enabled, unused_tcp_port_factory) -> None:
"""Test that handler cancels the request on disconnect.
From aiohttp tests/test_web_server.py
"""
assert web_protocol.RequestHandler is CancelOnDisconnectRequestHandler
assert web_server.RequestHandler is CancelOnDisconnectRequestHandler
event = asyncio.Event()
port = unused_tcp_port_factory()
async def on_request(_: web.Request) -> web.Response:
nonlocal event
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
event.set()
raise
else:
raise web.HTTPInternalServerError()
app = web.Application()
app.router.add_route("GET", "/", on_request)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host="127.0.0.1", port=port)
await site.start()
try:
async with client.ClientSession(
timeout=client.ClientTimeout(total=0.1)
) as sess:
with pytest.raises(asyncio.TimeoutError):
await sess.get(f"http://127.0.0.1:{port}/")
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(event.wait(), timeout=1)
assert event.is_set(), "Request handler hasn't been cancelled"
finally:
await asyncio.gather(runner.shutdown(), site.stop())