Use builtin TimeoutError [a-d] (#109678)

This commit is contained in:
Marc Mueller 2024-02-05 11:31:33 +01:00 committed by GitHub
parent 41a256a3ff
commit c82933175d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
63 changed files with 97 additions and 137 deletions

View file

@ -1,7 +1,6 @@
"""Adds config flow for AccuWeather.""" """Adds config flow for AccuWeather."""
from __future__ import annotations from __future__ import annotations
import asyncio
from asyncio import timeout from asyncio import timeout
from typing import Any from typing import Any
@ -61,7 +60,7 @@ class AccuWeatherFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
longitude=user_input[CONF_LONGITUDE], longitude=user_input[CONF_LONGITUDE],
) )
await accuweather.async_get_location() await accuweather.async_get_location()
except (ApiError, ClientConnectorError, asyncio.TimeoutError, ClientError): except (ApiError, ClientConnectorError, TimeoutError, ClientError):
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
except InvalidApiKeyError: except InvalidApiKeyError:
errors[CONF_API_KEY] = "invalid_api_key" errors[CONF_API_KEY] = "invalid_api_key"

View file

@ -1,7 +1,6 @@
"""Config flow for Rollease Acmeda Automate Pulse Hub.""" """Config flow for Rollease Acmeda Automate Pulse Hub."""
from __future__ import annotations from __future__ import annotations
import asyncio
from asyncio import timeout from asyncio import timeout
from contextlib import suppress from contextlib import suppress
from typing import Any from typing import Any
@ -42,7 +41,7 @@ class AcmedaFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
} }
hubs: list[aiopulse.Hub] = [] hubs: list[aiopulse.Hub] = []
with suppress(asyncio.TimeoutError): with suppress(TimeoutError):
async with timeout(5): async with timeout(5):
async for hub in aiopulse.Hub.discover(): async for hub in aiopulse.Hub.discover():
if hub.id not in already_configured: if hub.id not in already_configured:

View file

@ -303,7 +303,7 @@ class AdsEntity(Entity):
try: try:
async with timeout(10): async with timeout(10):
await self._event.wait() await self._event.wait()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.debug("Variable %s: Timeout during first update", ads_var) _LOGGER.debug("Variable %s: Timeout during first update", ads_var)
@property @property

View file

@ -1,5 +1,4 @@
"""The aladdin_connect component.""" """The aladdin_connect component."""
import asyncio
import logging import logging
from typing import Final from typing import Final
@ -29,7 +28,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
) )
try: try:
await acc.login() await acc.login()
except (ClientError, asyncio.TimeoutError, Aladdin.ConnectionError) as ex: except (ClientError, TimeoutError, Aladdin.ConnectionError) as ex:
raise ConfigEntryNotReady("Can not connect to host") from ex raise ConfigEntryNotReady("Can not connect to host") from ex
except Aladdin.InvalidPasswordError as ex: except Aladdin.InvalidPasswordError as ex:
raise ConfigEntryAuthFailed("Incorrect Password") from ex raise ConfigEntryAuthFailed("Incorrect Password") from ex

View file

@ -1,7 +1,6 @@
"""Config flow for Aladdin Connect cover integration.""" """Config flow for Aladdin Connect cover integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
from collections.abc import Mapping from collections.abc import Mapping
from typing import Any from typing import Any
@ -42,7 +41,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> None:
) )
try: try:
await acc.login() await acc.login()
except (ClientError, asyncio.TimeoutError, Aladdin.ConnectionError) as ex: except (ClientError, TimeoutError, Aladdin.ConnectionError) as ex:
raise ex raise ex
except Aladdin.InvalidPasswordError as ex: except Aladdin.InvalidPasswordError as ex:
@ -81,7 +80,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
except InvalidAuth: except InvalidAuth:
errors["base"] = "invalid_auth" errors["base"] = "invalid_auth"
except (ClientError, asyncio.TimeoutError, Aladdin.ConnectionError): except (ClientError, TimeoutError, Aladdin.ConnectionError):
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
else: else:
@ -117,7 +116,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
except InvalidAuth: except InvalidAuth:
errors["base"] = "invalid_auth" errors["base"] = "invalid_auth"
except (ClientError, asyncio.TimeoutError, Aladdin.ConnectionError): except (ClientError, TimeoutError, Aladdin.ConnectionError):
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
else: else:

View file

@ -122,7 +122,7 @@ class Auth:
allow_redirects=True, allow_redirects=True,
) )
except (asyncio.TimeoutError, aiohttp.ClientError): except (TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout calling LWA to get auth token") _LOGGER.error("Timeout calling LWA to get auth token")
return None return None

View file

@ -1,7 +1,6 @@
"""Alexa state report code.""" """Alexa state report code."""
from __future__ import annotations from __future__ import annotations
import asyncio
from asyncio import timeout from asyncio import timeout
from http import HTTPStatus from http import HTTPStatus
import json import json
@ -375,7 +374,7 @@ async def async_send_changereport_message(
allow_redirects=True, allow_redirects=True,
) )
except (asyncio.TimeoutError, aiohttp.ClientError): except (TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout sending report to Alexa for %s", alexa_entity.entity_id) _LOGGER.error("Timeout sending report to Alexa for %s", alexa_entity.entity_id)
return return
@ -531,7 +530,7 @@ async def async_send_doorbell_event_message(
allow_redirects=True, allow_redirects=True,
) )
except (asyncio.TimeoutError, aiohttp.ClientError): except (TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout sending report to Alexa for %s", alexa_entity.entity_id) _LOGGER.error("Timeout sending report to Alexa for %s", alexa_entity.entity_id)
return return

View file

@ -329,7 +329,7 @@ class Analytics:
response.status, response.status,
self.endpoint, self.endpoint,
) )
except asyncio.TimeoutError: except TimeoutError:
LOGGER.error("Timeout sending analytics to %s", ANALYTICS_ENDPOINT_URL) LOGGER.error("Timeout sending analytics to %s", ANALYTICS_ENDPOINT_URL)
except aiohttp.ClientError as err: except aiohttp.ClientError as err:
LOGGER.error( LOGGER.error(

View file

@ -1,7 +1,6 @@
"""The Android TV Remote integration.""" """The Android TV Remote integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
from asyncio import timeout from asyncio import timeout
import logging import logging
@ -50,7 +49,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
except InvalidAuth as exc: except InvalidAuth as exc:
# The Android TV is hard reset or the certificate and key files were deleted. # The Android TV is hard reset or the certificate and key files were deleted.
raise ConfigEntryAuthFailed from exc raise ConfigEntryAuthFailed from exc
except (CannotConnect, ConnectionClosed, asyncio.TimeoutError) as exc: except (CannotConnect, ConnectionClosed, TimeoutError) as exc:
# The Android TV is network unreachable. Raise exception and let Home Assistant retry # The Android TV is network unreachable. Raise exception and let Home Assistant retry
# later. If device gets a new IP address the zeroconf flow will update the config. # later. If device gets a new IP address the zeroconf flow will update the config.
raise ConfigEntryNotReady from exc raise ConfigEntryNotReady from exc

View file

@ -1,7 +1,6 @@
"""Config flow for APCUPSd integration.""" """Config flow for APCUPSd integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
from typing import Any from typing import Any
import voluptuous as vol import voluptuous as vol
@ -54,7 +53,7 @@ class ConfigFlowHandler(ConfigFlow, domain=DOMAIN):
coordinator = APCUPSdCoordinator(self.hass, host, port) coordinator = APCUPSdCoordinator(self.hass, host, port)
await coordinator.async_request_refresh() await coordinator.async_request_refresh()
if isinstance(coordinator.last_exception, (UpdateFailed, asyncio.TimeoutError)): if isinstance(coordinator.last_exception, (UpdateFailed, TimeoutError)):
errors = {"base": "cannot_connect"} errors = {"base": "cannot_connect"}
return self.async_show_form( return self.async_show_form(
step_id="user", data_schema=_SCHEMA, errors=errors step_id="user", data_schema=_SCHEMA, errors=errors

View file

@ -175,7 +175,7 @@ class APIEventStream(HomeAssistantView):
msg = f"data: {payload}\n\n" msg = f"data: {payload}\n\n"
_LOGGER.debug("STREAM %s WRITING %s", id(stop_obj), msg.strip()) _LOGGER.debug("STREAM %s WRITING %s", id(stop_obj), msg.strip())
await response.write(msg.encode("UTF-8")) await response.write(msg.encode("UTF-8"))
except asyncio.TimeoutError: except TimeoutError:
await to_write.put(STREAM_PING_PAYLOAD) await to_write.put(STREAM_PING_PAYLOAD)
except asyncio.CancelledError: except asyncio.CancelledError:

View file

@ -83,7 +83,7 @@ async def _run_client(hass: HomeAssistant, client: Client, interval: float) -> N
except ConnectionFailed: except ConnectionFailed:
await asyncio.sleep(interval) await asyncio.sleep(interval)
except asyncio.TimeoutError: except TimeoutError:
continue continue
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception, aborting arcam client") _LOGGER.exception("Unexpected exception, aborting arcam client")

View file

@ -241,7 +241,7 @@ async def websocket_run(
# Task contains a timeout # Task contains a timeout
async with asyncio.timeout(timeout): async with asyncio.timeout(timeout):
await run_task await run_task
except asyncio.TimeoutError: except TimeoutError:
pipeline_input.run.process_event( pipeline_input.run.process_event(
PipelineEvent( PipelineEvent(
PipelineEventType.ERROR, PipelineEventType.ERROR,
@ -487,7 +487,7 @@ async def websocket_device_capture(
) )
try: try:
with contextlib.suppress(asyncio.TimeoutError): with contextlib.suppress(TimeoutError):
async with asyncio.timeout(timeout_seconds): async with asyncio.timeout(timeout_seconds):
while True: while True:
# Send audio chunks encoded as base64 # Send audio chunks encoded as base64

View file

@ -59,7 +59,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return await async_setup_august(hass, entry, august_gateway) return await async_setup_august(hass, entry, august_gateway)
except (RequireValidation, InvalidAuth) as err: except (RequireValidation, InvalidAuth) as err:
raise ConfigEntryAuthFailed from err raise ConfigEntryAuthFailed from err
except asyncio.TimeoutError as err: except TimeoutError as err:
raise ConfigEntryNotReady("Timed out connecting to august api") from err raise ConfigEntryNotReady("Timed out connecting to august api") from err
except (AugustApiAIOHTTPError, ClientResponseError, CannotConnect) as err: except (AugustApiAIOHTTPError, ClientResponseError, CannotConnect) as err:
raise ConfigEntryNotReady from err raise ConfigEntryNotReady from err
@ -233,7 +233,7 @@ class AugustData(AugustSubscriberMixin):
return_exceptions=True, return_exceptions=True,
): ):
if isinstance(result, Exception) and not isinstance( if isinstance(result, Exception) and not isinstance(
result, (asyncio.TimeoutError, ClientResponseError, CannotConnect) result, (TimeoutError, ClientResponseError, CannotConnect)
): ):
_LOGGER.warning( _LOGGER.warning(
"Unexpected exception during initial sync: %s", "Unexpected exception during initial sync: %s",
@ -292,7 +292,7 @@ class AugustData(AugustSubscriberMixin):
for device_id in device_ids_list: for device_id in device_ids_list:
try: try:
await self._async_refresh_device_detail_by_id(device_id) await self._async_refresh_device_detail_by_id(device_id)
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning( _LOGGER.warning(
"Timed out calling august api during refresh of device: %s", "Timed out calling august api during refresh of device: %s",
device_id, device_id,

View file

@ -1,7 +1,6 @@
"""Helpers to resolve client ID/secret.""" """Helpers to resolve client ID/secret."""
from __future__ import annotations from __future__ import annotations
import asyncio
from html.parser import HTMLParser from html.parser import HTMLParser
from ipaddress import ip_address from ipaddress import ip_address
import logging import logging
@ -102,7 +101,7 @@ async def fetch_redirect_uris(hass: HomeAssistant, url: str) -> list[str]:
if chunks == 10: if chunks == 10:
break break
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error("Timeout while looking up redirect_uri %s", url) _LOGGER.error("Timeout while looking up redirect_uri %s", url)
except aiohttp.client_exceptions.ClientSSLError: except aiohttp.client_exceptions.ClientSSLError:
_LOGGER.error("SSL error while looking up redirect_uri %s", url) _LOGGER.error("SSL error while looking up redirect_uri %s", url)

View file

@ -1,6 +1,5 @@
"""Axis network device abstraction.""" """Axis network device abstraction."""
import asyncio
from asyncio import timeout from asyncio import timeout
from types import MappingProxyType from types import MappingProxyType
from typing import Any from typing import Any
@ -270,7 +269,7 @@ async def get_axis_device(
) )
raise AuthenticationRequired from err raise AuthenticationRequired from err
except (asyncio.TimeoutError, axis.RequestError) as err: except (TimeoutError, axis.RequestError) as err:
LOGGER.error("Error connecting to the Axis device at %s", config[CONF_HOST]) LOGGER.error("Error connecting to the Axis device at %s", config[CONF_HOST])
raise CannotConnect from err raise CannotConnect from err

View file

@ -1,7 +1,6 @@
"""The Big Ass Fans integration.""" """The Big Ass Fans integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
from asyncio import timeout from asyncio import timeout
from aiobafi6 import Device, Service from aiobafi6 import Device, Service
@ -42,7 +41,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"Unexpected device found at {ip_address}; expected {entry.unique_id}, found {device.dns_sd_uuid}" f"Unexpected device found at {ip_address}; expected {entry.unique_id}, found {device.dns_sd_uuid}"
) from ex ) from ex
except asyncio.TimeoutError as ex: except TimeoutError as ex:
run_future.cancel() run_future.cancel()
raise ConfigEntryNotReady(f"Timed out connecting to {ip_address}") from ex raise ConfigEntryNotReady(f"Timed out connecting to {ip_address}") from ex

View file

@ -1,7 +1,6 @@
"""Config flow for baf.""" """Config flow for baf."""
from __future__ import annotations from __future__ import annotations
import asyncio
from asyncio import timeout from asyncio import timeout
import logging import logging
from typing import Any from typing import Any
@ -28,7 +27,7 @@ async def async_try_connect(ip_address: str) -> Device:
try: try:
async with timeout(RUN_TIMEOUT): async with timeout(RUN_TIMEOUT):
await device.async_wait_available() await device.async_wait_available()
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise CannotConnect from ex raise CannotConnect from ex
finally: finally:
run_future.cancel() run_future.cancel()

View file

@ -1,5 +1,4 @@
"""Support for Blink Home Camera System.""" """Support for Blink Home Camera System."""
import asyncio
from copy import deepcopy from copy import deepcopy
import logging import logging
@ -93,7 +92,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
await blink.start() await blink.start()
except (ClientError, asyncio.TimeoutError) as ex: except (ClientError, TimeoutError) as ex:
raise ConfigEntryNotReady("Can not connect to host") from ex raise ConfigEntryNotReady("Can not connect to host") from ex
if blink.auth.check_key_required(): if blink.auth.check_key_required():

View file

@ -1,7 +1,6 @@
"""Support for Blink Alarm Control Panel.""" """Support for Blink Alarm Control Panel."""
from __future__ import annotations from __future__ import annotations
import asyncio
import logging import logging
from blinkpy.blinkpy import Blink, BlinkSyncModule from blinkpy.blinkpy import Blink, BlinkSyncModule
@ -91,7 +90,7 @@ class BlinkSyncModuleHA(
try: try:
await self.sync.async_arm(False) await self.sync.async_arm(False)
except asyncio.TimeoutError as er: except TimeoutError as er:
raise HomeAssistantError("Blink failed to disarm camera") from er raise HomeAssistantError("Blink failed to disarm camera") from er
await self.coordinator.async_refresh() await self.coordinator.async_refresh()
@ -101,7 +100,7 @@ class BlinkSyncModuleHA(
try: try:
await self.sync.async_arm(True) await self.sync.async_arm(True)
except asyncio.TimeoutError as er: except TimeoutError as er:
raise HomeAssistantError("Blink failed to arm camera away") from er raise HomeAssistantError("Blink failed to arm camera away") from er
await self.coordinator.async_refresh() await self.coordinator.async_refresh()

View file

@ -1,7 +1,6 @@
"""Support for Blink system camera.""" """Support for Blink system camera."""
from __future__ import annotations from __future__ import annotations
import asyncio
from collections.abc import Mapping from collections.abc import Mapping
import contextlib import contextlib
import logging import logging
@ -96,7 +95,7 @@ class BlinkCamera(CoordinatorEntity[BlinkUpdateCoordinator], Camera):
try: try:
await self._camera.async_arm(True) await self._camera.async_arm(True)
except asyncio.TimeoutError as er: except TimeoutError as er:
raise HomeAssistantError("Blink failed to arm camera") from er raise HomeAssistantError("Blink failed to arm camera") from er
self._camera.motion_enabled = True self._camera.motion_enabled = True
@ -106,7 +105,7 @@ class BlinkCamera(CoordinatorEntity[BlinkUpdateCoordinator], Camera):
"""Disable motion detection for the camera.""" """Disable motion detection for the camera."""
try: try:
await self._camera.async_arm(False) await self._camera.async_arm(False)
except asyncio.TimeoutError as er: except TimeoutError as er:
raise HomeAssistantError("Blink failed to disarm camera") from er raise HomeAssistantError("Blink failed to disarm camera") from er
self._camera.motion_enabled = False self._camera.motion_enabled = False
@ -124,7 +123,7 @@ class BlinkCamera(CoordinatorEntity[BlinkUpdateCoordinator], Camera):
async def trigger_camera(self) -> None: async def trigger_camera(self) -> None:
"""Trigger camera to take a snapshot.""" """Trigger camera to take a snapshot."""
with contextlib.suppress(asyncio.TimeoutError): with contextlib.suppress(TimeoutError):
await self._camera.snap_picture() await self._camera.snap_picture()
self.async_write_ha_state() self.async_write_ha_state()

View file

@ -1,7 +1,6 @@
"""Support for Blink Motion detection switches.""" """Support for Blink Motion detection switches."""
from __future__ import annotations from __future__ import annotations
import asyncio
from typing import Any from typing import Any
from homeassistant.components.switch import ( from homeassistant.components.switch import (
@ -74,7 +73,7 @@ class BlinkSwitch(CoordinatorEntity[BlinkUpdateCoordinator], SwitchEntity):
try: try:
await self._camera.async_arm(True) await self._camera.async_arm(True)
except asyncio.TimeoutError as er: except TimeoutError as er:
raise HomeAssistantError( raise HomeAssistantError(
"Blink failed to arm camera motion detection" "Blink failed to arm camera motion detection"
) from er ) from er
@ -86,7 +85,7 @@ class BlinkSwitch(CoordinatorEntity[BlinkUpdateCoordinator], SwitchEntity):
try: try:
await self._camera.async_arm(False) await self._camera.async_arm(False)
except asyncio.TimeoutError as er: except TimeoutError as er:
raise HomeAssistantError( raise HomeAssistantError(
"Blink failed to dis-arm camera motion detection" "Blink failed to dis-arm camera motion detection"
) from er ) from er

View file

@ -290,7 +290,7 @@ class BluesoundPlayer(MediaPlayerEntity):
while True: while True:
await self.async_update_status() await self.async_update_status()
except (asyncio.TimeoutError, ClientError, BluesoundPlayer._TimeoutException): except (TimeoutError, ClientError, BluesoundPlayer._TimeoutException):
_LOGGER.info("Node %s:%s is offline, retrying later", self.name, self.port) _LOGGER.info("Node %s:%s is offline, retrying later", self.name, self.port)
await asyncio.sleep(NODE_OFFLINE_CHECK_TIMEOUT) await asyncio.sleep(NODE_OFFLINE_CHECK_TIMEOUT)
self.start_polling() self.start_polling()
@ -317,7 +317,7 @@ class BluesoundPlayer(MediaPlayerEntity):
self._retry_remove = None self._retry_remove = None
await self.force_update_sync_status(self._init_callback, True) await self.force_update_sync_status(self._init_callback, True)
except (asyncio.TimeoutError, ClientError): except (TimeoutError, ClientError):
_LOGGER.info("Node %s:%s is offline, retrying later", self.host, self.port) _LOGGER.info("Node %s:%s is offline, retrying later", self.host, self.port)
self._retry_remove = async_track_time_interval( self._retry_remove = async_track_time_interval(
self._hass, self.async_init, NODE_RETRY_INITIATION self._hass, self.async_init, NODE_RETRY_INITIATION
@ -370,7 +370,7 @@ class BluesoundPlayer(MediaPlayerEntity):
_LOGGER.error("Error %s on %s", response.status, url) _LOGGER.error("Error %s on %s", response.status, url)
return None return None
except (asyncio.TimeoutError, aiohttp.ClientError): except (TimeoutError, aiohttp.ClientError):
if raise_timeout: if raise_timeout:
_LOGGER.info("Timeout: %s:%s", self.host, self.port) _LOGGER.info("Timeout: %s:%s", self.host, self.port)
raise raise
@ -437,7 +437,7 @@ class BluesoundPlayer(MediaPlayerEntity):
"Error %s on %s. Trying one more time", response.status, url "Error %s on %s. Trying one more time", response.status, url
) )
except (asyncio.TimeoutError, ClientError): except (TimeoutError, ClientError):
self._is_online = False self._is_online = False
self._last_status_update = None self._last_status_update = None
self._status = None self._status = None

View file

@ -1,7 +1,6 @@
"""Tracking for bluetooth low energy devices.""" """Tracking for bluetooth low energy devices."""
from __future__ import annotations from __future__ import annotations
import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
import logging import logging
from uuid import UUID from uuid import UUID
@ -155,7 +154,7 @@ async def async_setup_scanner( # noqa: C901
async with BleakClient(device) as client: async with BleakClient(device) as client:
bat_char = await client.read_gatt_char(BATTERY_CHARACTERISTIC_UUID) bat_char = await client.read_gatt_char(BATTERY_CHARACTERISTIC_UUID)
battery = ord(bat_char) battery = ord(bat_char)
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.debug( _LOGGER.debug(
"Timeout when trying to get battery status for %s", service_info.name "Timeout when trying to get battery status for %s", service_info.name
) )

View file

@ -1,7 +1,6 @@
"""Config flow for Bond integration.""" """Config flow for Bond integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
import contextlib import contextlib
from http import HTTPStatus from http import HTTPStatus
import logging import logging
@ -87,7 +86,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
try: try:
if not (token := await async_get_token(self.hass, host)): if not (token := await async_get_token(self.hass, host)):
return return
except asyncio.TimeoutError: except TimeoutError:
return return
self._discovered[CONF_ACCESS_TOKEN] = token self._discovered[CONF_ACCESS_TOKEN] = token

View file

@ -128,7 +128,7 @@ class BuienradarCam(Camera):
_LOGGER.debug("HTTP 200 - Last-Modified: %s", last_modified) _LOGGER.debug("HTTP 200 - Last-Modified: %s", last_modified)
return True return True
except (asyncio.TimeoutError, aiohttp.ClientError) as err: except (TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error("Failed to fetch image, %s", type(err)) _LOGGER.error("Failed to fetch image, %s", type(err))
return False return False

View file

@ -1,5 +1,4 @@
"""Shared utilities for different supported platforms.""" """Shared utilities for different supported platforms."""
import asyncio
from asyncio import timeout from asyncio import timeout
from datetime import datetime, timedelta from datetime import datetime, timedelta
from http import HTTPStatus from http import HTTPStatus
@ -104,7 +103,7 @@ class BrData:
result[MESSAGE] = "Got http statuscode: %d" % (resp.status) result[MESSAGE] = "Got http statuscode: %d" % (resp.status)
return result return result
except (asyncio.TimeoutError, aiohttp.ClientError) as err: except (TimeoutError, aiohttp.ClientError) as err:
result[MESSAGE] = str(err) result[MESSAGE] = str(err)
return result return result
finally: finally:

View file

@ -181,7 +181,7 @@ async def _async_get_image(
that we can scale, however the majority of cases that we can scale, however the majority of cases
are handled. are handled.
""" """
with suppress(asyncio.CancelledError, asyncio.TimeoutError): with suppress(asyncio.CancelledError, TimeoutError):
async with asyncio.timeout(timeout): async with asyncio.timeout(timeout):
image_bytes = ( image_bytes = (
await _async_get_stream_image( await _async_get_stream_image(
@ -891,7 +891,7 @@ async def ws_camera_stream(
except HomeAssistantError as ex: except HomeAssistantError as ex:
_LOGGER.error("Error requesting stream: %s", ex) _LOGGER.error("Error requesting stream: %s", ex)
connection.send_error(msg["id"], "start_stream_failed", str(ex)) connection.send_error(msg["id"], "start_stream_failed", str(ex))
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error("Timeout getting stream source") _LOGGER.error("Timeout getting stream source")
connection.send_error( connection.send_error(
msg["id"], "start_stream_failed", "Timeout getting stream source" msg["id"], "start_stream_failed", "Timeout getting stream source"
@ -936,7 +936,7 @@ async def ws_camera_web_rtc_offer(
except (HomeAssistantError, ValueError) as ex: except (HomeAssistantError, ValueError) as ex:
_LOGGER.error("Error handling WebRTC offer: %s", ex) _LOGGER.error("Error handling WebRTC offer: %s", ex)
connection.send_error(msg["id"], "web_rtc_offer_failed", str(ex)) connection.send_error(msg["id"], "web_rtc_offer_failed", str(ex))
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error("Timeout handling WebRTC offer") _LOGGER.error("Timeout handling WebRTC offer")
connection.send_error( connection.send_error(
msg["id"], "web_rtc_offer_failed", "Timeout handling WebRTC offer" msg["id"], "web_rtc_offer_failed", "Timeout handling WebRTC offer"

View file

@ -1,7 +1,6 @@
"""Helpers to deal with Cast devices.""" """Helpers to deal with Cast devices."""
from __future__ import annotations from __future__ import annotations
import asyncio
import configparser import configparser
from dataclasses import dataclass from dataclasses import dataclass
import logging import logging
@ -257,7 +256,7 @@ async def _fetch_playlist(hass, url, supported_content_types):
playlist_data = (await resp.content.read(64 * 1024)).decode(charset) playlist_data = (await resp.content.read(64 * 1024)).decode(charset)
except ValueError as err: except ValueError as err:
raise PlaylistError(f"Could not decode playlist {url}") from err raise PlaylistError(f"Could not decode playlist {url}") from err
except asyncio.TimeoutError as err: except TimeoutError as err:
raise PlaylistError(f"Timeout while fetching playlist {url}") from err raise PlaylistError(f"Timeout while fetching playlist {url}") from err
except aiohttp.client_exceptions.ClientError as err: except aiohttp.client_exceptions.ClientError as err:
raise PlaylistError(f"Error while fetching playlist {url}") from err raise PlaylistError(f"Error while fetching playlist {url}") from err

View file

@ -55,7 +55,7 @@ async def get_cert_expiry_timestamp(
cert = await async_get_cert(hass, hostname, port) cert = await async_get_cert(hass, hostname, port)
except socket.gaierror as err: except socket.gaierror as err:
raise ResolveFailed(f"Cannot resolve hostname: {hostname}") from err raise ResolveFailed(f"Cannot resolve hostname: {hostname}") from err
except asyncio.TimeoutError as err: except TimeoutError as err:
raise ConnectionTimeout( raise ConnectionTimeout(
f"Connection timeout with server: {hostname}:{port}" f"Connection timeout with server: {hostname}:{port}"
) from err ) from err

View file

@ -144,7 +144,7 @@ async def async_citybikes_request(hass, uri, schema):
json_response = await req.json() json_response = await req.json()
return schema(json_response) return schema(json_response)
except (asyncio.TimeoutError, aiohttp.ClientError): except (TimeoutError, aiohttp.ClientError):
_LOGGER.error("Could not connect to CityBikes API endpoint") _LOGGER.error("Could not connect to CityBikes API endpoint")
except ValueError: except ValueError:
_LOGGER.error("Received non-JSON data from CityBikes API endpoint") _LOGGER.error("Received non-JSON data from CityBikes API endpoint")

View file

@ -1,7 +1,6 @@
"""Account linking via the cloud.""" """Account linking via the cloud."""
from __future__ import annotations from __future__ import annotations
import asyncio
from datetime import datetime from datetime import datetime
import logging import logging
from typing import Any from typing import Any
@ -69,7 +68,7 @@ async def _get_services(hass: HomeAssistant) -> list[dict[str, Any]]:
try: try:
services = await account_link.async_fetch_available_services(hass.data[DOMAIN]) services = await account_link.async_fetch_available_services(hass.data[DOMAIN])
except (aiohttp.ClientError, asyncio.TimeoutError): except (aiohttp.ClientError, TimeoutError):
return [] return []
hass.data[DATA_SERVICES] = services hass.data[DATA_SERVICES] = services
@ -114,7 +113,7 @@ class CloudOAuth2Implementation(config_entry_oauth2_flow.AbstractOAuth2Implement
try: try:
tokens = await helper.async_get_tokens() tokens = await helper.async_get_tokens()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.info("Timeout fetching tokens for flow %s", flow_id) _LOGGER.info("Timeout fetching tokens for flow %s", flow_id)
except account_link.AccountLinkException as err: except account_link.AccountLinkException as err:
_LOGGER.info( _LOGGER.info(

View file

@ -505,7 +505,7 @@ class CloudAlexaConfig(alexa_config.AbstractConfig):
return True return True
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning("Timeout trying to sync entities to Alexa") _LOGGER.warning("Timeout trying to sync entities to Alexa")
return False return False

View file

@ -55,7 +55,7 @@ _LOGGER = logging.getLogger(__name__)
_CLOUD_ERRORS: dict[type[Exception], tuple[HTTPStatus, str]] = { _CLOUD_ERRORS: dict[type[Exception], tuple[HTTPStatus, str]] = {
asyncio.TimeoutError: ( TimeoutError: (
HTTPStatus.BAD_GATEWAY, HTTPStatus.BAD_GATEWAY,
"Unable to reach the Home Assistant cloud.", "Unable to reach the Home Assistant cloud.",
), ),
@ -429,7 +429,7 @@ async def websocket_update_prefs(
try: try:
async with asyncio.timeout(10): async with asyncio.timeout(10):
await alexa_config.async_get_access_token() await alexa_config.async_get_access_token()
except asyncio.TimeoutError: except TimeoutError:
connection.send_error( connection.send_error(
msg["id"], "alexa_timeout", "Timeout validating Alexa access token." msg["id"], "alexa_timeout", "Timeout validating Alexa access token."
) )

View file

@ -19,7 +19,7 @@ async def async_subscription_info(cloud: Cloud[CloudClient]) -> dict[str, Any] |
try: try:
async with asyncio.timeout(REQUEST_TIMEOUT): async with asyncio.timeout(REQUEST_TIMEOUT):
return await cloud_api.async_subscription_info(cloud) return await cloud_api.async_subscription_info(cloud)
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error( _LOGGER.error(
( (
"A timeout of %s was reached while trying to fetch subscription" "A timeout of %s was reached while trying to fetch subscription"
@ -40,7 +40,7 @@ async def async_migrate_paypal_agreement(
try: try:
async with asyncio.timeout(REQUEST_TIMEOUT): async with asyncio.timeout(REQUEST_TIMEOUT):
return await cloud_api.async_migrate_paypal_agreement(cloud) return await cloud_api.async_migrate_paypal_agreement(cloud)
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error( _LOGGER.error(
"A timeout of %s was reached while trying to start agreement migration", "A timeout of %s was reached while trying to start agreement migration",
REQUEST_TIMEOUT, REQUEST_TIMEOUT,

View file

@ -139,7 +139,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async with asyncio.timeout(10): async with asyncio.timeout(10):
response = await session.get(url) response = await session.get(url)
except (asyncio.TimeoutError, aiohttp.ClientError) as err: except (TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error("Failed to get ColorThief image due to HTTPError: %s", err) _LOGGER.error("Failed to get ColorThief image due to HTTPError: %s", err)
return None return None

View file

@ -123,7 +123,7 @@ class ComedHourlyPricingSensor(SensorEntity):
else: else:
self._attr_native_value = None self._attr_native_value = None
except (asyncio.TimeoutError, aiohttp.ClientError) as err: except (TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error("Could not get data from ComEd API: %s", err) _LOGGER.error("Could not get data from ComEd API: %s", err)
except (ValueError, KeyError): except (ValueError, KeyError):
_LOGGER.warning("Could not update status for %s", self.name) _LOGGER.warning("Could not update status for %s", self.name)

View file

@ -86,7 +86,7 @@ async def daikin_api_setup(
device = await Appliance.factory( device = await Appliance.factory(
host, session, key=key, uuid=uuid, password=password host, session, key=key, uuid=uuid, password=password
) )
except asyncio.TimeoutError as err: except TimeoutError as err:
_LOGGER.debug("Connection to %s timed out", host) _LOGGER.debug("Connection to %s timed out", host)
raise ConfigEntryNotReady from err raise ConfigEntryNotReady from err
except ClientConnectionError as err: except ClientConnectionError as err:

View file

@ -89,7 +89,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
uuid=uuid, uuid=uuid,
password=password, password=password,
) )
except (asyncio.TimeoutError, ClientError): except (TimeoutError, ClientError):
self.host = None self.host = None
return self.async_show_form( return self.async_show_form(
step_id="user", step_id="user",

View file

@ -103,7 +103,7 @@ class DeconzFlowHandler(ConfigFlow, domain=DOMAIN):
async with asyncio.timeout(10): async with asyncio.timeout(10):
self.bridges = await deconz_discovery(session) self.bridges = await deconz_discovery(session)
except (asyncio.TimeoutError, ResponseError): except (TimeoutError, ResponseError):
self.bridges = [] self.bridges = []
if LOGGER.isEnabledFor(logging.DEBUG): if LOGGER.isEnabledFor(logging.DEBUG):
@ -164,7 +164,7 @@ class DeconzFlowHandler(ConfigFlow, domain=DOMAIN):
except LinkButtonNotPressed: except LinkButtonNotPressed:
errors["base"] = "linking_not_possible" errors["base"] = "linking_not_possible"
except (ResponseError, RequestError, asyncio.TimeoutError): except (ResponseError, RequestError, TimeoutError):
errors["base"] = "no_key" errors["base"] = "no_key"
else: else:
@ -193,7 +193,7 @@ class DeconzFlowHandler(ConfigFlow, domain=DOMAIN):
} }
) )
except asyncio.TimeoutError: except TimeoutError:
return self.async_abort(reason="no_bridges") return self.async_abort(reason="no_bridges")
return self.async_create_entry( return self.async_create_entry(

View file

@ -360,6 +360,6 @@ async def get_deconz_session(
LOGGER.warning("Invalid key for deCONZ at %s", config[CONF_HOST]) LOGGER.warning("Invalid key for deCONZ at %s", config[CONF_HOST])
raise AuthenticationRequired from err raise AuthenticationRequired from err
except (asyncio.TimeoutError, errors.RequestError, errors.ResponseError) as err: except (TimeoutError, errors.RequestError, errors.ResponseError) as err:
LOGGER.error("Error connecting to deCONZ gateway at %s", config[CONF_HOST]) LOGGER.error("Error connecting to deCONZ gateway at %s", config[CONF_HOST])
raise CannotConnect from err raise CannotConnect from err

View file

@ -108,7 +108,7 @@ class DoorBirdCamera(DoorBirdEntity, Camera):
self._last_image = await response.read() self._last_image = await response.read()
self._last_update = now self._last_update = now
return self._last_image return self._last_image
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error("DoorBird %s: Camera image timed out", self.name) _LOGGER.error("DoorBird %s: Camera image timed out", self.name)
return self._last_image return self._last_image
except aiohttp.ClientError as error: except aiohttp.ClientError as error:

View file

@ -123,7 +123,7 @@ class DSMRConnection:
try: try:
async with asyncio.timeout(30): async with asyncio.timeout(30):
await protocol.wait_closed() await protocol.wait_closed()
except asyncio.TimeoutError: except TimeoutError:
# Timeout (no data received), close transport and return True (if telegram is empty, will result in CannotCommunicate error) # Timeout (no data received), close transport and return True (if telegram is empty, will result in CannotCommunicate error)
transport.close() transport.close()
await protocol.wait_closed() await protocol.wait_closed()

View file

@ -1,5 +1,4 @@
"""The tests for the analytics .""" """The tests for the analytics ."""
import asyncio
from typing import Any from typing import Any
from unittest.mock import ANY, AsyncMock, Mock, PropertyMock, patch from unittest.mock import ANY, AsyncMock, Mock, PropertyMock, patch
@ -756,7 +755,7 @@ async def test_timeout_while_sending(
) -> None: ) -> None:
"""Test timeout error while sending analytics.""" """Test timeout error while sending analytics."""
analytics = Analytics(hass) analytics = Analytics(hass)
aioclient_mock.post(ANALYTICS_ENDPOINT_URL_DEV, exc=asyncio.TimeoutError()) aioclient_mock.post(ANALYTICS_ENDPOINT_URL_DEV, exc=TimeoutError())
await analytics.save_preferences({ATTR_BASE: True}) await analytics.save_preferences({ATTR_BASE: True})
with patch( with patch(

View file

@ -1,5 +1,4 @@
"""The tests for the august platform.""" """The tests for the august platform."""
import asyncio
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from aiohttp import ClientResponseError from aiohttp import ClientResponseError
@ -68,7 +67,7 @@ async def test_august_is_offline(hass: HomeAssistant) -> None:
with patch( with patch(
"yalexs.authenticator_async.AuthenticatorAsync.async_authenticate", "yalexs.authenticator_async.AuthenticatorAsync.async_authenticate",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -1,5 +1,4 @@
"""Test the baf config flow.""" """Test the baf config flow."""
import asyncio
from ipaddress import ip_address from ipaddress import ip_address
from unittest.mock import patch from unittest.mock import patch
@ -55,7 +54,7 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
) )
with _patch_device_config_flow(asyncio.TimeoutError): with _patch_device_config_flow(TimeoutError):
result2 = await hass.config_entries.flow.async_configure( result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], result["flow_id"],
{CONF_IP_ADDRESS: "127.0.0.1"}, {CONF_IP_ADDRESS: "127.0.0.1"},

View file

@ -1,5 +1,4 @@
"""Test the Blink init.""" """Test the Blink init."""
import asyncio
from unittest.mock import AsyncMock, MagicMock from unittest.mock import AsyncMock, MagicMock
from aiohttp import ClientError from aiohttp import ClientError
@ -23,7 +22,7 @@ PIN = "1234"
@pytest.mark.parametrize( @pytest.mark.parametrize(
("the_error", "available"), ("the_error", "available"),
[(ClientError, False), (asyncio.TimeoutError, False), (None, False)], [(ClientError, False), (TimeoutError, False), (None, False)],
) )
async def test_setup_not_ready( async def test_setup_not_ready(
hass: HomeAssistant, hass: HomeAssistant,

View file

@ -2294,7 +2294,7 @@ async def test_process_advertisements_timeout(
def _callback(service_info: BluetoothServiceInfo) -> bool: def _callback(service_info: BluetoothServiceInfo) -> bool:
return False return False
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
await async_process_advertisements( await async_process_advertisements(
hass, _callback, {}, BluetoothScanningMode.ACTIVE, 0 hass, _callback, {}, BluetoothScanningMode.ACTIVE, 0
) )

View file

@ -1,5 +1,4 @@
"""Test Bluetooth LE device tracker.""" """Test Bluetooth LE device tracker."""
import asyncio
from datetime import timedelta from datetime import timedelta
from unittest.mock import patch from unittest.mock import patch
@ -47,7 +46,7 @@ class MockBleakClientTimesOut(MockBleakClient):
async def read_gatt_char(self, *args, **kwargs): async def read_gatt_char(self, *args, **kwargs):
"""Mock BleakClient.read_gatt_char.""" """Mock BleakClient.read_gatt_char."""
raise asyncio.TimeoutError raise TimeoutError
class MockBleakClientFailing(MockBleakClient): class MockBleakClientFailing(MockBleakClient):

View file

@ -1,7 +1,6 @@
"""Test the Bond config flow.""" """Test the Bond config flow."""
from __future__ import annotations from __future__ import annotations
import asyncio
from http import HTTPStatus from http import HTTPStatus
from ipaddress import ip_address from ipaddress import ip_address
from typing import Any from typing import Any
@ -274,7 +273,7 @@ async def test_zeroconf_form_token_unavailable(hass: HomeAssistant) -> None:
async def test_zeroconf_form_token_times_out(hass: HomeAssistant) -> None: async def test_zeroconf_form_token_times_out(hass: HomeAssistant) -> None:
"""Test we get the discovery form and we handle the token request timeout.""" """Test we get the discovery form and we handle the token request timeout."""
with patch_bond_version(), patch_bond_token(side_effect=asyncio.TimeoutError): with patch_bond_version(), patch_bond_token(side_effect=TimeoutError):
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
context={"source": config_entries.SOURCE_ZEROCONF}, context={"source": config_entries.SOURCE_ZEROCONF},

View file

@ -1,5 +1,4 @@
"""Tests for the Bond entities.""" """Tests for the Bond entities."""
import asyncio
from datetime import timedelta from datetime import timedelta
from unittest.mock import patch from unittest.mock import patch
@ -85,7 +84,7 @@ async def test_bpup_goes_offline_and_recovers_same_entity(hass: HomeAssistant) -
assert hass.states.get("fan.name_1").attributes[fan.ATTR_PERCENTAGE] == 33 assert hass.states.get("fan.name_1").attributes[fan.ATTR_PERCENTAGE] == 33
bpup_subs.last_message_time = -BPUP_ALIVE_TIMEOUT bpup_subs.last_message_time = -BPUP_ALIVE_TIMEOUT
with patch_bond_device_state(side_effect=asyncio.TimeoutError): with patch_bond_device_state(side_effect=TimeoutError):
async_fire_time_changed(hass, utcnow() + timedelta(seconds=230)) async_fire_time_changed(hass, utcnow() + timedelta(seconds=230))
await hass.async_block_till_done() await hass.async_block_till_done()
@ -147,7 +146,7 @@ async def test_bpup_goes_offline_and_recovers_different_entity(
assert hass.states.get("fan.name_1").attributes[fan.ATTR_PERCENTAGE] == 33 assert hass.states.get("fan.name_1").attributes[fan.ATTR_PERCENTAGE] == 33
bpup_subs.last_message_time = -BPUP_ALIVE_TIMEOUT bpup_subs.last_message_time = -BPUP_ALIVE_TIMEOUT
with patch_bond_device_state(side_effect=asyncio.TimeoutError): with patch_bond_device_state(side_effect=TimeoutError):
async_fire_time_changed(hass, utcnow() + timedelta(seconds=230)) async_fire_time_changed(hass, utcnow() + timedelta(seconds=230))
await hass.async_block_till_done() await hass.async_block_till_done()
@ -178,7 +177,7 @@ async def test_polling_fails_and_recovers(hass: HomeAssistant) -> None:
hass, FAN_DOMAIN, ceiling_fan("name-1"), bond_device_id="test-device-id" hass, FAN_DOMAIN, ceiling_fan("name-1"), bond_device_id="test-device-id"
) )
with patch_bond_device_state(side_effect=asyncio.TimeoutError): with patch_bond_device_state(side_effect=TimeoutError):
async_fire_time_changed(hass, utcnow() + timedelta(seconds=230)) async_fire_time_changed(hass, utcnow() + timedelta(seconds=230))
await hass.async_block_till_done() await hass.async_block_till_done()
@ -199,7 +198,7 @@ async def test_polling_stops_at_the_stop_event(hass: HomeAssistant) -> None:
hass, FAN_DOMAIN, ceiling_fan("name-1"), bond_device_id="test-device-id" hass, FAN_DOMAIN, ceiling_fan("name-1"), bond_device_id="test-device-id"
) )
with patch_bond_device_state(side_effect=asyncio.TimeoutError): with patch_bond_device_state(side_effect=TimeoutError):
async_fire_time_changed(hass, utcnow() + timedelta(seconds=230)) async_fire_time_changed(hass, utcnow() + timedelta(seconds=230))
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -1,5 +1,4 @@
"""Tests for the Bond module.""" """Tests for the Bond module."""
import asyncio
from unittest.mock import MagicMock, Mock from unittest.mock import MagicMock, Mock
from aiohttp import ClientConnectionError, ClientResponseError from aiohttp import ClientConnectionError, ClientResponseError
@ -45,7 +44,7 @@ async def test_async_setup_no_domain_config(hass: HomeAssistant) -> None:
[ [
ClientConnectionError, ClientConnectionError,
ClientResponseError(MagicMock(), MagicMock(), status=404), ClientResponseError(MagicMock(), MagicMock(), status=404),
asyncio.TimeoutError, TimeoutError,
OSError, OSError,
], ],
) )

View file

@ -1,5 +1,4 @@
"""The tests for the camera component.""" """The tests for the camera component."""
import asyncio
from http import HTTPStatus from http import HTTPStatus
import io import io
from types import ModuleType from types import ModuleType
@ -204,7 +203,7 @@ async def test_get_image_with_timeout(hass: HomeAssistant, image_mock_url) -> No
"""Try to get image with timeout.""" """Try to get image with timeout."""
with patch( with patch(
"homeassistant.components.demo.camera.DemoCamera.async_camera_image", "homeassistant.components.demo.camera.DemoCamera.async_camera_image",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
), pytest.raises(HomeAssistantError): ), pytest.raises(HomeAssistantError):
await camera.async_get_image(hass, "camera.demo_camera") await camera.async_get_image(hass, "camera.demo_camera")
@ -670,7 +669,7 @@ async def test_websocket_web_rtc_offer_timeout(
with patch( with patch(
"homeassistant.components.camera.Camera.async_handle_web_rtc_offer", "homeassistant.components.camera.Camera.async_handle_web_rtc_offer",
side_effect=asyncio.TimeoutError(), side_effect=TimeoutError(),
): ):
await client.send_json( await client.send_json(
{ {

View file

@ -1,5 +1,4 @@
"""Tests for the Cast integration helpers.""" """Tests for the Cast integration helpers."""
import asyncio
from aiohttp import client_exceptions from aiohttp import client_exceptions
import pytest import pytest
@ -141,7 +140,7 @@ async def test_parse_bad_playlist(
@pytest.mark.parametrize( @pytest.mark.parametrize(
("url", "exc"), ("url", "exc"),
( (
("http://sverigesradio.se/164-hi-aac.pls", asyncio.TimeoutError), ("http://sverigesradio.se/164-hi-aac.pls", TimeoutError),
("http://sverigesradio.se/164-hi-aac.pls", client_exceptions.ClientError), ("http://sverigesradio.se/164-hi-aac.pls", client_exceptions.ClientError),
), ),
) )

View file

@ -1,5 +1,4 @@
"""Tests for the Cert Expiry config flow.""" """Tests for the Cert Expiry config flow."""
import asyncio
import socket import socket
import ssl import ssl
from unittest.mock import patch from unittest.mock import patch
@ -210,7 +209,7 @@ async def test_abort_on_socket_failed(hass: HomeAssistant) -> None:
with patch( with patch(
"homeassistant.components.cert_expiry.helper.async_get_cert", "homeassistant.components.cert_expiry.helper.async_get_cert",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
result = await hass.config_entries.flow.async_configure( result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: HOST} result["flow_id"], user_input={CONF_HOST: HOST}

View file

@ -160,7 +160,7 @@ async def test_get_services_error(hass: HomeAssistant) -> None:
with patch.object(account_link, "CACHE_TIMEOUT", 0), patch( with patch.object(account_link, "CACHE_TIMEOUT", 0), patch(
"hass_nabucasa.account_link.async_fetch_available_services", "hass_nabucasa.account_link.async_fetch_available_services",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
assert await account_link._get_services(hass) == [] assert await account_link._get_services(hass) == []
assert account_link.DATA_SERVICES not in hass.data assert account_link.DATA_SERVICES not in hass.data

View file

@ -1,5 +1,4 @@
"""Tests for the HTTP API for the cloud component.""" """Tests for the HTTP API for the cloud component."""
import asyncio
from copy import deepcopy from copy import deepcopy
from http import HTTPStatus from http import HTTPStatus
from typing import Any from typing import Any
@ -346,7 +345,7 @@ async def test_login_view_request_timeout(
) -> None: ) -> None:
"""Test request timeout while trying to log in.""" """Test request timeout while trying to log in."""
cloud_client = await hass_client() cloud_client = await hass_client()
cloud.login.side_effect = asyncio.TimeoutError cloud.login.side_effect = TimeoutError
req = await cloud_client.post( req = await cloud_client.post(
"/api/cloud/login", json={"email": "my_username", "password": "my_password"} "/api/cloud/login", json={"email": "my_username", "password": "my_password"}
@ -409,7 +408,7 @@ async def test_logout_view_request_timeout(
) -> None: ) -> None:
"""Test timeout while logging out.""" """Test timeout while logging out."""
cloud_client = await hass_client() cloud_client = await hass_client()
cloud.logout.side_effect = asyncio.TimeoutError cloud.logout.side_effect = TimeoutError
req = await cloud_client.post("/api/cloud/logout") req = await cloud_client.post("/api/cloud/logout")
@ -524,7 +523,7 @@ async def test_register_view_request_timeout(
) -> None: ) -> None:
"""Test timeout while registering.""" """Test timeout while registering."""
cloud_client = await hass_client() cloud_client = await hass_client()
cloud.auth.async_register.side_effect = asyncio.TimeoutError cloud.auth.async_register.side_effect = TimeoutError
req = await cloud_client.post( req = await cloud_client.post(
"/api/cloud/register", json={"email": "hello@bla.com", "password": "falcon42"} "/api/cloud/register", json={"email": "hello@bla.com", "password": "falcon42"}
@ -590,7 +589,7 @@ async def test_forgot_password_view_request_timeout(
) -> None: ) -> None:
"""Test timeout while forgot password.""" """Test timeout while forgot password."""
cloud_client = await hass_client() cloud_client = await hass_client()
cloud.auth.async_forgot_password.side_effect = asyncio.TimeoutError cloud.auth.async_forgot_password.side_effect = TimeoutError
req = await cloud_client.post( req = await cloud_client.post(
"/api/cloud/forgot_password", json={"email": "hello@bla.com"} "/api/cloud/forgot_password", json={"email": "hello@bla.com"}
@ -674,7 +673,7 @@ async def test_resend_confirm_view_request_timeout(
) -> None: ) -> None:
"""Test timeout while resend confirm.""" """Test timeout while resend confirm."""
cloud_client = await hass_client() cloud_client = await hass_client()
cloud.auth.async_resend_email_confirm.side_effect = asyncio.TimeoutError cloud.auth.async_resend_email_confirm.side_effect = TimeoutError
req = await cloud_client.post( req = await cloud_client.post(
"/api/cloud/resend_confirm", json={"email": "hello@bla.com"} "/api/cloud/resend_confirm", json={"email": "hello@bla.com"}
@ -1400,7 +1399,7 @@ async def test_sync_alexa_entities_timeout(
"homeassistant.components.cloud.alexa_config.CloudAlexaConfig" "homeassistant.components.cloud.alexa_config.CloudAlexaConfig"
".async_sync_entities" ".async_sync_entities"
), ),
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
await client.send_json({"id": 5, "type": "cloud/alexa/sync"}) await client.send_json({"id": 5, "type": "cloud/alexa/sync"})
response = await client.receive_json() response = await client.receive_json()
@ -1484,7 +1483,7 @@ async def test_thingtalk_convert_timeout(
with patch( with patch(
"homeassistant.components.cloud.http_api.thingtalk.async_convert", "homeassistant.components.cloud.http_api.thingtalk.async_convert",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
await client.send_json( await client.send_json(
{"id": 5, "type": "cloud/thingtalk/convert", "query": "some-data"} {"id": 5, "type": "cloud/thingtalk/convert", "query": "some-data"}

View file

@ -1,5 +1,4 @@
"""Test cloud subscription functions.""" """Test cloud subscription functions."""
import asyncio
from unittest.mock import AsyncMock, Mock from unittest.mock import AsyncMock, Mock
from hass_nabucasa import Cloud from hass_nabucasa import Cloud
@ -33,7 +32,7 @@ async def test_fetching_subscription_with_timeout_error(
"""Test that we handle timeout error.""" """Test that we handle timeout error."""
aioclient_mock.get( aioclient_mock.get(
"https://accounts.nabucasa.com/payments/subscription_info", "https://accounts.nabucasa.com/payments/subscription_info",
exc=asyncio.TimeoutError(), exc=TimeoutError(),
) )
assert await async_subscription_info(mocked_cloud) is None assert await async_subscription_info(mocked_cloud) is None
@ -51,7 +50,7 @@ async def test_migrate_paypal_agreement_with_timeout_error(
"""Test that we handle timeout error.""" """Test that we handle timeout error."""
aioclient_mock.post( aioclient_mock.post(
"https://accounts.nabucasa.com/payments/migrate_paypal_agreement", "https://accounts.nabucasa.com/payments/migrate_paypal_agreement",
exc=asyncio.TimeoutError(), exc=TimeoutError(),
) )
assert await async_migrate_paypal_agreement(mocked_cloud) is None assert await async_migrate_paypal_agreement(mocked_cloud) is None

View file

@ -1,5 +1,4 @@
"""Tests for the Daikin config flow.""" """Tests for the Daikin config flow."""
import asyncio
from ipaddress import ip_address from ipaddress import ip_address
from unittest.mock import PropertyMock, patch from unittest.mock import PropertyMock, patch
@ -81,7 +80,7 @@ async def test_abort_if_already_setup(hass: HomeAssistant, mock_daikin) -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
("s_effect", "reason"), ("s_effect", "reason"),
[ [
(asyncio.TimeoutError, "cannot_connect"), (TimeoutError, "cannot_connect"),
(ClientError, "cannot_connect"), (ClientError, "cannot_connect"),
(web_exceptions.HTTPForbidden, "invalid_auth"), (web_exceptions.HTTPForbidden, "invalid_auth"),
(DaikinException, "unknown"), (DaikinException, "unknown"),

View file

@ -1,5 +1,4 @@
"""Define tests for the Daikin init.""" """Define tests for the Daikin init."""
import asyncio
from datetime import timedelta from datetime import timedelta
from unittest.mock import AsyncMock, PropertyMock, patch from unittest.mock import AsyncMock, PropertyMock, patch
@ -224,7 +223,7 @@ async def test_timeout_error(hass: HomeAssistant, mock_daikin) -> None:
) )
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
mock_daikin.factory.side_effect = asyncio.TimeoutError mock_daikin.factory.side_effect = TimeoutError
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -1,5 +1,4 @@
"""Tests for deCONZ config flow.""" """Tests for deCONZ config flow."""
import asyncio
import logging import logging
from unittest.mock import patch from unittest.mock import patch
@ -195,7 +194,7 @@ async def test_manual_configuration_after_discovery_timeout(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test failed discovery fallbacks to manual configuration.""" """Test failed discovery fallbacks to manual configuration."""
aioclient_mock.get(pydeconz.utils.URL_DISCOVER, exc=asyncio.TimeoutError) aioclient_mock.get(pydeconz.utils.URL_DISCOVER, exc=TimeoutError)
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DECONZ_DOMAIN, context={"source": SOURCE_USER} DECONZ_DOMAIN, context={"source": SOURCE_USER}
@ -347,9 +346,7 @@ async def test_manual_configuration_timeout_get_bridge(
headers={"content-type": CONTENT_TYPE_JSON}, headers={"content-type": CONTENT_TYPE_JSON},
) )
aioclient_mock.get( aioclient_mock.get(f"http://1.2.3.4:80/api/{API_KEY}/config", exc=TimeoutError)
f"http://1.2.3.4:80/api/{API_KEY}/config", exc=asyncio.TimeoutError
)
result = await hass.config_entries.flow.async_configure( result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={} result["flow_id"], user_input={}
@ -363,7 +360,7 @@ async def test_manual_configuration_timeout_get_bridge(
("raised_error", "error_string"), ("raised_error", "error_string"),
[ [
(pydeconz.errors.LinkButtonNotPressed, "linking_not_possible"), (pydeconz.errors.LinkButtonNotPressed, "linking_not_possible"),
(asyncio.TimeoutError, "no_key"), (TimeoutError, "no_key"),
(pydeconz.errors.ResponseError, "no_key"), (pydeconz.errors.ResponseError, "no_key"),
(pydeconz.errors.RequestError, "no_key"), (pydeconz.errors.RequestError, "no_key"),
], ],

View file

@ -1,5 +1,4 @@
"""Test deCONZ gateway.""" """Test deCONZ gateway."""
import asyncio
from copy import deepcopy from copy import deepcopy
from unittest.mock import patch from unittest.mock import patch
@ -297,7 +296,7 @@ async def test_get_deconz_session(hass: HomeAssistant) -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
("side_effect", "raised_exception"), ("side_effect", "raised_exception"),
[ [
(asyncio.TimeoutError, CannotConnect), (TimeoutError, CannotConnect),
(pydeconz.RequestError, CannotConnect), (pydeconz.RequestError, CannotConnect),
(pydeconz.ResponseError, CannotConnect), (pydeconz.ResponseError, CannotConnect),
(pydeconz.Unauthorized, AuthenticationRequired), (pydeconz.Unauthorized, AuthenticationRequired),

View file

@ -1,5 +1,4 @@
"""Test the DSMR config flow.""" """Test the DSMR config flow."""
import asyncio
from itertools import chain, repeat from itertools import chain, repeat
import os import os
from typing import Any from typing import Any
@ -388,13 +387,13 @@ async def test_setup_serial_timeout(
first_timeout_wait_closed = AsyncMock( first_timeout_wait_closed = AsyncMock(
return_value=True, return_value=True,
side_effect=chain([asyncio.TimeoutError], repeat(DEFAULT)), side_effect=chain([TimeoutError], repeat(DEFAULT)),
) )
protocol.wait_closed = first_timeout_wait_closed protocol.wait_closed = first_timeout_wait_closed
first_timeout_wait_closed = AsyncMock( first_timeout_wait_closed = AsyncMock(
return_value=True, return_value=True,
side_effect=chain([asyncio.TimeoutError], repeat(DEFAULT)), side_effect=chain([TimeoutError], repeat(DEFAULT)),
) )
rfxtrx_protocol.wait_closed = first_timeout_wait_closed rfxtrx_protocol.wait_closed = first_timeout_wait_closed