Use builtin TimeoutError [k-n] (#109681)

This commit is contained in:
Marc Mueller 2024-02-05 12:08:18 +01:00 committed by GitHub
parent 7a89e58873
commit a9147cf3dd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
58 changed files with 80 additions and 108 deletions

View file

@ -54,7 +54,7 @@ class KaiterraApiData:
try: try:
async with asyncio.timeout(10): async with asyncio.timeout(10):
data = await self._api.get_latest_sensor_readings(self._devices) data = await self._api.get_latest_sensor_readings(self._devices)
except (ClientResponseError, ClientConnectorError, asyncio.TimeoutError) as err: except (ClientResponseError, ClientConnectorError, TimeoutError) as err:
_LOGGER.debug("Couldn't fetch data from Kaiterra API: %s", err) _LOGGER.debug("Couldn't fetch data from Kaiterra API: %s", err)
self.data = {} self.data = {}
async_dispatcher_send(self._hass, DISPATCHER_KAITERRA) async_dispatcher_send(self._hass, DISPATCHER_KAITERRA)

View file

@ -1,5 +1,4 @@
"""Config flow for Kostal Plenticore Solar Inverter integration.""" """Config flow for Kostal Plenticore Solar Inverter integration."""
import asyncio
import logging import logging
from aiohttp.client_exceptions import ClientError from aiohttp.client_exceptions import ClientError
@ -57,7 +56,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
except AuthenticationException as ex: except AuthenticationException as ex:
errors[CONF_PASSWORD] = "invalid_auth" errors[CONF_PASSWORD] = "invalid_auth"
_LOGGER.error("Error response: %s", ex) _LOGGER.error("Error response: %s", ex)
except (ClientError, asyncio.TimeoutError): except (ClientError, TimeoutError):
errors[CONF_HOST] = "cannot_connect" errors[CONF_HOST] = "cannot_connect"
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception") _LOGGER.exception("Unexpected exception")

View file

@ -1,7 +1,6 @@
"""Code to handle the Plenticore API.""" """Code to handle the Plenticore API."""
from __future__ import annotations from __future__ import annotations
import asyncio
from collections import defaultdict from collections import defaultdict
from collections.abc import Callable, Mapping from collections.abc import Callable, Mapping
from datetime import datetime, timedelta from datetime import datetime, timedelta
@ -66,7 +65,7 @@ class Plenticore:
"Authentication exception connecting to %s: %s", self.host, err "Authentication exception connecting to %s: %s", self.host, err
) )
return False return False
except (ClientError, asyncio.TimeoutError) as err: except (ClientError, TimeoutError) as err:
_LOGGER.error("Error connecting to %s", self.host) _LOGGER.error("Error connecting to %s", self.host)
raise ConfigEntryNotReady from err raise ConfigEntryNotReady from err
else: else:

View file

@ -108,7 +108,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
# validate and retrieve the model and device number for a unique id # validate and retrieve the model and device number for a unique id
data = await self.hass.async_add_executor_job(heat_meter.read) data = await self.hass.async_add_executor_job(heat_meter.read)
except (asyncio.TimeoutError, serial.SerialException) as err: except (TimeoutError, serial.SerialException) as err:
_LOGGER.warning("Failed read data from: %s. %s", port, err) _LOGGER.warning("Failed read data from: %s. %s", port, err)
raise CannotConnect(f"Error communicating with device: {err}") from err raise CannotConnect(f"Error communicating with device: {err}") from err

View file

@ -34,7 +34,7 @@ class LaundrifyUpdateCoordinator(DataUpdateCoordinator[dict[str, LaundrifyDevice
async def _async_update_data(self) -> dict[str, LaundrifyDevice]: async def _async_update_data(self) -> dict[str, LaundrifyDevice]:
"""Fetch data from laundrify API.""" """Fetch data from laundrify API."""
try: try:
# Note: asyncio.TimeoutError and aiohttp.ClientError are already # Note: TimeoutError and aiohttp.ClientError are already
# handled by the data update coordinator. # handled by the data update coordinator.
async with asyncio.timeout(REQUEST_TIMEOUT): async with asyncio.timeout(REQUEST_TIMEOUT):
return {m["_id"]: m for m in await self.laundrify_api.get_machines()} return {m["_id"]: m for m in await self.laundrify_api.get_machines()}

View file

@ -79,7 +79,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
async with asyncio.timeout(DEVICE_TIMEOUT): async with asyncio.timeout(DEVICE_TIMEOUT):
await startup_event.wait() await startup_event.wait()
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
"Unable to communicate with the device; " "Unable to communicate with the device; "
f"Try moving the Bluetooth adapter closer to {led_ble.name}" f"Try moving the Bluetooth adapter closer to {led_ble.name}"

View file

@ -1,7 +1,6 @@
"""Config flow flow LIFX.""" """Config flow flow LIFX."""
from __future__ import annotations from __future__ import annotations
import asyncio
import socket import socket
from typing import Any from typing import Any
@ -242,7 +241,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
DEFAULT_ATTEMPTS, DEFAULT_ATTEMPTS,
OVERALL_TIMEOUT, OVERALL_TIMEOUT,
) )
except asyncio.TimeoutError: except TimeoutError:
return None return None
finally: finally:
connection.async_stop() connection.async_stop()

View file

@ -315,7 +315,7 @@ class LIFXUpdateCoordinator(DataUpdateCoordinator[None]):
"""Get updated color information for all zones.""" """Get updated color information for all zones."""
try: try:
await async_execute_lifx(self.device.get_extended_color_zones) await async_execute_lifx(self.device.get_extended_color_zones)
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise HomeAssistantError( raise HomeAssistantError(
f"Timeout getting color zones from {self.name}" f"Timeout getting color zones from {self.name}"
) from ex ) from ex

View file

@ -281,7 +281,7 @@ class LIFXLight(LIFXEntity, LightEntity):
"""Send a power change to the bulb.""" """Send a power change to the bulb."""
try: try:
await self.coordinator.async_set_power(pwr, duration) await self.coordinator.async_set_power(pwr, duration)
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise HomeAssistantError(f"Timeout setting power for {self.name}") from ex raise HomeAssistantError(f"Timeout setting power for {self.name}") from ex
async def set_color( async def set_color(
@ -294,7 +294,7 @@ class LIFXLight(LIFXEntity, LightEntity):
merged_hsbk = merge_hsbk(self.bulb.color, hsbk) merged_hsbk = merge_hsbk(self.bulb.color, hsbk)
try: try:
await self.coordinator.async_set_color(merged_hsbk, duration) await self.coordinator.async_set_color(merged_hsbk, duration)
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise HomeAssistantError(f"Timeout setting color for {self.name}") from ex raise HomeAssistantError(f"Timeout setting color for {self.name}") from ex
async def get_color( async def get_color(
@ -303,7 +303,7 @@ class LIFXLight(LIFXEntity, LightEntity):
"""Send a get color message to the bulb.""" """Send a get color message to the bulb."""
try: try:
await self.coordinator.async_get_color() await self.coordinator.async_get_color()
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise HomeAssistantError( raise HomeAssistantError(
f"Timeout setting getting color for {self.name}" f"Timeout setting getting color for {self.name}"
) from ex ) from ex
@ -429,7 +429,7 @@ class LIFXMultiZone(LIFXColor):
await self.coordinator.async_set_color_zones( await self.coordinator.async_set_color_zones(
zone, zone, zone_hsbk, duration, apply zone, zone, zone_hsbk, duration, apply
) )
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise HomeAssistantError( raise HomeAssistantError(
f"Timeout setting color zones for {self.name}" f"Timeout setting color zones for {self.name}"
) from ex ) from ex
@ -444,7 +444,7 @@ class LIFXMultiZone(LIFXColor):
"""Send a get color zones message to the device.""" """Send a get color zones message to the device."""
try: try:
await self.coordinator.async_get_color_zones() await self.coordinator.async_get_color_zones()
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise HomeAssistantError( raise HomeAssistantError(
f"Timeout getting color zones from {self.name}" f"Timeout getting color zones from {self.name}"
) from ex ) from ex
@ -477,7 +477,7 @@ class LIFXExtendedMultiZone(LIFXMultiZone):
await self.coordinator.async_set_extended_color_zones( await self.coordinator.async_set_extended_color_zones(
color_zones, duration=duration color_zones, duration=duration
) )
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise HomeAssistantError( raise HomeAssistantError(
f"Timeout setting color zones on {self.name}" f"Timeout setting color zones on {self.name}"
) from ex ) from ex

View file

@ -202,7 +202,7 @@ async def async_multi_execute_lifx_with_retries(
a response again. a response again.
If we don't get a result after all attempts, we will raise an If we don't get a result after all attempts, we will raise an
asyncio.TimeoutError exception. TimeoutError exception.
""" """
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
futures: list[asyncio.Future] = [loop.create_future() for _ in methods] futures: list[asyncio.Future] = [loop.create_future() for _ in methods]
@ -236,8 +236,6 @@ async def async_multi_execute_lifx_with_retries(
if failed: if failed:
failed_methods = ", ".join(failed) failed_methods = ", ".join(failed)
raise asyncio.TimeoutError( raise TimeoutError(f"{failed_methods} timed out after {attempts} attempts")
f"{failed_methods} timed out after {attempts} attempts"
)
return results return results

View file

@ -50,7 +50,7 @@ async def async_setup_platform(
async with asyncio.timeout(timeout): async with asyncio.timeout(timeout):
scenes_resp = await httpsession.get(url, headers=headers) scenes_resp = await httpsession.get(url, headers=headers)
except (asyncio.TimeoutError, aiohttp.ClientError): except (TimeoutError, aiohttp.ClientError):
_LOGGER.exception("Error on %s", url) _LOGGER.exception("Error on %s", url)
return return
@ -92,5 +92,5 @@ class LifxCloudScene(Scene):
async with asyncio.timeout(self._timeout): async with asyncio.timeout(self._timeout):
await httpsession.put(url, headers=self._headers) await httpsession.put(url, headers=self._headers)
except (asyncio.TimeoutError, aiohttp.ClientError): except (TimeoutError, aiohttp.ClientError):
_LOGGER.exception("Error on %s", url) _LOGGER.exception("Error on %s", url)

View file

@ -170,7 +170,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
notification_id=NOTIFICATION_ID, notification_id=NOTIFICATION_ID,
) )
return False return False
except asyncio.TimeoutError: except TimeoutError:
# The TimeoutError exception object returns nothing when casted to a # The TimeoutError exception object returns nothing when casted to a
# string, so we'll handle it separately. # string, so we'll handle it separately.
err = f"{_TIMEOUT}s timeout exceeded when connecting to Logi Circle API" err = f"{_TIMEOUT}s timeout exceeded when connecting to Logi Circle API"

View file

@ -162,7 +162,7 @@ class LogiCircleFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
except AuthorizationFailed: except AuthorizationFailed:
(self.hass.data[DATA_FLOW_IMPL][DOMAIN][EXTERNAL_ERRORS]) = "invalid_auth" (self.hass.data[DATA_FLOW_IMPL][DOMAIN][EXTERNAL_ERRORS]) = "invalid_auth"
return self.async_abort(reason="external_error") return self.async_abort(reason="external_error")
except asyncio.TimeoutError: except TimeoutError:
( (
self.hass.data[DATA_FLOW_IMPL][DOMAIN][EXTERNAL_ERRORS] self.hass.data[DATA_FLOW_IMPL][DOMAIN][EXTERNAL_ERRORS]
) = "authorize_url_timeout" ) = "authorize_url_timeout"

View file

@ -101,7 +101,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
lookin_device = await lookin_protocol.get_info() lookin_device = await lookin_protocol.get_info()
devices = await lookin_protocol.get_devices() devices = await lookin_protocol.get_devices()
except (asyncio.TimeoutError, aiohttp.ClientError, NoUsableService) as ex: except (TimeoutError, aiohttp.ClientError, NoUsableService) as ex:
raise ConfigEntryNotReady from ex raise ConfigEntryNotReady from ex
if entry.unique_id != (found_uuid := lookin_device.id.upper()): if entry.unique_id != (found_uuid := lookin_device.id.upper()):

View file

@ -1,7 +1,6 @@
"""The loqed integration.""" """The loqed integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
import logging import logging
import re import re
@ -40,7 +39,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
), ),
) )
except ( except (
asyncio.TimeoutError, TimeoutError,
aiohttp.ClientError, aiohttp.ClientError,
) as ex: ) as ex:
raise ConfigEntryNotReady(f"Unable to connect to bridge at {host}") from ex raise ConfigEntryNotReady(f"Unable to connect to bridge at {host}") from ex

View file

@ -171,7 +171,7 @@ async def async_setup_entry(
return False return False
timed_out = True timed_out = True
with contextlib.suppress(asyncio.TimeoutError): with contextlib.suppress(TimeoutError):
async with asyncio.timeout(BRIDGE_TIMEOUT): async with asyncio.timeout(BRIDGE_TIMEOUT):
await bridge.connect() await bridge.connect()
timed_out = False timed_out = False

View file

@ -117,7 +117,7 @@ class LutronCasetaFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
assets = None assets = None
try: try:
assets = await async_pair(self.data[CONF_HOST]) assets = await async_pair(self.data[CONF_HOST])
except (asyncio.TimeoutError, OSError): except (TimeoutError, OSError):
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
if not errors: if not errors:
@ -227,7 +227,7 @@ class LutronCasetaFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
try: try:
async with asyncio.timeout(BRIDGE_TIMEOUT): async with asyncio.timeout(BRIDGE_TIMEOUT):
await bridge.connect() await bridge.connect()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error( _LOGGER.error(
"Timeout while trying to connect to bridge at %s", "Timeout while trying to connect to bridge at %s",
self.data[CONF_HOST], self.data[CONF_HOST],

View file

@ -262,7 +262,7 @@ class MailboxMediaView(MailboxView):
"""Retrieve media.""" """Retrieve media."""
mailbox = self.get_mailbox(platform) mailbox = self.get_mailbox(platform)
with suppress(asyncio.CancelledError, asyncio.TimeoutError): with suppress(asyncio.CancelledError, TimeoutError):
async with asyncio.timeout(10): async with asyncio.timeout(10):
try: try:
stream = await mailbox.async_get_media(msgid) stream = await mailbox.async_get_media(msgid)

View file

@ -64,7 +64,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
async with asyncio.timeout(CONNECT_TIMEOUT): async with asyncio.timeout(CONNECT_TIMEOUT):
await matter_client.connect() await matter_client.connect()
except (CannotConnect, asyncio.TimeoutError) as err: except (CannotConnect, TimeoutError) as err:
raise ConfigEntryNotReady("Failed to connect to matter server") from err raise ConfigEntryNotReady("Failed to connect to matter server") from err
except InvalidServerVersion as err: except InvalidServerVersion as err:
if use_addon: if use_addon:
@ -109,7 +109,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
async with asyncio.timeout(LISTEN_READY_TIMEOUT): async with asyncio.timeout(LISTEN_READY_TIMEOUT):
await init_ready.wait() await init_ready.wait()
except asyncio.TimeoutError as err: except TimeoutError as err:
listen_task.cancel() listen_task.cancel()
raise ConfigEntryNotReady("Matter client not ready") from err raise ConfigEntryNotReady("Matter client not ready") from err

View file

@ -47,7 +47,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_update_data() -> dict[str, MeaterProbe]: async def async_update_data() -> dict[str, MeaterProbe]:
"""Fetch data from API endpoint.""" """Fetch data from API endpoint."""
try: try:
# Note: asyncio.TimeoutError and aiohttp.ClientError are already # Note: TimeoutError and aiohttp.ClientError are already
# handled by the data update coordinator. # handled by the data update coordinator.
async with asyncio.timeout(10): async with asyncio.timeout(10):
devices: list[MeaterProbe] = await meater_api.get_all_devices() devices: list[MeaterProbe] = await meater_api.get_all_devices()

View file

@ -1345,7 +1345,7 @@ async def async_fetch_image(
"""Retrieve an image.""" """Retrieve an image."""
content, content_type = (None, None) content, content_type = (None, None)
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
with suppress(asyncio.TimeoutError): with suppress(TimeoutError):
async with asyncio.timeout(10): async with asyncio.timeout(10):
response = await websession.get(url) response = await websession.get(url)
if response.status == HTTPStatus.OK: if response.status == HTTPStatus.OK:

View file

@ -36,7 +36,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if isinstance(ex, ClientResponseError) and ex.code == 401: if isinstance(ex, ClientResponseError) and ex.code == 401:
raise ConfigEntryAuthFailed from ex raise ConfigEntryAuthFailed from ex
raise ConfigEntryNotReady from ex raise ConfigEntryNotReady from ex
except (asyncio.TimeoutError, ClientConnectionError) as ex: except (TimeoutError, ClientConnectionError) as ex:
raise ConfigEntryNotReady from ex raise ConfigEntryNotReady from ex
hass.data.setdefault(DOMAIN, {}).update({entry.entry_id: mel_devices}) hass.data.setdefault(DOMAIN, {}).update({entry.entry_id: mel_devices})

View file

@ -60,7 +60,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
if err.status in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN): if err.status in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN):
return self.async_abort(reason="invalid_auth") return self.async_abort(reason="invalid_auth")
return self.async_abort(reason="cannot_connect") return self.async_abort(reason="cannot_connect")
except (asyncio.TimeoutError, ClientError): except (TimeoutError, ClientError):
return self.async_abort(reason="cannot_connect") return self.async_abort(reason="cannot_connect")
return await self._create_entry(username, acquired_token) return await self._create_entry(username, acquired_token)
@ -136,7 +136,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
else: else:
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
except ( except (
asyncio.TimeoutError, TimeoutError,
ClientError, ClientError,
): ):
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"

View file

@ -334,7 +334,7 @@ class MicrosoftFace:
except aiohttp.ClientError: except aiohttp.ClientError:
_LOGGER.warning("Can't connect to microsoft face api") _LOGGER.warning("Can't connect to microsoft face api")
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning("Timeout from microsoft face api %s", response.url) _LOGGER.warning("Timeout from microsoft face api %s", response.url)
raise HomeAssistantError("Network error on microsoft face api.") raise HomeAssistantError("Network error on microsoft face api.")

View file

@ -149,7 +149,7 @@ class MjpegCamera(Camera):
image = await response.read() image = await response.read()
return image return image
except asyncio.TimeoutError: except TimeoutError:
LOGGER.error("Timeout getting camera image from %s", self.name) LOGGER.error("Timeout getting camera image from %s", self.name)
except aiohttp.ClientError as err: except aiohttp.ClientError as err:
@ -169,7 +169,7 @@ class MjpegCamera(Camera):
try: try:
if self._still_image_url: if self._still_image_url:
# Fallback to MJPEG stream if still image URL is not available # Fallback to MJPEG stream if still image URL is not available
with suppress(asyncio.TimeoutError, httpx.HTTPError): with suppress(TimeoutError, httpx.HTTPError):
return ( return (
await client.get( await client.get(
self._still_image_url, auth=auth, timeout=TIMEOUT self._still_image_url, auth=auth, timeout=TIMEOUT
@ -183,7 +183,7 @@ class MjpegCamera(Camera):
stream.aiter_bytes(BUFFER_SIZE) stream.aiter_bytes(BUFFER_SIZE)
) )
except asyncio.TimeoutError: except TimeoutError:
LOGGER.error("Timeout getting camera image from %s", self.name) LOGGER.error("Timeout getting camera image from %s", self.name)
except httpx.HTTPError as err: except httpx.HTTPError as err:
@ -201,7 +201,7 @@ class MjpegCamera(Camera):
response = web.StreamResponse(headers=stream.headers) response = web.StreamResponse(headers=stream.headers)
await response.prepare(request) await response.prepare(request)
# Stream until we are done or client disconnects # Stream until we are done or client disconnects
with suppress(asyncio.TimeoutError, httpx.HTTPError): with suppress(TimeoutError, httpx.HTTPError):
async for chunk in stream.aiter_bytes(BUFFER_SIZE): async for chunk in stream.aiter_bytes(BUFFER_SIZE):
if not self.hass.is_running: if not self.hass.is_running:
break break

View file

@ -197,7 +197,7 @@ class MobileAppNotificationService(BaseNotificationService):
else: else:
_LOGGER.error(message) _LOGGER.error(message)
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error("Timeout sending notification to %s", push_url) _LOGGER.error("Timeout sending notification to %s", push_url)
except aiohttp.ClientError as err: except aiohttp.ClientError as err:
_LOGGER.error("Error sending notification to %s: %r", push_url, err) _LOGGER.error("Error sending notification to %s: %r", push_url, err)

View file

@ -1,5 +1,4 @@
"""Alpha2 config flow.""" """Alpha2 config flow."""
import asyncio
import logging import logging
from typing import Any from typing import Any
@ -27,7 +26,7 @@ async def validate_input(data: dict[str, Any]) -> dict[str, str]:
base = Alpha2Base(data[CONF_HOST]) base = Alpha2Base(data[CONF_HOST])
try: try:
await base.update_data() await base.update_data()
except (aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError): except (aiohttp.client_exceptions.ClientConnectorError, TimeoutError):
return {"error": "cannot_connect"} return {"error": "cannot_connect"}
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception") _LOGGER.exception("Unexpected exception")

View file

@ -128,18 +128,16 @@ class MpdDevice(MediaPlayerEntity):
try: try:
async with asyncio.timeout(self._client.timeout + 5): async with asyncio.timeout(self._client.timeout + 5):
await self._client.connect(self.server, self.port) await self._client.connect(self.server, self.port)
except asyncio.TimeoutError as error: except TimeoutError as error:
# TimeoutError has no message (which hinders logging further # TimeoutError has no message (which hinders logging further
# down the line), so provide one. # down the line), so provide one.
raise asyncio.TimeoutError( raise TimeoutError("Connection attempt timed out") from error
"Connection attempt timed out"
) from error
if self.password is not None: if self.password is not None:
await self._client.password(self.password) await self._client.password(self.password)
self._is_available = True self._is_available = True
yield yield
except ( except (
asyncio.TimeoutError, TimeoutError,
gaierror, gaierror,
mpd.ConnectionError, mpd.ConnectionError,
OSError, OSError,

View file

@ -921,7 +921,7 @@ class MQTT:
try: try:
async with asyncio.timeout(TIMEOUT_ACK): async with asyncio.timeout(TIMEOUT_ACK):
await self._pending_operations[mid].wait() await self._pending_operations[mid].wait()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning( _LOGGER.warning(
"No ACK from MQTT server in %s seconds (mid: %s)", TIMEOUT_ACK, mid "No ACK from MQTT server in %s seconds (mid: %s)", TIMEOUT_ACK, mid
) )

View file

@ -74,7 +74,7 @@ async def async_wait_for_mqtt_client(hass: HomeAssistant) -> bool:
async with asyncio.timeout(AVAILABILITY_TIMEOUT): async with asyncio.timeout(AVAILABILITY_TIMEOUT):
# Await the client setup or an error state was received # Await the client setup or an error state was received
return await state_reached_future return await state_reached_future
except asyncio.TimeoutError: except TimeoutError:
return False return False

View file

@ -32,7 +32,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str,
if error.status == 403: if error.status == 403:
raise InvalidAuth from error raise InvalidAuth from error
raise CannotConnect from error raise CannotConnect from error
except (aiohttp.ClientError, asyncio.TimeoutError) as error: except (aiohttp.ClientError, TimeoutError) as error:
raise CannotConnect from error raise CannotConnect from error
return token return token

View file

@ -109,7 +109,7 @@ async def try_connect(
async with asyncio.timeout(GATEWAY_READY_TIMEOUT): async with asyncio.timeout(GATEWAY_READY_TIMEOUT):
await gateway_ready.wait() await gateway_ready.wait()
return True return True
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.info("Try gateway connect failed with timeout") _LOGGER.info("Try gateway connect failed with timeout")
return False return False
finally: finally:
@ -301,7 +301,7 @@ async def _gw_start(
try: try:
async with asyncio.timeout(GATEWAY_READY_TIMEOUT): async with asyncio.timeout(GATEWAY_READY_TIMEOUT):
await gateway_ready.wait() await gateway_ready.wait()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning( _LOGGER.warning(
"Gateway %s not connected after %s secs so continuing with setup", "Gateway %s not connected after %s secs so continuing with setup",
entry.data[CONF_DEVICE], entry.data[CONF_DEVICE],

View file

@ -49,7 +49,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
options = ConnectionOptions(host=host, username=username, password=password) options = ConnectionOptions(host=host, username=username, password=password)
try: try:
nam = await NettigoAirMonitor.create(websession, options) nam = await NettigoAirMonitor.create(websession, options)
except (ApiError, ClientError, ClientConnectorError, asyncio.TimeoutError) as err: except (ApiError, ClientError, ClientConnectorError, TimeoutError) as err:
raise ConfigEntryNotReady from err raise ConfigEntryNotReady from err
try: try:

View file

@ -92,7 +92,7 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
try: try:
config = await async_get_config(self.hass, self.host) config = await async_get_config(self.hass, self.host)
except (ApiError, ClientConnectorError, asyncio.TimeoutError): except (ApiError, ClientConnectorError, TimeoutError):
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
except CannotGetMacError: except CannotGetMacError:
return self.async_abort(reason="device_unsupported") return self.async_abort(reason="device_unsupported")
@ -128,7 +128,7 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
await async_check_credentials(self.hass, self.host, user_input) await async_check_credentials(self.hass, self.host, user_input)
except AuthFailedError: except AuthFailedError:
errors["base"] = "invalid_auth" errors["base"] = "invalid_auth"
except (ApiError, ClientConnectorError, asyncio.TimeoutError): except (ApiError, ClientConnectorError, TimeoutError):
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception") _LOGGER.exception("Unexpected exception")
@ -155,7 +155,7 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
try: try:
self._config = await async_get_config(self.hass, self.host) self._config = await async_get_config(self.hass, self.host)
except (ApiError, ClientConnectorError, asyncio.TimeoutError): except (ApiError, ClientConnectorError, TimeoutError):
return self.async_abort(reason="cannot_connect") return self.async_abort(reason="cannot_connect")
except CannotGetMacError: except CannotGetMacError:
return self.async_abort(reason="device_unsupported") return self.async_abort(reason="device_unsupported")
@ -209,7 +209,7 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
ApiError, ApiError,
AuthFailedError, AuthFailedError,
ClientConnectorError, ClientConnectorError,
asyncio.TimeoutError, TimeoutError,
): ):
return self.async_abort(reason="reauth_unsuccessful") return self.async_abort(reason="reauth_unsuccessful")

View file

@ -1,7 +1,6 @@
"""The Netatmo data handler.""" """The Netatmo data handler."""
from __future__ import annotations from __future__ import annotations
import asyncio
from collections import deque from collections import deque
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime, timedelta from datetime import datetime, timedelta
@ -239,7 +238,7 @@ class NetatmoDataHandler:
_LOGGER.debug(err) _LOGGER.debug(err)
has_error = True has_error = True
except (asyncio.TimeoutError, aiohttp.ClientConnectorError) as err: except (TimeoutError, aiohttp.ClientConnectorError) as err:
_LOGGER.debug(err) _LOGGER.debug(err)
return True return True

View file

@ -1,5 +1,4 @@
"""Support for Nexia / Trane XL Thermostats.""" """Support for Nexia / Trane XL Thermostats."""
import asyncio
import logging import logging
import aiohttp import aiohttp
@ -45,7 +44,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
await nexia_home.login() await nexia_home.login()
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"Timed out trying to connect to Nexia service: {ex}" f"Timed out trying to connect to Nexia service: {ex}"
) from ex ) from ex

View file

@ -1,5 +1,4 @@
"""Config flow for Nexia integration.""" """Config flow for Nexia integration."""
import asyncio
import logging import logging
import aiohttp import aiohttp
@ -57,7 +56,7 @@ async def validate_input(hass: core.HomeAssistant, data):
) )
try: try:
await nexia_home.login() await nexia_home.login()
except asyncio.TimeoutError as ex: except TimeoutError as ex:
_LOGGER.error("Unable to connect to Nexia service: %s", ex) _LOGGER.error("Unable to connect to Nexia service: %s", ex)
raise CannotConnect from ex raise CannotConnect from ex
except aiohttp.ClientResponseError as http_ex: except aiohttp.ClientResponseError as http_ex:

View file

@ -163,7 +163,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
async with asyncio.timeout(10): async with asyncio.timeout(10):
nextdns = await NextDns.create(websession, api_key) nextdns = await NextDns.create(websession, api_key)
except (ApiError, ClientConnectorError, asyncio.TimeoutError) as err: except (ApiError, ClientConnectorError, TimeoutError) as err:
raise ConfigEntryNotReady from err raise ConfigEntryNotReady from err
tasks = [] tasks = []

View file

@ -43,7 +43,7 @@ class NextDnsFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
) )
except InvalidApiKeyError: except InvalidApiKeyError:
errors["base"] = "invalid_api_key" errors["base"] = "invalid_api_key"
except (ApiError, ClientConnectorError, asyncio.TimeoutError): except (ApiError, ClientConnectorError, TimeoutError):
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
errors["base"] = "unknown" errors["base"] = "unknown"

View file

@ -1,7 +1,6 @@
"""Support for the NextDNS service.""" """Support for the NextDNS service."""
from __future__ import annotations from __future__ import annotations
import asyncio
from collections.abc import Callable from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any, Generic from typing import Any, Generic
@ -647,7 +646,7 @@ class NextDnsSwitch(CoordinatorEntity[NextDnsSettingsUpdateCoordinator], SwitchE
except ( except (
ApiError, ApiError,
ClientConnectorError, ClientConnectorError,
asyncio.TimeoutError, TimeoutError,
ClientError, ClientError,
) as err: ) as err:
raise HomeAssistantError( raise HomeAssistantError(

View file

@ -228,7 +228,7 @@ class NmapDeviceScanner:
) )
) )
self._mac_vendor_lookup = AsyncMacLookup() self._mac_vendor_lookup = AsyncMacLookup()
with contextlib.suppress((asyncio.TimeoutError, aiohttp.ClientError)): with contextlib.suppress((TimeoutError, aiohttp.ClientError)):
# We don't care if this fails since it only # We don't care if this fails since it only
# improves the data when we don't have it from nmap # improves the data when we don't have it from nmap
await self._mac_vendor_lookup.load_vendors() await self._mac_vendor_lookup.load_vendors()

View file

@ -114,7 +114,7 @@ async def _update_no_ip(
except aiohttp.ClientError: except aiohttp.ClientError:
_LOGGER.warning("Can't connect to NO-IP API") _LOGGER.warning("Can't connect to NO-IP API")
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning("Timeout from NO-IP API for domain: %s", domain) _LOGGER.warning("Timeout from NO-IP API for domain: %s", domain)
return False return False

View file

@ -304,7 +304,7 @@ class NukiCoordinator(DataUpdateCoordinator[None]): # pylint: disable=hass-enfo
async def _async_update_data(self) -> None: async def _async_update_data(self) -> None:
"""Fetch data from Nuki bridge.""" """Fetch data from Nuki bridge."""
try: try:
# Note: asyncio.TimeoutError and aiohttp.ClientError are already # Note: TimeoutError and aiohttp.ClientError are already
# handled by the data update coordinator. # handled by the data update coordinator.
async with asyncio.timeout(10): async with asyncio.timeout(10):
events = await self.hass.async_add_executor_job( events = await self.hass.async_add_executor_job(

View file

@ -1,5 +1,4 @@
"""The tests for the KMtronic component.""" """The tests for the KMtronic component."""
import asyncio
from homeassistant.components.kmtronic.const import DOMAIN from homeassistant.components.kmtronic.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
@ -46,7 +45,7 @@ async def test_config_entry_not_ready(
aioclient_mock.get( aioclient_mock.get(
"http://1.1.1.1/status.xml", "http://1.1.1.1/status.xml",
exc=asyncio.TimeoutError(), exc=TimeoutError(),
) )
config_entry = MockConfigEntry( config_entry = MockConfigEntry(

View file

@ -1,5 +1,4 @@
"""The tests for the KMtronic switch platform.""" """The tests for the KMtronic switch platform."""
import asyncio
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus from http import HTTPStatus
@ -156,7 +155,7 @@ async def test_failed_update(
aioclient_mock.clear_requests() aioclient_mock.clear_requests()
aioclient_mock.get( aioclient_mock.get(
"http://1.1.1.1/status.xml", "http://1.1.1.1/status.xml",
exc=asyncio.TimeoutError(), exc=TimeoutError(),
) )
async_fire_time_changed(hass, future) async_fire_time_changed(hass, future)

View file

@ -1,5 +1,4 @@
"""Test the Kostal Plenticore Solar Inverter config flow.""" """Test the Kostal Plenticore Solar Inverter config flow."""
import asyncio
from collections.abc import Generator from collections.abc import Generator
from unittest.mock import ANY, AsyncMock, MagicMock, patch from unittest.mock import ANY, AsyncMock, MagicMock, patch
@ -212,7 +211,7 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
# mock of the context manager instance # mock of the context manager instance
mock_api_ctx = MagicMock() mock_api_ctx = MagicMock()
mock_api_ctx.login = AsyncMock( mock_api_ctx.login = AsyncMock(
side_effect=asyncio.TimeoutError(), side_effect=TimeoutError(),
) )
# mock of the return instance of ApiClient # mock of the return instance of ApiClient

View file

@ -146,7 +146,7 @@ async def test_abort_if_already_setup(hass: HomeAssistant) -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
("side_effect", "error"), ("side_effect", "error"),
[ [
(asyncio.TimeoutError, "authorize_url_timeout"), (TimeoutError, "authorize_url_timeout"),
(AuthorizationFailed, "invalid_auth"), (AuthorizationFailed, "invalid_auth"),
], ],
) )

View file

@ -1,5 +1,4 @@
"""Test the Lutron Caseta config flow.""" """Test the Lutron Caseta config flow."""
import asyncio
from ipaddress import ip_address from ipaddress import ip_address
from pathlib import Path from pathlib import Path
import ssl import ssl
@ -114,7 +113,7 @@ async def test_bridge_cannot_connect_unknown_error(hass: HomeAssistant) -> None:
with patch.object(Smartbridge, "create_tls") as create_tls: with patch.object(Smartbridge, "create_tls") as create_tls:
mock_bridge = MockBridge() mock_bridge = MockBridge()
mock_bridge.connect = AsyncMock(side_effect=asyncio.TimeoutError) mock_bridge.connect = AsyncMock(side_effect=TimeoutError)
create_tls.return_value = mock_bridge create_tls.return_value = mock_bridge
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -270,7 +269,7 @@ async def test_form_user_pairing_fails(hass: HomeAssistant, tmp_path: Path) -> N
with patch( with patch(
"homeassistant.components.lutron_caseta.config_flow.async_pair", "homeassistant.components.lutron_caseta.config_flow.async_pair",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
), patch( ), patch(
"homeassistant.components.lutron_caseta.async_setup", return_value=True "homeassistant.components.lutron_caseta.async_setup", return_value=True
) as mock_setup, patch( ) as mock_setup, patch(

View file

@ -1,5 +1,4 @@
"""Test the base functions of the media player.""" """Test the base functions of the media player."""
import asyncio
from http import HTTPStatus from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
@ -103,7 +102,7 @@ async def test_get_image_http_log_credentials_redacted(
state = hass.states.get("media_player.bedroom") state = hass.states.get("media_player.bedroom")
assert "entity_picture_local" not in state.attributes assert "entity_picture_local" not in state.attributes
aioclient_mock.get(url, exc=asyncio.TimeoutError()) aioclient_mock.get(url, exc=TimeoutError())
client = await hass_client_no_auth() client = await hass_client_no_auth()

View file

@ -1,5 +1,4 @@
"""Test the MELCloud config flow.""" """Test the MELCloud config flow."""
import asyncio
from http import HTTPStatus from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
@ -75,7 +74,7 @@ async def test_form(hass: HomeAssistant, mock_login, mock_get_devices) -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
("error", "reason"), ("error", "reason"),
[(ClientError(), "cannot_connect"), (asyncio.TimeoutError(), "cannot_connect")], [(ClientError(), "cannot_connect"), (TimeoutError(), "cannot_connect")],
) )
async def test_form_errors( async def test_form_errors(
hass: HomeAssistant, mock_login, mock_get_devices, error, reason hass: HomeAssistant, mock_login, mock_get_devices, error, reason
@ -195,7 +194,7 @@ async def test_token_reauthentication(
@pytest.mark.parametrize( @pytest.mark.parametrize(
("error", "reason"), ("error", "reason"),
[ [
(asyncio.TimeoutError(), "cannot_connect"), (TimeoutError(), "cannot_connect"),
(AttributeError(name="get"), "invalid_auth"), (AttributeError(name="get"), "invalid_auth"),
], ],
) )

View file

@ -1,5 +1,4 @@
"""The tests for the microsoft face platform.""" """The tests for the microsoft face platform."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -339,7 +338,7 @@ async def test_service_status_timeout(
aioclient_mock.put( aioclient_mock.put(
ENDPOINT_URL.format("persongroups/service_group"), ENDPOINT_URL.format("persongroups/service_group"),
status=400, status=400,
exc=asyncio.TimeoutError(), exc=TimeoutError(),
) )
with assert_setup_component(3, mf.DOMAIN): with assert_setup_component(3, mf.DOMAIN):

View file

@ -1,5 +1,4 @@
"""Test the moehlenhoff_alpha2 config flow.""" """Test the moehlenhoff_alpha2 config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
from homeassistant import config_entries from homeassistant import config_entries
@ -74,9 +73,7 @@ async def test_form_cannot_connect_error(hass: HomeAssistant) -> None:
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
) )
with patch( with patch("moehlenhoff_alpha2.Alpha2Base.update_data", side_effect=TimeoutError):
"moehlenhoff_alpha2.Alpha2Base.update_data", side_effect=asyncio.TimeoutError
):
result2 = await hass.config_entries.flow.async_configure( result2 = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"], flow_id=result["flow_id"],
user_input={"host": MOCK_BASE_HOST}, user_input={"host": MOCK_BASE_HOST},

View file

@ -2480,7 +2480,7 @@ async def test_delayed_birth_message(
await mqtt.async_subscribe(hass, "homeassistant/status", wait_birth) await mqtt.async_subscribe(hass, "homeassistant/status", wait_birth)
mqtt_client_mock.on_connect(None, None, 0, 0) mqtt_client_mock.on_connect(None, None, 0, 0)
await hass.async_block_till_done() await hass.async_block_till_done()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
await asyncio.wait_for(birth.wait(), 0.2) await asyncio.wait_for(birth.wait(), 0.2)
assert not mqtt_client_mock.publish.called assert not mqtt_client_mock.publish.called
assert not birth.is_set() assert not birth.is_set()

View file

@ -1,5 +1,4 @@
"""Test the mütesync config flow.""" """Test the mütesync config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
import aiohttp import aiohttp
@ -49,7 +48,7 @@ async def test_form(hass: HomeAssistant) -> None:
(Exception, "unknown"), (Exception, "unknown"),
(aiohttp.ClientResponseError(None, None, status=403), "invalid_auth"), (aiohttp.ClientResponseError(None, None, status=403), "invalid_auth"),
(aiohttp.ClientResponseError(None, None, status=500), "cannot_connect"), (aiohttp.ClientResponseError(None, None, status=500), "cannot_connect"),
(asyncio.TimeoutError, "cannot_connect"), (TimeoutError, "cannot_connect"),
], ],
) )
async def test_form_error( async def test_form_error(

View file

@ -1,5 +1,4 @@
"""Define tests for the Nettigo Air Monitor config flow.""" """Define tests for the Nettigo Air Monitor config flow."""
import asyncio
from ipaddress import ip_address from ipaddress import ip_address
from unittest.mock import patch from unittest.mock import patch
@ -171,7 +170,7 @@ async def test_reauth_unsuccessful(hass: HomeAssistant) -> None:
[ [
(ApiError("API Error"), "cannot_connect"), (ApiError("API Error"), "cannot_connect"),
(AuthFailedError("Auth Error"), "invalid_auth"), (AuthFailedError("Auth Error"), "invalid_auth"),
(asyncio.TimeoutError, "cannot_connect"), (TimeoutError, "cannot_connect"),
(ValueError, "unknown"), (ValueError, "unknown"),
], ],
) )
@ -210,7 +209,7 @@ async def test_form_with_auth_errors(hass: HomeAssistant, error) -> None:
"error", "error",
[ [
(ApiError("API Error"), "cannot_connect"), (ApiError("API Error"), "cannot_connect"),
(asyncio.TimeoutError, "cannot_connect"), (TimeoutError, "cannot_connect"),
(ValueError, "unknown"), (ValueError, "unknown"),
], ],
) )

View file

@ -1,5 +1,4 @@
"""Test the nexia config flow.""" """Test the nexia config flow."""
import asyncio
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
import aiohttp import aiohttp
@ -81,7 +80,7 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
with patch( with patch(
"homeassistant.components.nexia.config_flow.NexiaHome.login", "homeassistant.components.nexia.config_flow.NexiaHome.login",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
result2 = await hass.config_entries.flow.async_configure( result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], result["flow_id"],

View file

@ -1,5 +1,4 @@
"""Define tests for the NextDNS config flow.""" """Define tests for the NextDNS config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
from nextdns import ApiError, InvalidApiKeyError from nextdns import ApiError, InvalidApiKeyError
@ -53,7 +52,7 @@ async def test_form_create_entry(hass: HomeAssistant) -> None:
[ [
(ApiError("API Error"), "cannot_connect"), (ApiError("API Error"), "cannot_connect"),
(InvalidApiKeyError, "invalid_api_key"), (InvalidApiKeyError, "invalid_api_key"),
(asyncio.TimeoutError, "cannot_connect"), (TimeoutError, "cannot_connect"),
(ValueError, "unknown"), (ValueError, "unknown"),
], ],
) )

View file

@ -1,5 +1,4 @@
"""Test switch of NextDNS integration.""" """Test switch of NextDNS integration."""
import asyncio
from datetime import timedelta from datetime import timedelta
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
@ -717,7 +716,7 @@ async def test_availability(hass: HomeAssistant) -> None:
"exc", "exc",
[ [
ApiError(Mock()), ApiError(Mock()),
asyncio.TimeoutError, TimeoutError,
ClientConnectorError(Mock(), Mock()), ClientConnectorError(Mock(), Mock()),
ClientError, ClientError,
], ],