Use builtin TimeoutError [t-z] (#109683)

This commit is contained in:
Marc Mueller 2024-02-05 12:20:36 +01:00 committed by GitHub
parent 438d3b01b9
commit 8b0c9d3d18
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
63 changed files with 88 additions and 122 deletions

View file

@ -94,7 +94,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
auth_url = await self.hass.async_add_executor_job(self._get_auth_url)
if not auth_url:
return self.async_abort(reason="unknown_authorize_url_generation")
except asyncio.TimeoutError:
except TimeoutError:
return self.async_abort(reason="authorize_url_timeout")
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected error generating auth url")

View file

@ -136,7 +136,7 @@ class TtnDataStorage:
async with asyncio.timeout(DEFAULT_TIMEOUT):
response = await session.get(self._url, headers=self._headers)
except (asyncio.TimeoutError, aiohttp.ClientError):
except (TimeoutError, aiohttp.ClientError):
_LOGGER.error("Error while accessing: %s", self._url)
return None

View file

@ -1,5 +1,4 @@
"""Support for Tibber."""
import asyncio
import logging
import aiohttp
@ -55,7 +54,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await tibber_connection.update_info()
except (
asyncio.TimeoutError,
TimeoutError,
aiohttp.ClientError,
tibber.RetryableHttpException,
) as err:

View file

@ -1,7 +1,6 @@
"""Adds config flow for Tibber integration."""
from __future__ import annotations
import asyncio
from typing import Any
import aiohttp
@ -46,7 +45,7 @@ class TibberConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
try:
await tibber_connection.update_info()
except asyncio.TimeoutError:
except TimeoutError:
errors[CONF_ACCESS_TOKEN] = ERR_TIMEOUT
except tibber.InvalidLogin:
errors[CONF_ACCESS_TOKEN] = ERR_TOKEN

View file

@ -1,7 +1,6 @@
"""Support for Tibber notifications."""
from __future__ import annotations
import asyncio
from collections.abc import Callable
import logging
from typing import Any
@ -41,5 +40,5 @@ class TibberNotificationService(BaseNotificationService):
title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
try:
await self._notify(title=title, message=message)
except asyncio.TimeoutError:
except TimeoutError:
_LOGGER.error("Timeout sending message with Tibber")

View file

@ -1,7 +1,6 @@
"""Support for Tibber sensors."""
from __future__ import annotations
import asyncio
import datetime
from datetime import timedelta
import logging
@ -255,7 +254,7 @@ async def async_setup_entry(
for home in tibber_connection.get_homes(only_active=False):
try:
await home.update_info()
except asyncio.TimeoutError as err:
except TimeoutError as err:
_LOGGER.error("Timeout connecting to Tibber home: %s ", err)
raise PlatformNotReady() from err
except aiohttp.ClientError as err:
@ -399,7 +398,7 @@ class TibberSensorElPrice(TibberSensor):
_LOGGER.debug("Fetching data")
try:
await self._tibber_home.update_info_and_price_info()
except (asyncio.TimeoutError, aiohttp.ClientError):
except (TimeoutError, aiohttp.ClientError):
return
data = self._tibber_home.info["viewer"]["home"]
self._attr_extra_state_attributes["app_nickname"] = data["appNickname"]

View file

@ -144,7 +144,7 @@ async def authenticate(
key = await api_factory.generate_psk(security_code)
except RequestError as err:
raise AuthError("invalid_security_code") from err
except asyncio.TimeoutError as err:
except TimeoutError as err:
raise AuthError("timeout") from err
finally:
await api_factory.shutdown()

View file

@ -1,6 +1,5 @@
"""The twinkly component."""
import asyncio
from aiohttp import ClientError
from ttls.client import Twinkly
@ -31,7 +30,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try:
device_info = await client.get_details()
software_version = await client.get_firmware_version()
except (asyncio.TimeoutError, ClientError) as exception:
except (TimeoutError, ClientError) as exception:
raise ConfigEntryNotReady from exception
hass.data[DOMAIN][entry.entry_id] = {

View file

@ -1,7 +1,6 @@
"""Config flow to configure the Twinkly integration."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
@ -40,7 +39,7 @@ class TwinklyConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
device_info = await Twinkly(
host, async_get_clientsession(self.hass)
).get_details()
except (asyncio.TimeoutError, ClientError):
except (TimeoutError, ClientError):
errors[CONF_HOST] = "cannot_connect"
else:
await self.async_set_unique_id(device_info[DEV_ID])

View file

@ -1,7 +1,6 @@
"""The Twinkly light component."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
@ -282,7 +281,7 @@ class TwinklyLight(LightEntity):
# We don't use the echo API to track the availability since
# we already have to pull the device to get its state.
self._attr_available = True
except (asyncio.TimeoutError, ClientError):
except (TimeoutError, ClientError):
# We log this as "info" as it's pretty common that the Christmas
# light are not reachable in July
if self._attr_available:

View file

@ -1,7 +1,6 @@
"""Config flow for Ukraine Alarm."""
from __future__ import annotations
import asyncio
import logging
import aiohttp
@ -50,7 +49,7 @@ class UkraineAlarmConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
except aiohttp.ClientError as ex:
reason = "unknown"
unknown_err_msg = str(ex)
except asyncio.TimeoutError:
except TimeoutError:
reason = "timeout"
if not reason and not regions:

View file

@ -409,7 +409,7 @@ class UniFiController:
async_dispatcher_send(self.hass, self.signal_reachable)
except (
asyncio.TimeoutError,
TimeoutError,
aiounifi.BadGateway,
aiounifi.ServiceUnavailable,
aiounifi.AiounifiException,
@ -516,7 +516,7 @@ async def get_unifi_controller(
raise AuthenticationRequired from err
except (
asyncio.TimeoutError,
TimeoutError,
aiounifi.BadGateway,
aiounifi.Forbidden,
aiounifi.ServiceUnavailable,

View file

@ -1,7 +1,6 @@
"""UniFi Protect Platform."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
@ -64,7 +63,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
nvr_info = await protect.get_nvr()
except NotAuthorized as err:
raise ConfigEntryAuthFailed(err) from err
except (asyncio.TimeoutError, ClientError, ServerDisconnectedError) as err:
except (TimeoutError, ClientError, ServerDisconnectedError) as err:
raise ConfigEntryNotReady from err
if nvr_info.version < MIN_REQUIRED_PROTECT_V:

View file

@ -43,7 +43,7 @@ async def _validate_input(data):
upb.connect(_connected_callback)
with suppress(asyncio.TimeoutError):
with suppress(TimeoutError):
async with asyncio.timeout(VALIDATE_TIMEOUT):
await connected_event.wait()

View file

@ -72,7 +72,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try:
async with asyncio.timeout(10):
await device_discovered_event.wait()
except asyncio.TimeoutError as err:
except TimeoutError as err:
raise ConfigEntryNotReady(f"Device not discovered: {usn}") from err
finally:
cancel_discovered_callback()

View file

@ -84,7 +84,7 @@ async def async_http_request(hass, uri):
return {"error": req.status}
json_response = await req.json()
return json_response
except (asyncio.TimeoutError, aiohttp.ClientError) as exc:
except (TimeoutError, aiohttp.ClientError) as exc:
_LOGGER.error("Cannot connect to ViaggiaTreno API endpoint: %s", exc)
except ValueError:
_LOGGER.error("Received non-JSON data from ViaggiaTreno API endpoint")

View file

@ -209,7 +209,7 @@ class VoiceRSSProvider(Provider):
_LOGGER.error("Error receive %s from VoiceRSS", str(data, "utf-8"))
return (None, None)
except (asyncio.TimeoutError, aiohttp.ClientError):
except (TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout for VoiceRSS API")
return (None, None)

View file

@ -259,7 +259,7 @@ class PipelineRtpDatagramProtocol(RtpDatagramProtocol):
if self.processing_tone_enabled:
await self._play_processing_tone()
except asyncio.TimeoutError:
except TimeoutError:
# Expected after caller hangs up
_LOGGER.debug("Audio timeout")
self._session_id = None
@ -304,7 +304,7 @@ class PipelineRtpDatagramProtocol(RtpDatagramProtocol):
_LOGGER.debug("Pipeline finished")
except PipelineNotFound:
_LOGGER.warning("Pipeline not found")
except asyncio.TimeoutError:
except TimeoutError:
# Expected after caller hangs up
_LOGGER.debug("Pipeline timeout")
self._session_id = None
@ -444,7 +444,7 @@ class PipelineRtpDatagramProtocol(RtpDatagramProtocol):
async with asyncio.timeout(tts_seconds + self.tts_extra_timeout):
# TTS audio is 16Khz 16-bit mono
await self._async_send_audio(audio_bytes)
except asyncio.TimeoutError as err:
except TimeoutError as err:
_LOGGER.warning("TTS timeout")
raise err
finally:

View file

@ -153,7 +153,7 @@ async def websocket_entity_info(
try:
async with asyncio.timeout(TIMEOUT_FETCH_WAKE_WORDS):
wake_words = await entity.get_supported_wake_words()
except asyncio.TimeoutError:
except TimeoutError:
connection.send_error(
msg["id"], websocket_api.const.ERR_TIMEOUT, "Timeout fetching wake words"
)

View file

@ -36,7 +36,7 @@ async def _async_can_discover_devices() -> bool:
try:
client.on(EVENT_DEVICE_DISCOVERED, _async_found)
await future_event
except asyncio.TimeoutError:
except TimeoutError:
return False
return True

View file

@ -32,6 +32,6 @@ WEBOSTV_EXCEPTIONS = (
ConnectionClosedOK,
ConnectionRefusedError,
WebOsTvCommandError,
asyncio.TimeoutError,
TimeoutError,
asyncio.CancelledError,
)

View file

@ -474,7 +474,7 @@ class LgWebOSMediaPlayerEntity(RestoreEntity, MediaPlayerEntity):
content = None
websession = async_get_clientsession(self.hass)
with suppress(asyncio.TimeoutError):
with suppress(TimeoutError):
async with asyncio.timeout(10):
response = await websession.get(url, ssl=False)
if response.status == HTTPStatus.OK:

View file

@ -1,7 +1,6 @@
"""Connection session."""
from __future__ import annotations
import asyncio
from collections.abc import Callable, Hashable
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any
@ -266,7 +265,7 @@ class ActiveConnection:
elif isinstance(err, vol.Invalid):
code = const.ERR_INVALID_FORMAT
err_message = vol.humanize.humanize_error(msg, err)
elif isinstance(err, asyncio.TimeoutError):
elif isinstance(err, TimeoutError):
code = const.ERR_TIMEOUT
err_message = "Timeout"
elif isinstance(err, HomeAssistantError):

View file

@ -282,7 +282,7 @@ class WebSocketHandler:
try:
async with asyncio.timeout(10):
await wsock.prepare(request)
except asyncio.TimeoutError:
except TimeoutError:
self._logger.warning("Timeout preparing request from %s", request.remote)
return wsock
@ -310,7 +310,7 @@ class WebSocketHandler:
# Auth Phase
try:
msg = await wsock.receive(10)
except asyncio.TimeoutError as err:
except TimeoutError as err:
disconnect_warn = "Did not receive auth message within 10 seconds"
raise Disconnect from err

View file

@ -1,5 +1,4 @@
"""The Whirlpool Appliances integration."""
import asyncio
from dataclasses import dataclass
import logging
@ -35,7 +34,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
)
try:
await auth.do_auth(store=False)
except (ClientError, asyncio.TimeoutError) as ex:
except (ClientError, TimeoutError) as ex:
raise ConfigEntryNotReady("Cannot connect") from ex
if not auth.is_access_token_valid():

View file

@ -1,7 +1,6 @@
"""Config flow for Whirlpool Appliances integration."""
from __future__ import annotations
import asyncio
from collections.abc import Mapping
import logging
from typing import Any
@ -48,7 +47,7 @@ async def validate_input(
auth = Auth(backend_selector, data[CONF_USERNAME], data[CONF_PASSWORD], session)
try:
await auth.do_auth()
except (asyncio.TimeoutError, ClientError) as exc:
except (TimeoutError, ClientError) as exc:
raise CannotConnect from exc
if not auth.is_access_token_valid():
@ -92,7 +91,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
await validate_input(self.hass, data)
except InvalidAuth:
errors["base"] = "invalid_auth"
except (CannotConnect, asyncio.TimeoutError):
except (CannotConnect, TimeoutError):
errors["base"] = "cannot_connect"
else:
self.hass.config_entries.async_update_entry(

View file

@ -97,7 +97,7 @@ class WorxLandroidSensor(SensorEntity):
async with asyncio.timeout(self.timeout):
auth = aiohttp.helpers.BasicAuth("admin", self.pin)
mower_response = await session.get(self.url, auth=auth)
except (asyncio.TimeoutError, aiohttp.ClientError):
except (TimeoutError, aiohttp.ClientError):
if self.allow_unreachable is False:
_LOGGER.error("Error connecting to mower at %s", self.url)

View file

@ -107,7 +107,7 @@ async def load_wyoming_info(
if wyoming_info is not None:
break # for
except (asyncio.TimeoutError, OSError, WyomingError):
except (TimeoutError, OSError, WyomingError):
# Sleep and try again
await asyncio.sleep(retry_wait)

View file

@ -1,7 +1,6 @@
"""Config flow for Xiaomi Bluetooth integration."""
from __future__ import annotations
import asyncio
from collections.abc import Mapping
import dataclasses
from typing import Any
@ -96,7 +95,7 @@ class XiaomiConfigFlow(ConfigFlow, domain=DOMAIN):
self._discovery_info = await self._async_wait_for_full_advertisement(
discovery_info, device
)
except asyncio.TimeoutError:
except TimeoutError:
# This device might have a really long advertising interval
# So create a config entry for it, and if we discover it has
# encryption later, we can do a reauth
@ -220,7 +219,7 @@ class XiaomiConfigFlow(ConfigFlow, domain=DOMAIN):
self._discovery_info = await self._async_wait_for_full_advertisement(
discovery.discovery_info, discovery.device
)
except asyncio.TimeoutError:
except TimeoutError:
# This device might have a really long advertising interval
# So create a config entry for it, and if we discover
# it has encryption later, we can do a reauth

View file

@ -1,8 +1,6 @@
"""The Yale Access Bluetooth integration."""
from __future__ import annotations
import asyncio
from yalexs_ble import (
AuthError,
ConnectionInfo,
@ -89,7 +87,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await push_lock.wait_for_first_update(DEVICE_TIMEOUT)
except AuthError as ex:
raise ConfigEntryAuthFailed(str(ex)) from ex
except (YaleXSBLEError, asyncio.TimeoutError) as ex:
except (YaleXSBLEError, TimeoutError) as ex:
raise ConfigEntryNotReady(
f"{ex}; Try moving the Bluetooth adapter closer to {local_name}"
) from ex

View file

@ -139,7 +139,7 @@ class YandexSpeechKitProvider(Provider):
return (None, None)
data = await request.read()
except (asyncio.TimeoutError, aiohttp.ClientError):
except (TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout for yandex speech kit API")
return (None, None)

View file

@ -64,7 +64,7 @@ class YardianUpdateCoordinator(DataUpdateCoordinator[YardianDeviceState]):
async with asyncio.timeout(10):
return await self.controller.fetch_device_state()
except asyncio.TimeoutError as e:
except TimeoutError as e:
raise UpdateFailed("Communication with Device was time out") from e
except NotAuthorizedException as e:
raise UpdateFailed("Invalid access token") from e

View file

@ -1,7 +1,6 @@
"""Support for Xiaomi Yeelight WiFi color bulb."""
from __future__ import annotations
import asyncio
import logging
import voluptuous as vol
@ -214,7 +213,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try:
device = await _async_get_device(hass, entry.data[CONF_HOST], entry)
await _async_initialize(hass, entry, device)
except (asyncio.TimeoutError, OSError, BulbException) as ex:
except (TimeoutError, OSError, BulbException) as ex:
raise ConfigEntryNotReady from ex
found_unique_id = device.unique_id

View file

@ -1,7 +1,6 @@
"""Config flow for Yeelight integration."""
from __future__ import annotations
import asyncio
import logging
from urllib.parse import urlparse
@ -268,7 +267,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
await bulb.async_listen(lambda _: True)
await bulb.async_get_properties()
await bulb.async_stop_listening()
except (asyncio.TimeoutError, yeelight.BulbException) as err:
except (TimeoutError, yeelight.BulbException) as err:
_LOGGER.debug("Failed to get properties from %s: %s", host, err)
raise CannotConnect from err
_LOGGER.debug("Get properties: %s", bulb.last_properties)

View file

@ -1,7 +1,6 @@
"""Support for Xiaomi Yeelight WiFi color bulb."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
@ -176,7 +175,7 @@ class YeelightDevice:
self._available = True
if not self._initialized:
self._initialized = True
except asyncio.TimeoutError as ex:
except TimeoutError as ex:
_LOGGER.debug(
"timed out while trying to update device %s, %s: %s",
self._host,

View file

@ -1,7 +1,6 @@
"""Light platform support for yeelight."""
from __future__ import annotations
import asyncio
from collections.abc import Callable, Coroutine
import logging
import math
@ -255,7 +254,7 @@ def _async_cmd(
try:
_LOGGER.debug("Calling %s with %s %s", func, args, kwargs)
return await func(self, *args, **kwargs)
except asyncio.TimeoutError as ex:
except TimeoutError as ex:
# The wifi likely dropped, so we want to retry once since
# python-yeelight will auto reconnect
if attempts == 0:

View file

@ -155,7 +155,7 @@ class YeelightScanner:
for listener in self._listeners:
listener.async_search((host, SSDP_TARGET[1]))
with contextlib.suppress(asyncio.TimeoutError):
with contextlib.suppress(TimeoutError):
async with asyncio.timeout(DISCOVERY_TIMEOUT):
await host_event.wait()

View file

@ -118,7 +118,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
)
except YoLinkAuthFailError as yl_auth_err:
raise ConfigEntryAuthFailed from yl_auth_err
except (YoLinkClientError, asyncio.TimeoutError) as err:
except (YoLinkClientError, TimeoutError) as err:
raise ConfigEntryNotReady from err
device_coordinators = {}

View file

@ -1,7 +1,6 @@
"""Cluster handlers module for Zigbee Home Automation."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Coroutine, Iterator
import contextlib
from enum import Enum
@ -62,7 +61,7 @@ def wrap_zigpy_exceptions() -> Iterator[None]:
"""Wrap zigpy exceptions in `HomeAssistantError` exceptions."""
try:
yield
except asyncio.TimeoutError as exc:
except TimeoutError as exc:
raise HomeAssistantError(
"Failed to send request: device did not respond"
) from exc
@ -214,7 +213,7 @@ class ClusterHandler(LogMixin):
},
},
)
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
except (zigpy.exceptions.ZigbeeException, TimeoutError) as ex:
self.debug(
"Failed to bind '%s' cluster: %s",
self.cluster.ep_attribute,
@ -275,7 +274,7 @@ class ClusterHandler(LogMixin):
try:
res = await self.cluster.configure_reporting_multiple(reports, **kwargs)
self._configure_reporting_status(reports, res[0], event_data)
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
except (zigpy.exceptions.ZigbeeException, TimeoutError) as ex:
self.debug(
"failed to set reporting on '%s' cluster for: %s",
self.cluster.ep_attribute,
@ -518,7 +517,7 @@ class ClusterHandler(LogMixin):
manufacturer=manufacturer,
)
result.update(read)
except (asyncio.TimeoutError, zigpy.exceptions.ZigbeeException) as ex:
except (TimeoutError, zigpy.exceptions.ZigbeeException) as ex:
self.debug(
"failed to get attributes '%s' on '%s' cluster: %s",
chunk,

View file

@ -1,5 +1,4 @@
"""Lightlink cluster handlers module for Zigbee Home Automation."""
import asyncio
import zigpy.exceptions
from zigpy.zcl.clusters.lightlink import LightLink
@ -32,7 +31,7 @@ class LightLinkClusterHandler(ClusterHandler):
try:
rsp = await self.cluster.get_group_identifiers(0)
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as exc:
except (zigpy.exceptions.ZigbeeException, TimeoutError) as exc:
self.warning("Couldn't get list of groups: %s", str(exc))
return

View file

@ -870,7 +870,7 @@ class ZHADevice(LogMixin):
# store it, so we cannot rely on it existing after being written. This is
# only done to make the ZCL command valid.
await self._zigpy_device.add_to_group(group_id, name=f"0x{group_id:04X}")
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
except (zigpy.exceptions.ZigbeeException, TimeoutError) as ex:
self.debug(
"Failed to add device '%s' to group: 0x%04x ex: %s",
self._zigpy_device.ieee,
@ -882,7 +882,7 @@ class ZHADevice(LogMixin):
"""Remove this device from the provided zigbee group."""
try:
await self._zigpy_device.remove_from_group(group_id)
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
except (zigpy.exceptions.ZigbeeException, TimeoutError) as ex:
self.debug(
"Failed to remove device '%s' from group: 0x%04x ex: %s",
self._zigpy_device.ieee,
@ -898,7 +898,7 @@ class ZHADevice(LogMixin):
await self._zigpy_device.endpoints[endpoint_id].add_to_group(
group_id, name=f"0x{group_id:04X}"
)
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
except (zigpy.exceptions.ZigbeeException, TimeoutError) as ex:
self.debug(
"Failed to add endpoint: %s for device: '%s' to group: 0x%04x ex: %s",
endpoint_id,
@ -913,7 +913,7 @@ class ZHADevice(LogMixin):
"""Remove the device endpoint from the provided zigbee group."""
try:
await self._zigpy_device.endpoints[endpoint_id].remove_from_group(group_id)
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
except (zigpy.exceptions.ZigbeeException, TimeoutError) as ex:
self.debug(
(
"Failed to remove endpoint: %s for device '%s' from group: 0x%04x"

View file

@ -112,7 +112,7 @@ class ZHAGroupMember(LogMixin):
await self._zha_device.device.endpoints[
self._endpoint_id
].remove_from_group(self._zha_group.group_id)
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
except (zigpy.exceptions.ZigbeeException, TimeoutError) as ex:
self.debug(
(
"Failed to remove endpoint: %s for device '%s' from group: 0x%04x"

View file

@ -168,7 +168,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
translation_key="invalid_server_version",
)
raise ConfigEntryNotReady(f"Invalid server version: {err}") from err
except (asyncio.TimeoutError, BaseZwaveJSServerError) as err:
except (TimeoutError, BaseZwaveJSServerError) as err:
raise ConfigEntryNotReady(f"Failed to connect: {err}") from err
async_delete_issue(hass, DOMAIN, "invalid_server_version")

View file

@ -118,7 +118,7 @@ async def async_get_version_info(hass: HomeAssistant, ws_address: str) -> Versio
version_info: VersionInfo = await get_server_version(
ws_address, async_get_clientsession(hass)
)
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
except (TimeoutError, aiohttp.ClientError) as err:
# We don't want to spam the log if the add-on isn't started
# or takes a long time to start.
_LOGGER.debug("Failed to connect to Z-Wave JS server: %s", err)

View file

@ -1,6 +1,5 @@
# flake8: noqa pylint: skip-file
"""Tests for the TelldusLive config flow."""
import asyncio
from unittest.mock import Mock, patch
import pytest
@ -224,7 +223,7 @@ async def test_abort_if_timeout_generating_auth_url(
hass: HomeAssistant, mock_tellduslive
) -> None:
"""Test abort if generating authorize url timeout."""
flow = init_config_flow(hass, side_effect=asyncio.TimeoutError)
flow = init_config_flow(hass, side_effect=TimeoutError)
result = await flow.async_step_user()
assert result["type"] == data_entry_flow.FlowResultType.ABORT

View file

@ -1,5 +1,4 @@
"""Test the Ukraine Alarm config flow."""
import asyncio
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
@ -271,7 +270,7 @@ async def test_unknown_client_error(
async def test_timeout_error(hass: HomeAssistant, mock_get_regions: AsyncMock) -> None:
"""Test timeout error."""
mock_get_regions.side_effect = asyncio.TimeoutError
mock_get_regions.side_effect = TimeoutError
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)

View file

@ -1,5 +1,4 @@
"""Test UniFi Network."""
import asyncio
from copy import deepcopy
from datetime import timedelta
from http import HTTPStatus
@ -421,7 +420,7 @@ async def test_reconnect_mechanism(
@pytest.mark.parametrize(
"exception",
[
asyncio.TimeoutError,
TimeoutError,
aiounifi.BadGateway,
aiounifi.ServiceUnavailable,
aiounifi.AiounifiException,
@ -459,7 +458,7 @@ async def test_get_unifi_controller_verify_ssl_false(hass: HomeAssistant) -> Non
@pytest.mark.parametrize(
("side_effect", "raised_exception"),
[
(asyncio.TimeoutError, CannotConnect),
(TimeoutError, CannotConnect),
(aiounifi.BadGateway, CannotConnect),
(aiounifi.Forbidden, CannotConnect),
(aiounifi.ServiceUnavailable, CannotConnect),

View file

@ -1,5 +1,4 @@
"""The tests for the VoiceRSS speech platform."""
import asyncio
from http import HTTPStatus
import pytest
@ -213,7 +212,7 @@ async def test_service_say_timeout(
"""Test service call say with http timeout."""
calls = async_mock_service(hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
aioclient_mock.post(URL, data=FORM_DATA, exc=asyncio.TimeoutError())
aioclient_mock.post(URL, data=FORM_DATA, exc=TimeoutError())
config = {tts.DOMAIN: {"platform": "voicerss", "api_key": "1234567xx"}}

View file

@ -319,7 +319,7 @@ async def test_tts_timeout(
async def send_tts(*args, **kwargs):
# Call original then end test successfully
with pytest.raises(asyncio.TimeoutError):
with pytest.raises(TimeoutError):
await original_send_tts(*args, **kwargs)
done.set()

View file

@ -55,7 +55,7 @@ async def test_devices_with_mocks(
@pytest.mark.parametrize(
("exception", "error_msg"),
[
(asyncio.TimeoutError, ERROR_MSG_NO_DEVICE_FOUND),
(TimeoutError, ERROR_MSG_NO_DEVICE_FOUND),
(asyncio.exceptions.CancelledError, ERROR_MSG_CANNOT_CONNECT),
(AddressInUseError, ERROR_MSG_ADDRESS_IN_USE),
],

View file

@ -1,5 +1,4 @@
"""The tests for the LG webOS media player platform."""
import asyncio
from datetime import timedelta
from http import HTTPStatus
from unittest.mock import Mock
@ -469,7 +468,7 @@ async def test_client_disconnected(hass: HomeAssistant, client, monkeypatch) ->
"""Test error not raised when client is disconnected."""
await setup_webostv(hass)
monkeypatch.setattr(client, "is_connected", Mock(return_value=False))
monkeypatch.setattr(client, "connect", Mock(side_effect=asyncio.TimeoutError))
monkeypatch.setattr(client, "connect", Mock(side_effect=TimeoutError))
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=20))
await hass.async_block_till_done()
@ -495,7 +494,7 @@ async def test_control_error_handling(
# Device off, log a warning
monkeypatch.setattr(client, "is_on", False)
monkeypatch.setattr(client, "play", Mock(side_effect=asyncio.TimeoutError))
monkeypatch.setattr(client, "play", Mock(side_effect=TimeoutError))
await client.mock_state_update()
await hass.services.async_call(MP_DOMAIN, SERVICE_MEDIA_PLAY, data, True)
@ -752,7 +751,7 @@ async def test_get_image_http_error(
attrs = hass.states.get(ENTITY_ID).attributes
assert "entity_picture_local" not in attrs
aioclient_mock.get(url, exc=asyncio.TimeoutError())
aioclient_mock.get(url, exc=TimeoutError())
client = await hass_client_no_auth()
resp = await client.get(attrs["entity_picture"])

View file

@ -1,5 +1,4 @@
"""Test WebSocket Connection class."""
import asyncio
import logging
from typing import Any
from unittest.mock import AsyncMock, Mock, patch
@ -32,7 +31,7 @@ from tests.common import MockUser
"Error handling message: Invalid something. Got {'id': 5} (invalid_format) Mock User from 127.0.0.42 (Browser)",
),
(
asyncio.TimeoutError(),
TimeoutError(),
websocket_api.ERR_TIMEOUT,
"Timeout",
"Error handling message: Timeout (timeout) Mock User from 127.0.0.42 (Browser)",

View file

@ -372,7 +372,7 @@ async def test_prepare_fail(
"""Test failing to prepare."""
with patch(
"homeassistant.components.websocket_api.http.web.WebSocketResponse.prepare",
side_effect=(asyncio.TimeoutError, web.WebSocketResponse.prepare),
side_effect=(TimeoutError, web.WebSocketResponse.prepare),
), pytest.raises(ServerDisconnectedError):
await hass_ws_client(hass)

View file

@ -1,5 +1,4 @@
"""Test the Whirlpool Sixth Sense config flow."""
import asyncio
from unittest.mock import patch
import aiohttp
@ -110,7 +109,7 @@ async def test_form_auth_timeout(hass: HomeAssistant, region) -> None:
)
with patch(
"homeassistant.components.whirlpool.config_flow.Auth.do_auth",
side_effect=asyncio.TimeoutError,
side_effect=TimeoutError,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],

View file

@ -1,5 +1,4 @@
"""Test the Xiaomi config flow."""
import asyncio
from unittest.mock import patch
from xiaomi_ble import XiaomiBluetoothDeviceData as DeviceData
@ -50,7 +49,7 @@ async def test_async_step_bluetooth_valid_device_but_missing_payload(
"""Test discovery via bluetooth with a valid device but missing payload."""
with patch(
"homeassistant.components.xiaomi_ble.config_flow.async_process_advertisements",
side_effect=asyncio.TimeoutError(),
side_effect=TimeoutError(),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@ -402,7 +401,7 @@ async def test_async_step_user_short_payload(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
with patch(
"homeassistant.components.xiaomi_ble.config_flow.async_process_advertisements",
side_effect=asyncio.TimeoutError(),
side_effect=TimeoutError(),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],

View file

@ -1,5 +1,4 @@
"""The tests for the Yandex SpeechKit speech platform."""
import asyncio
from http import HTTPStatus
import pytest
@ -201,7 +200,7 @@ async def test_service_say_timeout(
aioclient_mock.get(
URL,
status=HTTPStatus.OK,
exc=asyncio.TimeoutError(),
exc=TimeoutError(),
params=url_param,
)

View file

@ -1,5 +1,4 @@
"""Test Yeelight."""
import asyncio
from datetime import timedelta
from unittest.mock import AsyncMock, patch
@ -571,7 +570,7 @@ async def test_oserror_on_first_update_results_in_unavailable(
assert hass.states.get("light.test_name").state == STATE_UNAVAILABLE
@pytest.mark.parametrize("exception", [BulbException, asyncio.TimeoutError])
@pytest.mark.parametrize("exception", [BulbException, TimeoutError])
async def test_non_oserror_exception_on_first_update(
hass: HomeAssistant, exception: Exception
) -> None:

View file

@ -1,5 +1,4 @@
"""Test the Yeelight light."""
import asyncio
from datetime import timedelta
import logging
import socket
@ -504,7 +503,7 @@ async def test_services(hass: HomeAssistant, caplog: pytest.LogCaptureFixture) -
)
assert hass.states.get(ENTITY_LIGHT).state == STATE_OFF
mocked_bulb.async_set_brightness = AsyncMock(side_effect=asyncio.TimeoutError)
mocked_bulb.async_set_brightness = AsyncMock(side_effect=TimeoutError)
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
"light",
@ -553,7 +552,7 @@ async def test_update_errors(
# Timeout usually means the bulb is overloaded with commands
# but will still respond eventually.
mocked_bulb.async_turn_off = AsyncMock(side_effect=asyncio.TimeoutError)
mocked_bulb.async_turn_off = AsyncMock(side_effect=TimeoutError)
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
"light",

View file

@ -1,5 +1,4 @@
"""Test yolink config flow."""
import asyncio
from http import HTTPStatus
from unittest.mock import patch
@ -127,7 +126,7 @@ async def test_abort_if_authorization_timeout(
with patch(
"homeassistant.components.yolink.config_entry_oauth2_flow."
"LocalOAuth2Implementation.async_generate_authorize_url",
side_effect=asyncio.TimeoutError,
side_effect=TimeoutError,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}

View file

@ -1,5 +1,4 @@
"""Test ZHA Core cluster handlers."""
import asyncio
from collections.abc import Callable
import logging
import math
@ -564,12 +563,12 @@ async def test_ep_cluster_handlers_configure(cluster_handler) -> None:
ch_1 = cluster_handler(zha_const.CLUSTER_HANDLER_ON_OFF, 6)
ch_2 = cluster_handler(zha_const.CLUSTER_HANDLER_LEVEL, 8)
ch_3 = cluster_handler(zha_const.CLUSTER_HANDLER_COLOR, 768)
ch_3.async_configure = AsyncMock(side_effect=asyncio.TimeoutError)
ch_3.async_initialize = AsyncMock(side_effect=asyncio.TimeoutError)
ch_3.async_configure = AsyncMock(side_effect=TimeoutError)
ch_3.async_initialize = AsyncMock(side_effect=TimeoutError)
ch_4 = cluster_handler(zha_const.CLUSTER_HANDLER_ON_OFF, 6)
ch_5 = cluster_handler(zha_const.CLUSTER_HANDLER_LEVEL, 8)
ch_5.async_configure = AsyncMock(side_effect=asyncio.TimeoutError)
ch_5.async_initialize = AsyncMock(side_effect=asyncio.TimeoutError)
ch_5.async_configure = AsyncMock(side_effect=TimeoutError)
ch_5.async_initialize = AsyncMock(side_effect=TimeoutError)
endpoint_mock = mock.MagicMock(spec_set=ZigpyEndpoint)
type(endpoint_mock).in_clusters = mock.PropertyMock(return_value={})
@ -959,7 +958,7 @@ async def test_quirk_id_cluster_handler(hass: HomeAssistant, caplog) -> None:
zigpy.exceptions.ZigbeeException("Zigbee exception"),
"Failed to send request: Zigbee exception",
),
(asyncio.TimeoutError(), "Failed to send request: device did not respond"),
(TimeoutError(), "Failed to send request: device did not respond"),
],
)
async def test_retry_request(

View file

@ -835,7 +835,7 @@ async def test_shade(
assert hass.states.get(entity_id).state == STATE_OPEN
# test cover stop
with patch("zigpy.zcl.Cluster.request", side_effect=asyncio.TimeoutError):
with patch("zigpy.zcl.Cluster.request", side_effect=TimeoutError):
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
COVER_DOMAIN,
@ -924,7 +924,7 @@ async def test_keen_vent(
assert hass.states.get(entity_id).state == STATE_CLOSED
# open from UI command fails
p1 = patch.object(cluster_on_off, "request", side_effect=asyncio.TimeoutError)
p1 = patch.object(cluster_on_off, "request", side_effect=TimeoutError)
p2 = patch.object(cluster_level, "request", return_value=[4, 0])
with p1, p2:

View file

@ -198,7 +198,7 @@ async def test_gateway_group_methods(
# the group entity should not have been cleaned up
assert entity_id not in hass.states.async_entity_ids(Platform.LIGHT)
with patch("zigpy.zcl.Cluster.request", side_effect=asyncio.TimeoutError):
with patch("zigpy.zcl.Cluster.request", side_effect=TimeoutError):
await zha_group.members[0].async_remove_from_group()
assert len(zha_group.members) == 1
for member in zha_group.members:

View file

@ -374,7 +374,7 @@ async def test_supervisor_discovery(
@pytest.mark.parametrize(
("discovery_info", "server_version_side_effect"),
[({"config": ADDON_DISCOVERY_INFO}, asyncio.TimeoutError())],
[({"config": ADDON_DISCOVERY_INFO}, TimeoutError())],
)
async def test_supervisor_discovery_cannot_connect(
hass: HomeAssistant, supervisor, get_addon_discovery_info
@ -1114,7 +1114,7 @@ async def test_addon_running(
(
{"config": ADDON_DISCOVERY_INFO},
None,
asyncio.TimeoutError,
TimeoutError,
None,
"cannot_connect",
),
@ -1366,7 +1366,7 @@ async def test_addon_installed_start_failure(
[
(
{"config": ADDON_DISCOVERY_INFO},
asyncio.TimeoutError,
TimeoutError,
),
(
None,