Use builtin TimeoutError [o-s] (#109682)

This commit is contained in:
Marc Mueller 2024-02-05 12:14:37 +01:00 committed by GitHub
parent cd0ee98dba
commit 438d3b01b9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
94 changed files with 117 additions and 169 deletions

View file

@ -1,6 +1,5 @@
"""Constants for the Oncue integration.""" """Constants for the Oncue integration."""
import asyncio
import aiohttp import aiohttp
from aiooncue import ServiceFailedException from aiooncue import ServiceFailedException
@ -8,7 +7,7 @@ from aiooncue import ServiceFailedException
DOMAIN = "oncue" DOMAIN = "oncue"
CONNECTION_EXCEPTIONS = ( CONNECTION_EXCEPTIONS = (
asyncio.TimeoutError, TimeoutError,
aiohttp.ClientError, aiohttp.ClientError,
ServiceFailedException, ServiceFailedException,
) )

View file

@ -197,7 +197,7 @@ class ONVIFCameraEntity(ONVIFBaseEntity, Camera):
self._stream_uri_future = loop.create_future() self._stream_uri_future = loop.create_future()
try: try:
uri_no_auth = await self.device.async_get_stream_uri(self.profile) uri_no_auth = await self.device.async_get_stream_uri(self.profile)
except (asyncio.TimeoutError, Exception) as err: except (TimeoutError, Exception) as err:
LOGGER.error("Failed to get stream uri: %s", err) LOGGER.error("Failed to get stream uri: %s", err)
if self._stream_uri_future: if self._stream_uri_future:
self._stream_uri_future.set_exception(err) self._stream_uri_future.set_exception(err)

View file

@ -32,7 +32,7 @@ from .parsers import PARSERS
# entities for them. # entities for them.
UNHANDLED_TOPICS: set[str] = {"tns1:MediaControl/VideoEncoderConfiguration"} UNHANDLED_TOPICS: set[str] = {"tns1:MediaControl/VideoEncoderConfiguration"}
SUBSCRIPTION_ERRORS = (Fault, asyncio.TimeoutError, TransportError) SUBSCRIPTION_ERRORS = (Fault, TimeoutError, TransportError)
CREATE_ERRORS = (ONVIFError, Fault, RequestError, XMLParseError, ValidationError) CREATE_ERRORS = (ONVIFError, Fault, RequestError, XMLParseError, ValidationError)
SET_SYNCHRONIZATION_POINT_ERRORS = (*SUBSCRIPTION_ERRORS, TypeError) SET_SYNCHRONIZATION_POINT_ERRORS = (*SUBSCRIPTION_ERRORS, TypeError)
UNSUBSCRIBE_ERRORS = (XMLParseError, *SUBSCRIPTION_ERRORS) UNSUBSCRIBE_ERRORS = (XMLParseError, *SUBSCRIPTION_ERRORS)

View file

@ -209,7 +209,7 @@ class OpenAlprCloudEntity(ImageProcessingAlprEntity):
_LOGGER.error("Error %d -> %s", request.status, data.get("error")) _LOGGER.error("Error %d -> %s", request.status, data.get("error"))
return return
except (asyncio.TimeoutError, aiohttp.ClientError): except (TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout for OpenALPR API") _LOGGER.error("Timeout for OpenALPR API")
return return

View file

@ -81,7 +81,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors["base"] = "invalid_auth" errors["base"] = "invalid_auth"
except OpenExchangeRatesClientError: except OpenExchangeRatesClientError:
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
except asyncio.TimeoutError: except TimeoutError:
errors["base"] = "timeout_connect" errors["base"] = "timeout_connect"
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
LOGGER.exception("Unexpected exception") LOGGER.exception("Unexpected exception")
@ -126,6 +126,6 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self.currencies = await client.get_currencies() self.currencies = await client.get_currencies()
except OpenExchangeRatesClientError as err: except OpenExchangeRatesClientError as err:
raise AbortFlow("cannot_connect") from err raise AbortFlow("cannot_connect") from err
except asyncio.TimeoutError as err: except TimeoutError as err:
raise AbortFlow("timeout_connect") from err raise AbortFlow("timeout_connect") from err
return self.currencies return self.currencies

View file

@ -1,6 +1,5 @@
"""The openhome component.""" """The openhome component."""
import asyncio
import logging import logging
import aiohttp import aiohttp
@ -43,7 +42,7 @@ async def async_setup_entry(
try: try:
await device.init() await device.init()
except (asyncio.TimeoutError, aiohttp.ClientError, UpnpError) as exc: except (TimeoutError, aiohttp.ClientError, UpnpError) as exc:
raise ConfigEntryNotReady from exc raise ConfigEntryNotReady from exc
_LOGGER.debug("Initialised device: %s", device.uuid()) _LOGGER.debug("Initialised device: %s", device.uuid())

View file

@ -1,7 +1,6 @@
"""Support for Openhome Devices.""" """Support for Openhome Devices."""
from __future__ import annotations from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Coroutine from collections.abc import Awaitable, Callable, Coroutine
import functools import functools
import logging import logging
@ -76,7 +75,7 @@ def catch_request_errors() -> (
[_FuncType[_OpenhomeDeviceT, _P, _R]], _ReturnFuncType[_OpenhomeDeviceT, _P, _R] [_FuncType[_OpenhomeDeviceT, _P, _R]], _ReturnFuncType[_OpenhomeDeviceT, _P, _R]
] ]
): ):
"""Catch asyncio.TimeoutError, aiohttp.ClientError, UpnpError errors.""" """Catch TimeoutError, aiohttp.ClientError, UpnpError errors."""
def call_wrapper( def call_wrapper(
func: _FuncType[_OpenhomeDeviceT, _P, _R], func: _FuncType[_OpenhomeDeviceT, _P, _R],
@ -87,10 +86,10 @@ def catch_request_errors() -> (
async def wrapper( async def wrapper(
self: _OpenhomeDeviceT, *args: _P.args, **kwargs: _P.kwargs self: _OpenhomeDeviceT, *args: _P.args, **kwargs: _P.kwargs
) -> _R | None: ) -> _R | None:
"""Catch asyncio.TimeoutError, aiohttp.ClientError, UpnpError errors.""" """Catch TimeoutError, aiohttp.ClientError, UpnpError errors."""
try: try:
return await func(self, *args, **kwargs) return await func(self, *args, **kwargs)
except (asyncio.TimeoutError, aiohttp.ClientError, UpnpError): except (TimeoutError, aiohttp.ClientError, UpnpError):
_LOGGER.error("Error during call %s", func.__name__) _LOGGER.error("Error during call %s", func.__name__)
return None return None
@ -186,7 +185,7 @@ class OpenhomeDevice(MediaPlayerEntity):
self._attr_state = MediaPlayerState.PLAYING self._attr_state = MediaPlayerState.PLAYING
self._attr_available = True self._attr_available = True
except (asyncio.TimeoutError, aiohttp.ClientError, UpnpError): except (TimeoutError, aiohttp.ClientError, UpnpError):
self._attr_available = False self._attr_available = False
@catch_request_errors() @catch_request_errors()

View file

@ -1,7 +1,6 @@
"""Update entities for Linn devices.""" """Update entities for Linn devices."""
from __future__ import annotations from __future__ import annotations
import asyncio
import logging import logging
from typing import Any from typing import Any
@ -93,7 +92,7 @@ class OpenhomeUpdateEntity(UpdateEntity):
try: try:
if self.latest_version: if self.latest_version:
await self._device.update_firmware() await self._device.update_firmware()
except (asyncio.TimeoutError, aiohttp.ClientError, UpnpError) as err: except (TimeoutError, aiohttp.ClientError, UpnpError) as err:
raise HomeAssistantError( raise HomeAssistantError(
f"Error updating {self._device.device.friendly_name}: {err}" f"Error updating {self._device.device.friendly_name}: {err}"
) from err ) from err

View file

@ -114,7 +114,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
try: try:
async with asyncio.timeout(CONNECTION_TIMEOUT): async with asyncio.timeout(CONNECTION_TIMEOUT):
await gateway.connect_and_subscribe() await gateway.connect_and_subscribe()
except (asyncio.TimeoutError, ConnectionError, SerialException) as ex: except (TimeoutError, ConnectionError, SerialException) as ex:
await gateway.cleanup() await gateway.cleanup()
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"Could not connect to gateway at {gateway.device_path}: {ex}" f"Could not connect to gateway at {gateway.device_path}: {ex}"

View file

@ -70,7 +70,7 @@ class OpenThermGwConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
try: try:
async with asyncio.timeout(CONNECTION_TIMEOUT): async with asyncio.timeout(CONNECTION_TIMEOUT):
await test_connection() await test_connection()
except asyncio.TimeoutError: except TimeoutError:
return self._show_form({"base": "timeout_connect"}) return self._show_form({"base": "timeout_connect"})
except (ConnectionError, SerialException): except (ConnectionError, SerialException):
return self._show_form({"base": "cannot_connect"}) return self._show_form({"base": "cannot_connect"})

View file

@ -1,8 +1,6 @@
"""The Open Thread Border Router integration.""" """The Open Thread Border Router integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
import aiohttp import aiohttp
import python_otbr_api import python_otbr_api
@ -42,7 +40,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
except ( except (
HomeAssistantError, HomeAssistantError,
aiohttp.ClientError, aiohttp.ClientError,
asyncio.TimeoutError, TimeoutError,
) as err: ) as err:
raise ConfigEntryNotReady("Unable to connect") from err raise ConfigEntryNotReady("Unable to connect") from err
if border_agent_id is None: if border_agent_id is None:

View file

@ -1,7 +1,6 @@
"""Config flow for the Open Thread Border Router integration.""" """Config flow for the Open Thread Border Router integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
from contextlib import suppress from contextlib import suppress
import logging import logging
from typing import cast from typing import cast
@ -115,7 +114,7 @@ class OTBRConfigFlow(ConfigFlow, domain=DOMAIN):
except ( except (
python_otbr_api.OTBRError, python_otbr_api.OTBRError,
aiohttp.ClientError, aiohttp.ClientError,
asyncio.TimeoutError, TimeoutError,
): ):
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
else: else:

View file

@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio
import logging import logging
import aiohttp import aiohttp
@ -64,7 +63,7 @@ async def async_get_channel(hass: HomeAssistant) -> int | None:
except ( except (
HomeAssistantError, HomeAssistantError,
aiohttp.ClientError, aiohttp.ClientError,
asyncio.TimeoutError, TimeoutError,
) as err: ) as err:
_LOGGER.warning("Failed to communicate with OTBR %s", err) _LOGGER.warning("Failed to communicate with OTBR %s", err)
return None return None

View file

@ -42,7 +42,7 @@ class PicnicUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self) -> dict: async def _async_update_data(self) -> dict:
"""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):
data = await self.hass.async_add_executor_job(self.fetch_data) data = await self.hass.async_add_executor_job(self.fetch_data)

View file

@ -141,7 +141,7 @@ class PingDataSubProcess(PingData):
assert match is not None assert match is not None
rtt_min, rtt_avg, rtt_max, rtt_mdev = match.groups() rtt_min, rtt_avg, rtt_max, rtt_mdev = match.groups()
return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": rtt_mdev} return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": rtt_mdev}
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.exception( _LOGGER.exception(
"Timed out running command: `%s`, after: %ss", "Timed out running command: `%s`, after: %ss",
self._ping_cmd, self._ping_cmd,

View file

@ -95,7 +95,7 @@ class PointFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
try: try:
async with asyncio.timeout(10): async with asyncio.timeout(10):
url = await self._get_authorization_url() url = await self._get_authorization_url()
except asyncio.TimeoutError: except TimeoutError:
return self.async_abort(reason="authorize_url_timeout") return self.async_abort(reason="authorize_url_timeout")
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected error generating auth url") _LOGGER.exception("Unexpected error generating auth url")

View file

@ -89,7 +89,7 @@ class PowerwallDataManager:
if attempt == 1: if attempt == 1:
await self._recreate_powerwall_login() await self._recreate_powerwall_login()
data = await _fetch_powerwall_data(self.power_wall) data = await _fetch_powerwall_data(self.power_wall)
except (asyncio.TimeoutError, PowerwallUnreachableError) as err: except (TimeoutError, PowerwallUnreachableError) as err:
raise UpdateFailed("Unable to fetch data from powerwall") from err raise UpdateFailed("Unable to fetch data from powerwall") from err
except MissingAttributeError as err: except MissingAttributeError as err:
_LOGGER.error("The powerwall api has changed: %s", str(err)) _LOGGER.error("The powerwall api has changed: %s", str(err))
@ -136,7 +136,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# Cancel closing power_wall on success # Cancel closing power_wall on success
stack.pop_all() stack.pop_all()
except (asyncio.TimeoutError, PowerwallUnreachableError) as err: except (TimeoutError, PowerwallUnreachableError) as err:
raise ConfigEntryNotReady from err raise ConfigEntryNotReady from err
except MissingAttributeError as err: except MissingAttributeError as err:
# The error might include some important information about what exactly changed. # The error might include some important information about what exactly changed.

View file

@ -166,7 +166,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
description_placeholders: dict[str, str] = {} description_placeholders: dict[str, str] = {}
try: try:
info = await validate_input(self.hass, user_input) info = await validate_input(self.hass, user_input)
except (PowerwallUnreachableError, asyncio.TimeoutError) as ex: except (PowerwallUnreachableError, TimeoutError) as ex:
errors[CONF_IP_ADDRESS] = "cannot_connect" errors[CONF_IP_ADDRESS] = "cannot_connect"
description_placeholders = {"error": str(ex)} description_placeholders = {"error": str(ex)}
except WrongVersion as ex: except WrongVersion as ex:

View file

@ -73,5 +73,5 @@ class ProwlNotificationService(BaseNotificationService):
response.status, response.status,
result, result,
) )
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error("Timeout accessing Prowl at %s", url) _LOGGER.error("Timeout accessing Prowl at %s", url)

View file

@ -50,7 +50,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, str]) -> dict[str,
async with asyncio.timeout(5): async with asyncio.timeout(5):
version = await api.get_version() version = await api.get_version()
except (asyncio.TimeoutError, ClientError) as err: except (TimeoutError, ClientError) as err:
_LOGGER.error("Could not connect to PrusaLink: %s", err) _LOGGER.error("Could not connect to PrusaLink: %s", err)
raise CannotConnect from err raise CannotConnect from err

View file

@ -1,5 +1,4 @@
"""Support for PlayStation 4 consoles.""" """Support for PlayStation 4 consoles."""
import asyncio
from contextlib import suppress from contextlib import suppress
import logging import logging
from typing import Any, cast from typing import Any, cast
@ -257,7 +256,7 @@ class PS4Device(MediaPlayerEntity):
except PSDataIncomplete: except PSDataIncomplete:
title = None title = None
except asyncio.TimeoutError: except TimeoutError:
title = None title = None
_LOGGER.error("PS Store Search Timed out") _LOGGER.error("PS Store Search Timed out")

View file

@ -75,7 +75,7 @@ async def handle_webhook(hass, webhook_id, request):
try: try:
async with asyncio.timeout(5): async with asyncio.timeout(5):
data = dict(await request.post()) data = dict(await request.post())
except (asyncio.TimeoutError, aiohttp.web.HTTPException) as error: except (TimeoutError, aiohttp.web.HTTPException) as error:
_LOGGER.error("Could not get information from POST <%s>", error) _LOGGER.error("Could not get information from POST <%s>", error)
return return

View file

@ -1,7 +1,6 @@
"""Config flow for Qingping integration.""" """Config flow for Qingping integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
from typing import Any from typing import Any
from qingping_ble import QingpingBluetoothDeviceData as DeviceData from qingping_ble import QingpingBluetoothDeviceData as DeviceData
@ -62,7 +61,7 @@ class QingpingConfigFlow(ConfigFlow, domain=DOMAIN):
self._discovery_info = await self._async_wait_for_full_advertisement( self._discovery_info = await self._async_wait_for_full_advertisement(
discovery_info, device discovery_info, device
) )
except asyncio.TimeoutError: except TimeoutError:
return self.async_abort(reason="not_supported") return self.async_abort(reason="not_supported")
self._discovery_info = discovery_info self._discovery_info = discovery_info
self._discovered_device = device self._discovered_device = device

View file

@ -1,7 +1,6 @@
"""Config flow for Rabbit Air integration.""" """Config flow for Rabbit Air integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
import logging import logging
from typing import Any from typing import Any
@ -36,7 +35,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str,
except ValueError as err: except ValueError as err:
# Most likely caused by the invalid access token. # Most likely caused by the invalid access token.
raise InvalidAccessToken from err raise InvalidAccessToken from err
except asyncio.TimeoutError as err: except TimeoutError as err:
# Either the host doesn't respond or the auth failed. # Either the host doesn't respond or the auth failed.
raise TimeoutConnect from err raise TimeoutConnect from err
except OSError as err: except OSError as err:

View file

@ -114,7 +114,7 @@ class RainbirdConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
controller.get_serial_number(), controller.get_serial_number(),
controller.get_wifi_params(), controller.get_wifi_params(),
) )
except asyncio.TimeoutError as err: except TimeoutError as err:
raise ConfigFlowError( raise ConfigFlowError(
f"Timeout connecting to Rain Bird controller: {str(err)}", f"Timeout connecting to Rain Bird controller: {str(err)}",
"timeout_connect", "timeout_connect",

View file

@ -106,7 +106,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
await self.async_set_unique_id(unique_id) await self.async_set_unique_id(unique_id)
try: try:
await self._validate_device(dev_path) await self._validate_device(dev_path)
except asyncio.TimeoutError: except TimeoutError:
return self.async_abort(reason="timeout_connect") return self.async_abort(reason="timeout_connect")
except RAVEnConnectionError: except RAVEnConnectionError:
return self.async_abort(reason="cannot_connect") return self.async_abort(reason="cannot_connect")
@ -147,7 +147,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
await self.async_set_unique_id(unique_id) await self.async_set_unique_id(unique_id)
try: try:
await self._validate_device(dev_path) await self._validate_device(dev_path)
except asyncio.TimeoutError: except TimeoutError:
errors[CONF_DEVICE] = "timeout_connect" errors[CONF_DEVICE] = "timeout_connect"
except RAVEnConnectionError: except RAVEnConnectionError:
errors[CONF_DEVICE] = "cannot_connect" errors[CONF_DEVICE] = "cannot_connect"

View file

@ -1335,7 +1335,7 @@ class Recorder(threading.Thread):
try: try:
async with asyncio.timeout(DB_LOCK_TIMEOUT): async with asyncio.timeout(DB_LOCK_TIMEOUT):
await database_locked.wait() await database_locked.wait()
except asyncio.TimeoutError as err: except TimeoutError as err:
task.database_unlock.set() task.database_unlock.set()
raise TimeoutError( raise TimeoutError(
f"Could not lock database within {DB_LOCK_TIMEOUT} seconds." f"Could not lock database within {DB_LOCK_TIMEOUT} seconds."

View file

@ -1,7 +1,6 @@
"""Support for RESTful switches.""" """Support for RESTful switches."""
from __future__ import annotations from __future__ import annotations
import asyncio
from http import HTTPStatus from http import HTTPStatus
import logging import logging
from typing import Any from typing import Any
@ -117,7 +116,7 @@ async def async_setup_platform(
"Missing resource or schema in configuration. " "Missing resource or schema in configuration. "
"Add http:// or https:// to your URL" "Add http:// or https:// to your URL"
) )
except (asyncio.TimeoutError, httpx.RequestError) as exc: except (TimeoutError, httpx.RequestError) as exc:
raise PlatformNotReady(f"No route to resource/endpoint: {resource}") from exc raise PlatformNotReady(f"No route to resource/endpoint: {resource}") from exc
@ -177,7 +176,7 @@ class RestSwitch(ManualTriggerEntity, SwitchEntity):
_LOGGER.error( _LOGGER.error(
"Can't turn on %s. Is resource/endpoint offline?", self._resource "Can't turn on %s. Is resource/endpoint offline?", self._resource
) )
except (asyncio.TimeoutError, httpx.RequestError): except (TimeoutError, httpx.RequestError):
_LOGGER.error("Error while switching on %s", self._resource) _LOGGER.error("Error while switching on %s", self._resource)
async def async_turn_off(self, **kwargs: Any) -> None: async def async_turn_off(self, **kwargs: Any) -> None:
@ -192,7 +191,7 @@ class RestSwitch(ManualTriggerEntity, SwitchEntity):
_LOGGER.error( _LOGGER.error(
"Can't turn off %s. Is resource/endpoint offline?", self._resource "Can't turn off %s. Is resource/endpoint offline?", self._resource
) )
except (asyncio.TimeoutError, httpx.RequestError): except (TimeoutError, httpx.RequestError):
_LOGGER.error("Error while switching off %s", self._resource) _LOGGER.error("Error while switching off %s", self._resource)
async def set_device_state(self, body: Any) -> httpx.Response: async def set_device_state(self, body: Any) -> httpx.Response:
@ -217,7 +216,7 @@ class RestSwitch(ManualTriggerEntity, SwitchEntity):
req = None req = None
try: try:
req = await self.get_device_state(self.hass) req = await self.get_device_state(self.hass)
except (asyncio.TimeoutError, httpx.TimeoutException): except (TimeoutError, httpx.TimeoutException):
_LOGGER.exception("Timed out while fetching data") _LOGGER.exception("Timed out while fetching data")
except httpx.RequestError as err: except httpx.RequestError as err:
_LOGGER.exception("Error while fetching data: %s", err) _LOGGER.exception("Error while fetching data: %s", err)

View file

@ -1,7 +1,6 @@
"""Support for exposing regular REST commands as services.""" """Support for exposing regular REST commands as services."""
from __future__ import annotations from __future__ import annotations
import asyncio
from http import HTTPStatus from http import HTTPStatus
from json.decoder import JSONDecodeError from json.decoder import JSONDecodeError
import logging import logging
@ -188,7 +187,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
) from err ) from err
return {"content": _content, "status": response.status} return {"content": _content, "status": response.status}
except asyncio.TimeoutError as err: except TimeoutError as err:
raise HomeAssistantError( raise HomeAssistantError(
f"Timeout when calling resource '{request_url}'", f"Timeout when calling resource '{request_url}'",
translation_domain=DOMAIN, translation_domain=DOMAIN,

View file

@ -285,7 +285,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
except ( except (
SerialException, SerialException,
OSError, OSError,
asyncio.TimeoutError, TimeoutError,
): ):
reconnect_interval = config[DOMAIN][CONF_RECONNECT_INTERVAL] reconnect_interval = config[DOMAIN][CONF_RECONNECT_INTERVAL]
_LOGGER.exception( _LOGGER.exception(

View file

@ -91,7 +91,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
await async_setup_internal(hass, entry) await async_setup_internal(hass, entry)
except asyncio.TimeoutError: except TimeoutError:
# Library currently doesn't support reload # Library currently doesn't support reload
_LOGGER.error( _LOGGER.error(
"Connection timeout: failed to receive response from RFXtrx device" "Connection timeout: failed to receive response from RFXtrx device"

View file

@ -372,7 +372,7 @@ class OptionsFlow(config_entries.OptionsFlow):
entity_registry.async_remove(entry.entity_id) entity_registry.async_remove(entry.entity_id)
# Wait for entities to finish cleanup # Wait for entities to finish cleanup
with suppress(asyncio.TimeoutError): with suppress(TimeoutError):
async with asyncio.timeout(10): async with asyncio.timeout(10):
await wait_for_entities.wait() await wait_for_entities.wait()
remove_track_state_changes() remove_track_state_changes()
@ -407,7 +407,7 @@ class OptionsFlow(config_entries.OptionsFlow):
) )
# Wait for entities to finish renaming # Wait for entities to finish renaming
with suppress(asyncio.TimeoutError): with suppress(TimeoutError):
async with asyncio.timeout(10): async with asyncio.timeout(10):
await wait_for_entities.wait() await wait_for_entities.wait()
remove_track_state_changes() remove_track_state_changes()

View file

@ -90,7 +90,7 @@ async def async_connect_or_timeout(
except RoombaConnectionError as err: except RoombaConnectionError as err:
_LOGGER.debug("Error to connect to vacuum: %s", err) _LOGGER.debug("Error to connect to vacuum: %s", err)
raise CannotConnect from err raise CannotConnect from err
except asyncio.TimeoutError as err: except TimeoutError as err:
# api looping if user or password incorrect and roomba exist # api looping if user or password incorrect and roomba exist
await async_disconnect_or_timeout(hass, roomba) await async_disconnect_or_timeout(hass, roomba)
_LOGGER.debug("Timeout expired: %s", err) _LOGGER.debug("Timeout expired: %s", err)
@ -102,7 +102,7 @@ async def async_connect_or_timeout(
async def async_disconnect_or_timeout(hass: HomeAssistant, roomba: Roomba) -> None: async def async_disconnect_or_timeout(hass: HomeAssistant, roomba: Roomba) -> None:
"""Disconnect to vacuum.""" """Disconnect to vacuum."""
_LOGGER.debug("Disconnect vacuum") _LOGGER.debug("Disconnect vacuum")
with contextlib.suppress(asyncio.TimeoutError): with contextlib.suppress(TimeoutError):
async with asyncio.timeout(3): async with asyncio.timeout(3):
await hass.async_add_executor_job(roomba.disconnect) await hass.async_add_executor_job(roomba.disconnect)

View file

@ -219,7 +219,7 @@ class SamsungTVDevice(SamsungTVEntity, MediaPlayerEntity):
try: try:
async with asyncio.timeout(APP_LIST_DELAY): async with asyncio.timeout(APP_LIST_DELAY):
await self._app_list_event.wait() await self._app_list_event.wait()
except asyncio.TimeoutError as err: except TimeoutError as err:
# No need to try again # No need to try again
self._app_list_event.set() self._app_list_event.set()
LOGGER.debug("Failed to load app list from %s: %r", self._host, err) LOGGER.debug("Failed to load app list from %s: %r", self._host, err)

View file

@ -1,6 +1,5 @@
"""Constants for monitoring a Sense energy sensor.""" """Constants for monitoring a Sense energy sensor."""
import asyncio
import socket import socket
from sense_energy import ( from sense_energy import (
@ -39,11 +38,11 @@ FROM_GRID_ID = "from_grid"
SOLAR_POWERED_NAME = "Solar Powered Percentage" SOLAR_POWERED_NAME = "Solar Powered Percentage"
SOLAR_POWERED_ID = "solar_powered" SOLAR_POWERED_ID = "solar_powered"
SENSE_TIMEOUT_EXCEPTIONS = (asyncio.TimeoutError, SenseAPITimeoutException) SENSE_TIMEOUT_EXCEPTIONS = (TimeoutError, SenseAPITimeoutException)
SENSE_WEBSOCKET_EXCEPTIONS = (socket.gaierror, SenseWebsocketException) SENSE_WEBSOCKET_EXCEPTIONS = (socket.gaierror, SenseWebsocketException)
SENSE_CONNECT_EXCEPTIONS = ( SENSE_CONNECT_EXCEPTIONS = (
socket.gaierror, socket.gaierror,
asyncio.TimeoutError, TimeoutError,
SenseAPITimeoutException, SenseAPITimeoutException,
SenseAPIException, SenseAPIException,
) )

View file

@ -1,6 +1,5 @@
"""Constants for Sensibo.""" """Constants for Sensibo."""
import asyncio
import logging import logging
from aiohttp.client_exceptions import ClientConnectionError from aiohttp.client_exceptions import ClientConnectionError
@ -27,7 +26,7 @@ TIMEOUT = 8
SENSIBO_ERRORS = ( SENSIBO_ERRORS = (
ClientConnectionError, ClientConnectionError,
asyncio.TimeoutError, TimeoutError,
AuthenticationError, AuthenticationError,
SensiboError, SensiboError,
) )

View file

@ -40,7 +40,7 @@ async def async_connect_or_timeout(ayla_api: AylaApi) -> bool:
except SharkIqAuthError: except SharkIqAuthError:
LOGGER.error("Authentication error connecting to Shark IQ api") LOGGER.error("Authentication error connecting to Shark IQ api")
return False return False
except asyncio.TimeoutError as exc: except TimeoutError as exc:
LOGGER.error("Timeout expired") LOGGER.error("Timeout expired")
raise CannotConnect from exc raise CannotConnect from exc

View file

@ -53,7 +53,7 @@ async def _validate_input(
async with asyncio.timeout(10): async with asyncio.timeout(10):
LOGGER.debug("Initialize connection to Ayla networks API") LOGGER.debug("Initialize connection to Ayla networks API")
await ayla_api.async_sign_in() await ayla_api.async_sign_in()
except (asyncio.TimeoutError, aiohttp.ClientError, TypeError) as error: except (TimeoutError, aiohttp.ClientError, TypeError) as error:
LOGGER.error(error) LOGGER.error(error)
raise CannotConnect( raise CannotConnect(
"Unable to connect to SharkIQ services. Check your region settings." "Unable to connect to SharkIQ services. Check your region settings."

View file

@ -90,7 +90,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
try: try:
async with asyncio.timeout(COMMAND_TIMEOUT): async with asyncio.timeout(COMMAND_TIMEOUT):
stdout_data, stderr_data = await process.communicate() stdout_data, stderr_data = await process.communicate()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error( _LOGGER.error(
"Timed out running command: `%s`, after: %ss", cmd, COMMAND_TIMEOUT "Timed out running command: `%s`, after: %ss", cmd, COMMAND_TIMEOUT
) )

View file

@ -1,5 +1,4 @@
"""The Smart Meter Texas integration.""" """The Smart Meter Texas integration."""
import asyncio
import logging import logging
import ssl import ssl
@ -47,7 +46,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
except SmartMeterTexasAuthError: except SmartMeterTexasAuthError:
_LOGGER.error("Username or password was not accepted") _LOGGER.error("Username or password was not accepted")
return False return False
except asyncio.TimeoutError as error: except TimeoutError as error:
raise ConfigEntryNotReady from error raise ConfigEntryNotReady from error
await smart_meter_texas_data.setup() await smart_meter_texas_data.setup()

View file

@ -1,5 +1,4 @@
"""Config flow for Smart Meter Texas integration.""" """Config flow for Smart Meter Texas integration."""
import asyncio
import logging import logging
from aiohttp import ClientError from aiohttp import ClientError
@ -36,7 +35,7 @@ async def validate_input(hass: core.HomeAssistant, data):
try: try:
await client.authenticate() await client.authenticate()
except (asyncio.TimeoutError, ClientError, SmartMeterTexasAPIError) as error: except (TimeoutError, ClientError, SmartMeterTexasAPIError) as error:
raise CannotConnect from error raise CannotConnect from error
except SmartMeterTexasAuthError as error: except SmartMeterTexasAuthError as error:
raise InvalidAuth(error) from error raise InvalidAuth(error) from error

View file

@ -56,7 +56,7 @@ class SmartTubController:
# credentials were changed or invalidated, we need new ones # credentials were changed or invalidated, we need new ones
raise ConfigEntryAuthFailed from ex raise ConfigEntryAuthFailed from ex
except ( except (
asyncio.TimeoutError, TimeoutError,
client_exceptions.ClientOSError, client_exceptions.ClientOSError,
client_exceptions.ServerDisconnectedError, client_exceptions.ServerDisconnectedError,
client_exceptions.ContentTypeError, client_exceptions.ContentTypeError,

View file

@ -171,7 +171,7 @@ class SmhiWeather(WeatherEntity):
self._forecast_daily = await self._smhi_api.async_get_forecast() self._forecast_daily = await self._smhi_api.async_get_forecast()
self._forecast_hourly = await self._smhi_api.async_get_forecast_hour() self._forecast_hourly = await self._smhi_api.async_get_forecast_hour()
self._fail_count = 0 self._fail_count = 0
except (asyncio.TimeoutError, SmhiForecastException): except (TimeoutError, SmhiForecastException):
_LOGGER.error("Failed to connect to SMHI API, retry in 5 minutes") _LOGGER.error("Failed to connect to SMHI API, retry in 5 minutes")
self._fail_count += 1 self._fail_count += 1
if self._fail_count < 3: if self._fail_count < 3:

View file

@ -144,7 +144,7 @@ class SnoozConfigFlow(ConfigFlow, domain=DOMAIN):
try: try:
await self._pairing_task await self._pairing_task
except asyncio.TimeoutError: except TimeoutError:
return self.async_show_progress_done(next_step_id="pairing_timeout") return self.async_show_progress_done(next_step_id="pairing_timeout")
finally: finally:
self._pairing_task = None self._pairing_task = None

View file

@ -1,5 +1,4 @@
"""Component for the Somfy MyLink device supporting the Synergy API.""" """Component for the Somfy MyLink device supporting the Synergy API."""
import asyncio
import logging import logging
from somfy_mylink_synergy import SomfyMyLinkSynergy from somfy_mylink_synergy import SomfyMyLinkSynergy
@ -30,7 +29,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
mylink_status = await somfy_mylink.status_info() mylink_status = await somfy_mylink.status_info()
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
"Unable to connect to the Somfy MyLink device, please check your settings" "Unable to connect to the Somfy MyLink device, please check your settings"
) from ex ) from ex

View file

@ -1,7 +1,6 @@
"""Config flow for Somfy MyLink integration.""" """Config flow for Somfy MyLink integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
from copy import deepcopy from copy import deepcopy
import logging import logging
@ -40,7 +39,7 @@ async def validate_input(hass: core.HomeAssistant, data):
try: try:
status_info = await somfy_mylink.status_info() status_info = await somfy_mylink.status_info()
except asyncio.TimeoutError as ex: except TimeoutError as ex:
raise CannotConnect from ex raise CannotConnect from ex
if not status_info or "error" in status_info: if not status_info or "error" in status_info:

View file

@ -72,7 +72,7 @@ async def async_setup_entry(
10 10
): # set timeout to avoid blocking the setup process ): # set timeout to avoid blocking the setup process
await device.get_supported_methods() await device.get_supported_methods()
except (SongpalException, asyncio.TimeoutError) as ex: except (SongpalException, TimeoutError) as ex:
_LOGGER.warning("[%s(%s)] Unable to connect", name, endpoint) _LOGGER.warning("[%s(%s)] Unable to connect", name, endpoint)
_LOGGER.debug("Unable to get methods from songpal: %s", ex) _LOGGER.debug("Unable to get methods from songpal: %s", ex)
raise PlatformNotReady from ex raise PlatformNotReady from ex

View file

@ -393,7 +393,7 @@ class SonosDiscoveryManager:
OSError, OSError,
SoCoException, SoCoException,
Timeout, Timeout,
asyncio.TimeoutError, TimeoutError,
) as ex: ) as ex:
if not self.hosts_in_error.get(ip_addr): if not self.hosts_in_error.get(ip_addr):
_LOGGER.warning( _LOGGER.warning(
@ -447,7 +447,7 @@ class SonosDiscoveryManager:
OSError, OSError,
SoCoException, SoCoException,
Timeout, Timeout,
asyncio.TimeoutError, TimeoutError,
) as ex: ) as ex:
_LOGGER.warning("Discovery message failed to %s : %s", ip_addr, ex) _LOGGER.warning("Discovery message failed to %s : %s", ip_addr, ex)
elif not known_speaker.available: elif not known_speaker.available:

View file

@ -1126,7 +1126,7 @@ class SonosSpeaker:
async with asyncio.timeout(5): async with asyncio.timeout(5):
while not _test_groups(groups): while not _test_groups(groups):
await hass.data[DATA_SONOS].topology_condition.wait() await hass.data[DATA_SONOS].topology_condition.wait()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning("Timeout waiting for target groups %s", groups) _LOGGER.warning("Timeout waiting for target groups %s", groups)
any_speaker = next(iter(hass.data[DATA_SONOS].discovered.values())) any_speaker = next(iter(hass.data[DATA_SONOS].discovered.values()))

View file

@ -1,5 +1,4 @@
"""Support to send data to a Splunk instance.""" """Support to send data to a Splunk instance."""
import asyncio
from http import HTTPStatus from http import HTTPStatus
import json import json
import logging import logging
@ -120,7 +119,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
_LOGGER.warning(err) _LOGGER.warning(err)
except ClientConnectionError as err: except ClientConnectionError as err:
_LOGGER.warning(err) _LOGGER.warning(err)
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning("Connection to %s:%s timed out", host, port) _LOGGER.warning("Connection to %s:%s timed out", host, port)
except ClientResponseError as err: except ClientResponseError as err:
_LOGGER.error(err.message) _LOGGER.error(err.message)

View file

@ -140,7 +140,7 @@ class SqueezeboxConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
async with asyncio.timeout(TIMEOUT): async with asyncio.timeout(TIMEOUT):
await self._discover() await self._discover()
return await self.async_step_edit() return await self.async_step_edit()
except asyncio.TimeoutError: except TimeoutError:
errors["base"] = "no_server_found" errors["base"] = "no_server_found"
# display the form # display the form

View file

@ -1,12 +1,11 @@
"""Constants for the Steamist integration.""" """Constants for the Steamist integration."""
import asyncio
import aiohttp import aiohttp
DOMAIN = "steamist" DOMAIN = "steamist"
CONNECTION_EXCEPTIONS = (asyncio.TimeoutError, aiohttp.ClientError) CONNECTION_EXCEPTIONS = (TimeoutError, aiohttp.ClientError)
STARTUP_SCAN_TIMEOUT = 5 STARTUP_SCAN_TIMEOUT = 5
DISCOVER_SCAN_TIMEOUT = 10 DISCOVER_SCAN_TIMEOUT = 10

View file

@ -333,7 +333,7 @@ class StreamOutput:
try: try:
async with asyncio.timeout(timeout): async with asyncio.timeout(timeout):
await self._part_event.wait() await self._part_event.wait()
except asyncio.TimeoutError: except TimeoutError:
return False return False
return True return True

View file

@ -115,7 +115,7 @@ class SwitchbotDataUpdateCoordinator(ActiveBluetoothDataUpdateCoordinator[None])
async def async_wait_ready(self) -> bool: async def async_wait_ready(self) -> bool:
"""Wait for the device to be ready.""" """Wait for the device to be ready."""
with contextlib.suppress(asyncio.TimeoutError): with contextlib.suppress(TimeoutError):
async with asyncio.timeout(DEVICE_STARTUP_TIMEOUT): async with asyncio.timeout(DEVICE_STARTUP_TIMEOUT):
await self._ready_event.wait() await self._ready_event.wait()
return True return True

View file

@ -1,7 +1,6 @@
"""Switcher integration Button platform.""" """Switcher integration Button platform."""
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
@ -147,7 +146,7 @@ class SwitcherThermostatButtonEntity(
self.coordinator.data.device_key, self.coordinator.data.device_key,
) as swapi: ) as swapi:
response = await self.entity_description.press_fn(swapi, self._remote) response = await self.entity_description.press_fn(swapi, self._remote)
except (asyncio.TimeoutError, OSError, RuntimeError) as err: except (TimeoutError, OSError, RuntimeError) as err:
error = repr(err) error = repr(err)
if error or not response or not response.successful: if error or not response or not response.successful:

View file

@ -1,7 +1,6 @@
"""Switcher integration Climate platform.""" """Switcher integration Climate platform."""
from __future__ import annotations from __future__ import annotations
import asyncio
from typing import Any, cast from typing import Any, cast
from aioswitcher.api import SwitcherBaseResponse, SwitcherType2Api from aioswitcher.api import SwitcherBaseResponse, SwitcherType2Api
@ -172,7 +171,7 @@ class SwitcherClimateEntity(
self.coordinator.data.device_key, self.coordinator.data.device_key,
) as swapi: ) as swapi:
response = await swapi.control_breeze_device(self._remote, **kwargs) response = await swapi.control_breeze_device(self._remote, **kwargs)
except (asyncio.TimeoutError, OSError, RuntimeError) as err: except (TimeoutError, OSError, RuntimeError) as err:
error = repr(err) error = repr(err)
if error or not response or not response.successful: if error or not response or not response.successful:

View file

@ -1,7 +1,6 @@
"""Switcher integration Cover platform.""" """Switcher integration Cover platform."""
from __future__ import annotations from __future__ import annotations
import asyncio
import logging import logging
from typing import Any from typing import Any
@ -103,7 +102,7 @@ class SwitcherCoverEntity(
self.coordinator.data.device_key, self.coordinator.data.device_key,
) as swapi: ) as swapi:
response = await getattr(swapi, api)(*args) response = await getattr(swapi, api)(*args)
except (asyncio.TimeoutError, OSError, RuntimeError) as err: except (TimeoutError, OSError, RuntimeError) as err:
error = repr(err) error = repr(err)
if error or not response or not response.successful: if error or not response or not response.successful:

View file

@ -1,7 +1,6 @@
"""Switcher integration Switch platform.""" """Switcher integration Switch platform."""
from __future__ import annotations from __future__ import annotations
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import Any from typing import Any
@ -118,7 +117,7 @@ class SwitcherBaseSwitchEntity(
self.coordinator.data.device_key, self.coordinator.data.device_key,
) as swapi: ) as swapi:
response = await getattr(swapi, api)(*args) response = await getattr(swapi, api)(*args)
except (asyncio.TimeoutError, OSError, RuntimeError) as err: except (TimeoutError, OSError, RuntimeError) as err:
error = repr(err) error = repr(err)
if error or not response or not response.successful: if error or not response or not response.successful:

View file

@ -97,7 +97,7 @@ async def async_setup_entry(
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"Could not connect to {entry.title} ({entry.data[CONF_HOST]})." f"Could not connect to {entry.title} ({entry.data[CONF_HOST]})."
) from exception ) from exception
except asyncio.TimeoutError as exception: except TimeoutError as exception:
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"Timed out waiting for {entry.title} ({entry.data[CONF_HOST]})." f"Timed out waiting for {entry.title} ({entry.data[CONF_HOST]})."
) from exception ) from exception
@ -117,7 +117,7 @@ async def async_setup_entry(
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"Could not connect to {entry.title} ({entry.data[CONF_HOST]})." f"Could not connect to {entry.title} ({entry.data[CONF_HOST]})."
) from exception ) from exception
except asyncio.TimeoutError as exception: except TimeoutError as exception:
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"Timed out waiting for {entry.title} ({entry.data[CONF_HOST]})." f"Timed out waiting for {entry.title} ({entry.data[CONF_HOST]})."
) from exception ) from exception
@ -134,7 +134,7 @@ async def async_setup_entry(
entry.data[CONF_HOST], entry.data[CONF_HOST],
) )
await asyncio.sleep(1) await asyncio.sleep(1)
except asyncio.TimeoutError as exception: except TimeoutError as exception:
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"Timed out waiting for {entry.title} ({entry.data[CONF_HOST]})." f"Timed out waiting for {entry.title} ({entry.data[CONF_HOST]})."
) from exception ) from exception

View file

@ -75,7 +75,7 @@ async def _validate_input(
"Connection error when connecting to %s: %s", data[CONF_HOST], exception "Connection error when connecting to %s: %s", data[CONF_HOST], exception
) )
raise CannotConnect from exception raise CannotConnect from exception
except asyncio.TimeoutError as exception: except TimeoutError as exception:
_LOGGER.warning("Timed out connecting to %s: %s", data[CONF_HOST], exception) _LOGGER.warning("Timed out connecting to %s: %s", data[CONF_HOST], exception)
raise CannotConnect from exception raise CannotConnect from exception
except ValueError as exception: except ValueError as exception:

View file

@ -215,7 +215,7 @@ class SystemBridgeDataUpdateCoordinator(
) )
self.last_update_success = False self.last_update_success = False
self.async_update_listeners() self.async_update_listeners()
except asyncio.TimeoutError as exception: except TimeoutError as exception:
self.logger.warning( self.logger.warning(
"Timed out waiting for %s. Will retry: %s", "Timed out waiting for %s. Will retry: %s",
self.title, self.title,

View file

@ -85,7 +85,7 @@ async def get_integration_info(
assert registration.info_callback assert registration.info_callback
async with asyncio.timeout(INFO_CALLBACK_TIMEOUT): async with asyncio.timeout(INFO_CALLBACK_TIMEOUT):
data = await registration.info_callback(hass) data = await registration.info_callback(hass)
except asyncio.TimeoutError: except TimeoutError:
data = {"error": {"type": "failed", "error": "timeout"}} data = {"error": {"type": "failed", "error": "timeout"}}
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error fetching info") _LOGGER.exception("Error fetching info")
@ -236,7 +236,7 @@ async def async_check_can_reach_url(
return "ok" return "ok"
except aiohttp.ClientError: except aiohttp.ClientError:
data = {"type": "failed", "error": "unreachable"} data = {"type": "failed", "error": "unreachable"}
except asyncio.TimeoutError: except TimeoutError:
data = {"type": "failed", "error": "timeout"} data = {"type": "failed", "error": "timeout"}
if more_info is not None: if more_info is not None:
data["more_info"] = more_info data["more_info"] = more_info

View file

@ -1,5 +1,4 @@
"""Test the Oncue config flow.""" """Test the Oncue config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
from aiooncue import LoginFailedException from aiooncue import LoginFailedException
@ -72,7 +71,7 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
with patch( with patch(
"homeassistant.components.oncue.config_flow.Oncue.async_login", "homeassistant.components.oncue.config_flow.Oncue.async_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,7 +1,6 @@
"""Tests for the oncue component.""" """Tests for the oncue component."""
from __future__ import annotations from __future__ import annotations
import asyncio
from unittest.mock import patch from unittest.mock import patch
from aiooncue import LoginFailedException from aiooncue import LoginFailedException
@ -62,7 +61,7 @@ async def test_config_entry_retry_later(hass: HomeAssistant) -> None:
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
with patch( with patch(
"homeassistant.components.oncue.Oncue.async_login", "homeassistant.components.oncue.Oncue.async_login",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
await async_setup_component(hass, oncue.DOMAIN, {oncue.DOMAIN: {}}) await async_setup_component(hass, oncue.DOMAIN, {oncue.DOMAIN: {}})
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -1,5 +1,4 @@
"""The tests for the openalpr cloud platform.""" """The tests for the openalpr cloud platform."""
import asyncio
from unittest.mock import PropertyMock, patch from unittest.mock import PropertyMock, patch
import pytest import pytest
@ -193,7 +192,7 @@ async def test_openalpr_process_image_api_timeout(
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
) -> None: ) -> None:
"""Set up and scan a picture and test api error.""" """Set up and scan a picture and test api error."""
aioclient_mock.post(OPENALPR_API_URL, params=PARAMS, exc=asyncio.TimeoutError()) aioclient_mock.post(OPENALPR_API_URL, params=PARAMS, exc=TimeoutError())
with patch( with patch(
"homeassistant.components.camera.async_get_image", "homeassistant.components.camera.async_get_image",

View file

@ -1,5 +1,4 @@
"""Test the Opentherm Gateway config flow.""" """Test the Opentherm Gateway config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
from pyotgw.vars import OTGW, OTGW_ABOUT from pyotgw.vars import OTGW, OTGW_ABOUT
@ -155,7 +154,7 @@ async def test_form_connection_timeout(hass: HomeAssistant) -> None:
) )
with patch( with patch(
"pyotgw.OpenThermGateway.connect", side_effect=(asyncio.TimeoutError) "pyotgw.OpenThermGateway.connect", side_effect=(TimeoutError)
) as mock_connect, patch( ) as mock_connect, patch(
"pyotgw.status.StatusManager._process_updates", return_value=None "pyotgw.status.StatusManager._process_updates", return_value=None
): ):

View file

@ -175,7 +175,7 @@ async def test_user_flow_404(
@pytest.mark.parametrize( @pytest.mark.parametrize(
"error", "error",
[ [
asyncio.TimeoutError, TimeoutError,
python_otbr_api.OTBRError, python_otbr_api.OTBRError,
aiohttp.ClientError, aiohttp.ClientError,
], ],

View file

@ -244,7 +244,7 @@ async def test_import_insecure_dataset(hass: HomeAssistant, dataset: bytes) -> N
@pytest.mark.parametrize( @pytest.mark.parametrize(
"error", "error",
[ [
asyncio.TimeoutError, TimeoutError,
python_otbr_api.OTBRError, python_otbr_api.OTBRError,
aiohttp.ClientError, aiohttp.ClientError,
], ],

View file

@ -1,5 +1,4 @@
"""Test the PECO Outage Counter init file.""" """Test the PECO Outage Counter init file."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
from peco import ( from peco import (
@ -72,7 +71,7 @@ async def test_update_timeout(hass: HomeAssistant, sensor) -> None:
with patch( with patch(
"peco.PecoOutageApi.get_outage_count", "peco.PecoOutageApi.get_outage_count",
side_effect=asyncio.TimeoutError(), side_effect=TimeoutError(),
): ):
assert not await hass.config_entries.async_setup(config_entry.entry_id) assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -97,7 +96,7 @@ async def test_total_update_timeout(hass: HomeAssistant, sensor) -> None:
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
with patch( with patch(
"peco.PecoOutageApi.get_outage_totals", "peco.PecoOutageApi.get_outage_totals",
side_effect=asyncio.TimeoutError(), side_effect=TimeoutError(),
): ):
assert not await hass.config_entries.async_setup(config_entry.entry_id) assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -256,7 +255,7 @@ async def test_meter_timeout(hass: HomeAssistant) -> None:
with patch( with patch(
"peco.PecoOutageApi.meter_check", "peco.PecoOutageApi.meter_check",
side_effect=asyncio.TimeoutError(), side_effect=TimeoutError(),
), patch( ), patch(
"peco.PecoOutageApi.get_outage_count", "peco.PecoOutageApi.get_outage_count",
return_value=OutageResults( return_value=OutageResults(

View file

@ -1,5 +1,4 @@
"""Tests for the Point config flow.""" """Tests for the Point config flow."""
import asyncio
from unittest.mock import AsyncMock, patch from unittest.mock import AsyncMock, patch
import pytest import pytest
@ -126,7 +125,7 @@ async def test_not_pick_implementation_if_only_one(hass: HomeAssistant) -> None:
async def test_abort_if_timeout_generating_auth_url(hass: HomeAssistant) -> None: async def test_abort_if_timeout_generating_auth_url(hass: HomeAssistant) -> None:
"""Test we abort if generating authorize url fails.""" """Test we abort if generating authorize url fails."""
flow = init_config_flow(hass, side_effect=asyncio.TimeoutError) flow = init_config_flow(hass, side_effect=TimeoutError)
result = await flow.async_step_user() result = await flow.async_step_user()
assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["type"] == data_entry_flow.FlowResultType.ABORT

View file

@ -1,6 +1,5 @@
"""Test the Powerwall config flow.""" """Test the Powerwall config flow."""
import asyncio
from datetime import timedelta from datetime import timedelta
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
@ -61,7 +60,7 @@ async def test_form_source_user(hass: HomeAssistant) -> None:
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize("exc", (PowerwallUnreachableError, asyncio.TimeoutError)) @pytest.mark.parametrize("exc", (PowerwallUnreachableError, TimeoutError))
async def test_form_cannot_connect(hass: HomeAssistant, exc: Exception) -> None: async def test_form_cannot_connect(hass: HomeAssistant, exc: Exception) -> None:
"""Test we handle cannot connect error.""" """Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -586,7 +585,7 @@ async def test_discovered_wifi_does_not_update_ip_online_but_access_denied(
# the discovery flow to probe to see if its online # the discovery flow to probe to see if its online
# which will result in an access denied error, which # which will result in an access denied error, which
# means its still online and we should not update the ip # means its still online and we should not update the ip
mock_powerwall.get_meters.side_effect = asyncio.TimeoutError mock_powerwall.get_meters.side_effect = TimeoutError
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=60)) async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=60))
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -1,5 +1,4 @@
"""Test the PrusaLink config flow.""" """Test the PrusaLink config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
from homeassistant import config_entries from homeassistant import config_entries
@ -137,7 +136,7 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
with patch( with patch(
"homeassistant.components.prusalink.config_flow.PrusaLink.get_version", "homeassistant.components.prusalink.config_flow.PrusaLink.get_version",
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 @@
"""Test the Qingping config flow.""" """Test the Qingping config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
from homeassistant import config_entries from homeassistant import config_entries
@ -68,7 +67,7 @@ async def test_async_step_bluetooth_not_qingping(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth not qingping.""" """Test discovery via bluetooth not qingping."""
with patch( with patch(
"homeassistant.components.qingping.config_flow.async_process_advertisements", "homeassistant.components.qingping.config_flow.async_process_advertisements",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,

View file

@ -1,7 +1,6 @@
"""Test the RabbitAir config flow.""" """Test the RabbitAir config flow."""
from __future__ import annotations from __future__ import annotations
import asyncio
from collections.abc import Generator from collections.abc import Generator
from ipaddress import ip_address from ipaddress import ip_address
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
@ -115,7 +114,7 @@ async def test_form(hass: HomeAssistant) -> None:
[ [
(ValueError, "invalid_access_token"), (ValueError, "invalid_access_token"),
(OSError, "invalid_host"), (OSError, "invalid_host"),
(asyncio.TimeoutError, "timeout_connect"), (TimeoutError, "timeout_connect"),
(Exception, "cannot_connect"), (Exception, "cannot_connect"),
], ],
) )

View file

@ -1,6 +1,5 @@
"""Tests for the Rain Bird config flow.""" """Tests for the Rain Bird config flow."""
import asyncio
from collections.abc import Generator from collections.abc import Generator
from http import HTTPStatus from http import HTTPStatus
from typing import Any from typing import Any
@ -277,7 +276,7 @@ async def test_controller_timeout(
with patch( with patch(
"homeassistant.components.rainbird.config_flow.asyncio.timeout", "homeassistant.components.rainbird.config_flow.asyncio.timeout",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
result = await complete_flow(hass) result = await complete_flow(hass)
assert result.get("type") == FlowResultType.FORM assert result.get("type") == FlowResultType.FORM

View file

@ -1,5 +1,4 @@
"""Test Rainforest RAVEn config flow.""" """Test Rainforest RAVEn config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
from aioraven.device import RAVEnConnectionError from aioraven.device import RAVEnConnectionError
@ -48,8 +47,8 @@ def mock_device_comm_error(mock_device):
@pytest.fixture @pytest.fixture
def mock_device_timeout(mock_device): def mock_device_timeout(mock_device):
"""Mock a device which times out when queried.""" """Mock a device which times out when queried."""
mock_device.get_meter_list.side_effect = asyncio.TimeoutError mock_device.get_meter_list.side_effect = TimeoutError
mock_device.get_meter_info.side_effect = asyncio.TimeoutError mock_device.get_meter_info.side_effect = TimeoutError
return mock_device return mock_device

View file

@ -1767,7 +1767,7 @@ async def test_database_lock_and_unlock(
task = asyncio.create_task(async_wait_recording_done(hass)) task = asyncio.create_task(async_wait_recording_done(hass))
# Recording can't be finished while lock is held # Recording can't be finished while lock is held
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
await asyncio.wait_for(asyncio.shield(task), timeout=0.25) await asyncio.wait_for(asyncio.shield(task), timeout=0.25)
db_events = await hass.async_add_executor_job(_get_db_events) db_events = await hass.async_add_executor_job(_get_db_events)
assert len(db_events) == 0 assert len(db_events) == 0

View file

@ -1,6 +1,5 @@
"""The tests for the REST binary sensor platform.""" """The tests for the REST binary sensor platform."""
import asyncio
from http import HTTPStatus from http import HTTPStatus
import ssl import ssl
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
@ -107,7 +106,7 @@ async def test_setup_fail_on_ssl_erros(
@respx.mock @respx.mock
async def test_setup_timeout(hass: HomeAssistant) -> None: async def test_setup_timeout(hass: HomeAssistant) -> None:
"""Test setup when connection timeout occurs.""" """Test setup when connection timeout occurs."""
respx.get("http://localhost").mock(side_effect=asyncio.TimeoutError()) respx.get("http://localhost").mock(side_effect=TimeoutError())
assert await async_setup_component( assert await async_setup_component(
hass, hass,
BINARY_SENSOR_DOMAIN, BINARY_SENSOR_DOMAIN,

View file

@ -1,6 +1,5 @@
"""Tests for rest component.""" """Tests for rest component."""
import asyncio
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus from http import HTTPStatus
import ssl import ssl
@ -33,7 +32,7 @@ async def test_setup_with_endpoint_timeout_with_recovery(hass: HomeAssistant) ->
"""Test setup with an endpoint that times out that recovers.""" """Test setup with an endpoint that times out that recovers."""
await async_setup_component(hass, "homeassistant", {}) await async_setup_component(hass, "homeassistant", {})
respx.get("http://localhost").mock(side_effect=asyncio.TimeoutError()) respx.get("http://localhost").mock(side_effect=TimeoutError())
assert await async_setup_component( assert await async_setup_component(
hass, hass,
DOMAIN, DOMAIN,
@ -99,7 +98,7 @@ async def test_setup_with_endpoint_timeout_with_recovery(hass: HomeAssistant) ->
assert hass.states.get("binary_sensor.binary_sensor2").state == "off" assert hass.states.get("binary_sensor.binary_sensor2").state == "off"
# Now the end point flakes out again # Now the end point flakes out again
respx.get("http://localhost").mock(side_effect=asyncio.TimeoutError()) respx.get("http://localhost").mock(side_effect=TimeoutError())
# Refresh the coordinator # Refresh the coordinator
async_fire_time_changed(hass, utcnow() + timedelta(seconds=31)) async_fire_time_changed(hass, utcnow() + timedelta(seconds=31))

View file

@ -1,5 +1,4 @@
"""The tests for the REST sensor platform.""" """The tests for the REST sensor platform."""
import asyncio
from http import HTTPStatus from http import HTTPStatus
import ssl import ssl
from unittest.mock import AsyncMock, MagicMock, patch from unittest.mock import AsyncMock, MagicMock, patch
@ -105,7 +104,7 @@ async def test_setup_fail_on_ssl_erros(
@respx.mock @respx.mock
async def test_setup_timeout(hass: HomeAssistant) -> None: async def test_setup_timeout(hass: HomeAssistant) -> None:
"""Test setup when connection timeout occurs.""" """Test setup when connection timeout occurs."""
respx.get("http://localhost").mock(side_effect=asyncio.TimeoutError()) respx.get("http://localhost").mock(side_effect=TimeoutError())
assert await async_setup_component( assert await async_setup_component(
hass, hass,
SENSOR_DOMAIN, SENSOR_DOMAIN,

View file

@ -1,5 +1,4 @@
"""The tests for the rest command platform.""" """The tests for the rest command platform."""
import asyncio
import base64 import base64
from http import HTTPStatus from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
@ -64,7 +63,7 @@ async def test_rest_command_timeout(
"""Call a rest command with timeout.""" """Call a rest command with timeout."""
await setup_component() await setup_component()
aioclient_mock.get(TEST_URL, exc=asyncio.TimeoutError()) aioclient_mock.get(TEST_URL, exc=TimeoutError())
with pytest.raises( with pytest.raises(
HomeAssistantError, HomeAssistantError,

View file

@ -1,7 +1,6 @@
"""Test the Sensibo config flow.""" """Test the Sensibo config flow."""
from __future__ import annotations from __future__ import annotations
import asyncio
from typing import Any from typing import Any
from unittest.mock import patch from unittest.mock import patch
@ -60,7 +59,7 @@ async def test_form(hass: HomeAssistant) -> None:
("error_message", "p_error"), ("error_message", "p_error"),
[ [
(aiohttp.ClientConnectionError, "cannot_connect"), (aiohttp.ClientConnectionError, "cannot_connect"),
(asyncio.TimeoutError, "cannot_connect"), (TimeoutError, "cannot_connect"),
(AuthenticationError, "invalid_auth"), (AuthenticationError, "invalid_auth"),
(SensiboError, "cannot_connect"), (SensiboError, "cannot_connect"),
], ],
@ -219,7 +218,7 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
("sideeffect", "p_error"), ("sideeffect", "p_error"),
[ [
(aiohttp.ClientConnectionError, "cannot_connect"), (aiohttp.ClientConnectionError, "cannot_connect"),
(asyncio.TimeoutError, "cannot_connect"), (TimeoutError, "cannot_connect"),
(AuthenticationError, "invalid_auth"), (AuthenticationError, "invalid_auth"),
(SensiboError, "cannot_connect"), (SensiboError, "cannot_connect"),
], ],

View file

@ -254,7 +254,7 @@ async def test_do_not_run_forever(
"homeassistant.components.shell_command.asyncio.create_subprocess_shell", "homeassistant.components.shell_command.asyncio.create_subprocess_shell",
side_effect=mock_create_subprocess_shell, side_effect=mock_create_subprocess_shell,
): ):
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
await hass.services.async_call( await hass.services.async_call(
shell_command.DOMAIN, shell_command.DOMAIN,
"test_service", "test_service",

View file

@ -1,5 +1,4 @@
"""Test configuration and mocks for Smart Meter Texas.""" """Test configuration and mocks for Smart Meter Texas."""
import asyncio
from http import HTTPStatus from http import HTTPStatus
import json import json
@ -71,7 +70,7 @@ def mock_connection(
json={"errormessage": "ERR-USR-INVALIDPASSWORDERROR"}, json={"errormessage": "ERR-USR-INVALIDPASSWORDERROR"},
) )
else: # auth_timeout else: # auth_timeout
aioclient_mock.post(auth_endpoint, exc=asyncio.TimeoutError) aioclient_mock.post(auth_endpoint, exc=TimeoutError)
aioclient_mock.post( aioclient_mock.post(
f"{BASE_ENDPOINT}{METER_ENDPOINT}", f"{BASE_ENDPOINT}{METER_ENDPOINT}",

View file

@ -1,5 +1,4 @@
"""Test the Smart Meter Texas config flow.""" """Test the Smart Meter Texas config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
from aiohttp import ClientError from aiohttp import ClientError
@ -63,7 +62,7 @@ async def test_form_invalid_auth(hass: HomeAssistant) -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"side_effect", [asyncio.TimeoutError, ClientError, SmartMeterTexasAPIError] "side_effect", [TimeoutError, ClientError, SmartMeterTexasAPIError]
) )
async def test_form_cannot_connect(hass: HomeAssistant, side_effect) -> None: async def test_form_cannot_connect(hass: HomeAssistant, side_effect) -> None:
"""Test we handle cannot connect error.""" """Test we handle cannot connect error."""

View file

@ -1,5 +1,4 @@
"""Test smarttub setup process.""" """Test smarttub setup process."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
from smarttub import LoginFailed from smarttub import LoginFailed
@ -26,7 +25,7 @@ async def test_setup_entry_not_ready(
setup_component, hass: HomeAssistant, config_entry, smarttub_api setup_component, hass: HomeAssistant, config_entry, smarttub_api
) -> None: ) -> None:
"""Test setup when the entry is not ready.""" """Test setup when the entry is not ready."""
smarttub_api.login.side_effect = asyncio.TimeoutError smarttub_api.login.side_effect = TimeoutError
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)

View file

@ -1,5 +1,4 @@
"""Test for the smhi weather entity.""" """Test for the smhi weather entity."""
import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
from unittest.mock import patch from unittest.mock import patch
@ -187,7 +186,7 @@ async def test_properties_unknown_symbol(hass: HomeAssistant) -> None:
) )
@pytest.mark.parametrize("error", [SmhiForecastException(), asyncio.TimeoutError()]) @pytest.mark.parametrize("error", [SmhiForecastException(), TimeoutError()])
async def test_refresh_weather_forecast_retry( async def test_refresh_weather_forecast_retry(
hass: HomeAssistant, error: Exception hass: HomeAssistant, error: Exception
) -> None: ) -> None:

View file

@ -1,7 +1,6 @@
"""Test the Snooz config flow.""" """Test the Snooz config flow."""
from __future__ import annotations from __future__ import annotations
import asyncio
from asyncio import Event from asyncio import Event
from unittest.mock import patch from unittest.mock import patch
@ -300,7 +299,7 @@ async def _test_pairs_timeout(
) -> str: ) -> str:
with patch( with patch(
"homeassistant.components.snooz.config_flow.async_process_advertisements", "homeassistant.components.snooz.config_flow.async_process_advertisements",
side_effect=asyncio.TimeoutError(), side_effect=TimeoutError(),
): ):
result = await hass.config_entries.flow.async_configure( result = await hass.config_entries.flow.async_configure(
flow_id, user_input=user_input or {} flow_id, user_input=user_input or {}

View file

@ -1,5 +1,4 @@
"""Test the Somfy MyLink config flow.""" """Test the Somfy MyLink config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -123,7 +122,7 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
with patch( with patch(
"homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info", "homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
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

@ -377,7 +377,7 @@ async def test_async_poll_manual_hosts_6(
with caplog.at_level(logging.DEBUG): with caplog.at_level(logging.DEBUG):
caplog.clear() caplog.clear()
# The discovery events should not fire, wait with a timeout. # The discovery events should not fire, wait with a timeout.
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with asyncio.timeout(1.0): async with asyncio.timeout(1.0):
await speaker_1_activity.event.wait() await speaker_1_activity.event.wait()
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -1,5 +1,4 @@
"""Test the Steamist config flow.""" """Test the Steamist config flow."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -103,7 +102,7 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
with patch( with patch(
"homeassistant.components.steamist.config_flow.Steamist.async_get_status", "homeassistant.components.steamist.config_flow.Steamist.async_get_status",
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,7 +1,6 @@
"""Tests for the steamist component.""" """Tests for the steamist component."""
from __future__ import annotations from __future__ import annotations
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch from unittest.mock import AsyncMock, MagicMock, patch
from discovery30303 import AIODiscovery30303 from discovery30303 import AIODiscovery30303
@ -60,7 +59,7 @@ async def test_config_entry_retry_later(hass: HomeAssistant) -> None:
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
with patch( with patch(
"homeassistant.components.steamist.Steamist.async_get_status", "homeassistant.components.steamist.Steamist.async_get_status",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
await async_setup_component(hass, steamist.DOMAIN, {steamist.DOMAIN: {}}) await async_setup_component(hass, steamist.DOMAIN, {steamist.DOMAIN: {}})
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -1,5 +1,4 @@
"""Test the System Bridge config flow.""" """Test the System Bridge config flow."""
import asyncio
from ipaddress import ip_address from ipaddress import ip_address
from unittest.mock import patch from unittest.mock import patch
@ -231,7 +230,7 @@ async def test_form_timeout_cannot_connect(hass: HomeAssistant) -> None:
"homeassistant.components.system_bridge.config_flow.WebSocketClient.connect" "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
), patch( ), patch(
"systembridgeconnector.websocket_client.WebSocketClient.get_data", "systembridgeconnector.websocket_client.WebSocketClient.get_data",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
), patch( ), patch(
"systembridgeconnector.websocket_client.WebSocketClient.listen", "systembridgeconnector.websocket_client.WebSocketClient.listen",
): ):

View file

@ -1,5 +1,4 @@
"""Tests for the system health component init.""" """Tests for the system health component init."""
import asyncio
from unittest.mock import AsyncMock, Mock, patch from unittest.mock import AsyncMock, Mock, patch
from aiohttp.client_exceptions import ClientError from aiohttp.client_exceptions import ClientError
@ -92,7 +91,7 @@ async def test_info_endpoint_register_callback_timeout(
"""Test that the info endpoint timing out.""" """Test that the info endpoint timing out."""
async def mock_info(hass): async def mock_info(hass):
raise asyncio.TimeoutError raise TimeoutError
hass.components.system_health.async_register_info("lovelace", mock_info) hass.components.system_health.async_register_info("lovelace", mock_info)
assert await async_setup_component(hass, "system_health", {}) assert await async_setup_component(hass, "system_health", {})
@ -128,7 +127,7 @@ async def test_platform_loading(
"""Test registering via platform.""" """Test registering via platform."""
aioclient_mock.get("http://example.com/status", text="") aioclient_mock.get("http://example.com/status", text="")
aioclient_mock.get("http://example.com/status_fail", exc=ClientError) aioclient_mock.get("http://example.com/status_fail", exc=ClientError)
aioclient_mock.get("http://example.com/timeout", exc=asyncio.TimeoutError) aioclient_mock.get("http://example.com/timeout", exc=TimeoutError)
hass.config.components.add("fake_integration") hass.config.components.add("fake_integration")
mock_platform( mock_platform(
hass, hass,