From 381ffe6eed4ab3c19f671cb89b4abfab091473c2 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 29 Apr 2024 00:38:40 -0500 Subject: [PATCH] Use built-in aiohttp timeout instead of asyncio.timeout in media_player (#116364) * Use built-in aiohttp timeout instead of asyncio.timeout in media_player Avoids having two timeouts running to fetch images * fix mock --- homeassistant/components/media_player/__init__.py | 15 +++++++++------ tests/components/demo/test_media_player.py | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/media_player/__init__.py b/homeassistant/components/media_player/__init__.py index 35e1b1cb71e7b6..b90de95a48942c 100644 --- a/homeassistant/components/media_player/__init__.py +++ b/homeassistant/components/media_player/__init__.py @@ -17,6 +17,7 @@ from typing import Any, Final, Required, TypedDict, final from urllib.parse import quote, urlparse +import aiohttp from aiohttp import web from aiohttp.hdrs import CACHE_CONTROL, CONTENT_TYPE from aiohttp.typedefs import LooseHeaders @@ -1336,6 +1337,9 @@ async def websocket_browse_media( connection.send_result(msg["id"], result) +_FETCH_TIMEOUT = aiohttp.ClientTimeout(total=10) + + async def async_fetch_image( logger: logging.Logger, hass: HomeAssistant, url: str ) -> tuple[bytes | None, str | None]: @@ -1343,12 +1347,11 @@ async def async_fetch_image( content, content_type = (None, None) websession = async_get_clientsession(hass) with suppress(TimeoutError): - async with asyncio.timeout(10): - response = await websession.get(url) - if response.status == HTTPStatus.OK: - content = await response.read() - if content_type := response.headers.get(CONTENT_TYPE): - content_type = content_type.split(";")[0] + response = await websession.get(url, timeout=_FETCH_TIMEOUT) + if response.status == HTTPStatus.OK: + content = await response.read() + if content_type := response.headers.get(CONTENT_TYPE): + content_type = content_type.split(";")[0] if content is None: url_parts = URL(url) diff --git a/tests/components/demo/test_media_player.py b/tests/components/demo/test_media_player.py index 6bc4c7a980b7fc..8e7b32cc4b7ea1 100644 --- a/tests/components/demo/test_media_player.py +++ b/tests/components/demo/test_media_player.py @@ -477,7 +477,7 @@ async def release(self): class MockWebsession: """Test websession.""" - async def get(self, url): + async def get(self, url, **kwargs): """Test websession get.""" return MockResponse()