Use asyncio.timeout [core] (#98447)

This commit is contained in:
Marc Mueller 2023-08-15 15:36:05 +02:00 committed by GitHub
parent e2d2ec8817
commit a9ade1f84d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
27 changed files with 77 additions and 96 deletions

View file

@ -8,7 +8,6 @@ import logging
import platform import platform
from typing import Any from typing import Any
import async_timeout
import bleak import bleak
from bleak import BleakError from bleak import BleakError
from bleak.assigned_numbers import AdvertisementDataType from bleak.assigned_numbers import AdvertisementDataType
@ -220,7 +219,7 @@ class HaScanner(BaseHaScanner):
START_ATTEMPTS, START_ATTEMPTS,
) )
try: try:
async with async_timeout.timeout(START_TIMEOUT): async with asyncio.timeout(START_TIMEOUT):
await self.scanner.start() # type: ignore[no-untyped-call] await self.scanner.start() # type: ignore[no-untyped-call]
except InvalidMessageError as ex: except InvalidMessageError as ex:
_LOGGER.debug( _LOGGER.debug(

View file

@ -15,7 +15,6 @@ from random import SystemRandom
from typing import Any, Final, cast, final from typing import Any, Final, cast, final
from aiohttp import hdrs, web from aiohttp import hdrs, web
import async_timeout
import attr import attr
import voluptuous as vol import voluptuous as vol
@ -168,7 +167,7 @@ async def _async_get_image(
are handled. are handled.
""" """
with suppress(asyncio.CancelledError, asyncio.TimeoutError): with suppress(asyncio.CancelledError, asyncio.TimeoutError):
async with async_timeout.timeout(timeout): async with asyncio.timeout(timeout):
if image_bytes := await camera.async_camera_image( if image_bytes := await camera.async_camera_image(
width=width, height=height width=width, height=height
): ):
@ -525,7 +524,7 @@ class Camera(Entity):
self._create_stream_lock = asyncio.Lock() self._create_stream_lock = asyncio.Lock()
async with self._create_stream_lock: async with self._create_stream_lock:
if not self.stream: if not self.stream:
async with async_timeout.timeout(CAMERA_STREAM_SOURCE_TIMEOUT): async with asyncio.timeout(CAMERA_STREAM_SOURCE_TIMEOUT):
source = await self.stream_source() source = await self.stream_source()
if not source: if not source:
return None return None

View file

@ -10,7 +10,6 @@ import logging
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
import aiohttp import aiohttp
import async_timeout
from hass_nabucasa import Cloud, cloud_api from hass_nabucasa import Cloud, cloud_api
from yarl import URL from yarl import URL
@ -501,7 +500,7 @@ class CloudAlexaConfig(alexa_config.AbstractConfig):
) )
try: try:
async with async_timeout.timeout(10): async with asyncio.timeout(10):
await asyncio.wait(tasks, return_when=asyncio.ALL_COMPLETED) await asyncio.wait(tasks, return_when=asyncio.ALL_COMPLETED)
return True return True

View file

@ -10,7 +10,6 @@ from typing import Any, Concatenate, ParamSpec, TypeVar
import aiohttp import aiohttp
from aiohttp import web from aiohttp import web
import async_timeout
import attr import attr
from hass_nabucasa import Cloud, auth, thingtalk from hass_nabucasa import Cloud, auth, thingtalk
from hass_nabucasa.const import STATE_DISCONNECTED from hass_nabucasa.const import STATE_DISCONNECTED
@ -252,7 +251,7 @@ class CloudLogoutView(HomeAssistantView):
hass = request.app["hass"] hass = request.app["hass"]
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
async with async_timeout.timeout(REQUEST_TIMEOUT): async with asyncio.timeout(REQUEST_TIMEOUT):
await cloud.logout() await cloud.logout()
return self.json_message("ok") return self.json_message("ok")
@ -292,7 +291,7 @@ class CloudRegisterView(HomeAssistantView):
if location_info.zip_code is not None: if location_info.zip_code is not None:
client_metadata["NC_ZIP_CODE"] = location_info.zip_code client_metadata["NC_ZIP_CODE"] = location_info.zip_code
async with async_timeout.timeout(REQUEST_TIMEOUT): async with asyncio.timeout(REQUEST_TIMEOUT):
await cloud.auth.async_register( await cloud.auth.async_register(
data["email"], data["email"],
data["password"], data["password"],
@ -316,7 +315,7 @@ class CloudResendConfirmView(HomeAssistantView):
hass = request.app["hass"] hass = request.app["hass"]
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
async with async_timeout.timeout(REQUEST_TIMEOUT): async with asyncio.timeout(REQUEST_TIMEOUT):
await cloud.auth.async_resend_email_confirm(data["email"]) await cloud.auth.async_resend_email_confirm(data["email"])
return self.json_message("ok") return self.json_message("ok")
@ -336,7 +335,7 @@ class CloudForgotPasswordView(HomeAssistantView):
hass = request.app["hass"] hass = request.app["hass"]
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
async with async_timeout.timeout(REQUEST_TIMEOUT): async with asyncio.timeout(REQUEST_TIMEOUT):
await cloud.auth.async_forgot_password(data["email"]) await cloud.auth.async_forgot_password(data["email"])
return self.json_message("ok") return self.json_message("ok")
@ -439,7 +438,7 @@ async def websocket_update_prefs(
if changes.get(PREF_ALEXA_REPORT_STATE): if changes.get(PREF_ALEXA_REPORT_STATE):
alexa_config = await cloud.client.get_alexa_config() alexa_config = await cloud.client.get_alexa_config()
try: try:
async with async_timeout.timeout(10): async with asyncio.timeout(10):
await alexa_config.async_get_access_token() await alexa_config.async_get_access_token()
except asyncio.TimeoutError: except asyncio.TimeoutError:
connection.send_error( connection.send_error(
@ -779,7 +778,7 @@ async def alexa_sync(
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
alexa_config = await cloud.client.get_alexa_config() alexa_config = await cloud.client.get_alexa_config()
async with async_timeout.timeout(10): async with asyncio.timeout(10):
try: try:
success = await alexa_config.async_sync_entities() success = await alexa_config.async_sync_entities()
except alexa_errors.NoTokenAvailable: except alexa_errors.NoTokenAvailable:
@ -808,7 +807,7 @@ async def thingtalk_convert(
"""Convert a query.""" """Convert a query."""
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
async with async_timeout.timeout(10): async with asyncio.timeout(10):
try: try:
connection.send_result( connection.send_result(
msg["id"], await thingtalk.async_convert(cloud, msg["query"]) msg["id"], await thingtalk.async_convert(cloud, msg["query"])

View file

@ -6,7 +6,6 @@ import logging
from typing import Any from typing import Any
from aiohttp.client_exceptions import ClientError from aiohttp.client_exceptions import ClientError
import async_timeout
from hass_nabucasa import Cloud, cloud_api from hass_nabucasa import Cloud, cloud_api
from .client import CloudClient from .client import CloudClient
@ -18,7 +17,7 @@ _LOGGER = logging.getLogger(__name__)
async def async_subscription_info(cloud: Cloud[CloudClient]) -> dict[str, Any] | None: async def async_subscription_info(cloud: Cloud[CloudClient]) -> dict[str, Any] | None:
"""Fetch the subscription info.""" """Fetch the subscription info."""
try: try:
async with async_timeout.timeout(REQUEST_TIMEOUT): async with asyncio.timeout(REQUEST_TIMEOUT):
return await cloud_api.async_subscription_info(cloud) return await cloud_api.async_subscription_info(cloud)
except asyncio.TimeoutError: except asyncio.TimeoutError:
_LOGGER.error( _LOGGER.error(
@ -39,7 +38,7 @@ async def async_migrate_paypal_agreement(
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
"""Migrate a paypal agreement from legacy.""" """Migrate a paypal agreement from legacy."""
try: try:
async with async_timeout.timeout(REQUEST_TIMEOUT): async with asyncio.timeout(REQUEST_TIMEOUT):
return await cloud_api.async_migrate_paypal_agreement(cloud) return await cloud_api.async_migrate_paypal_agreement(cloud)
except asyncio.TimeoutError: except asyncio.TimeoutError:
_LOGGER.error( _LOGGER.error(

View file

@ -12,7 +12,6 @@ import time
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
import uuid import uuid
import async_timeout
import attr import attr
import certifi import certifi
@ -918,7 +917,7 @@ class MQTT:
# may be executed first. # may be executed first.
await self._register_mid(mid) await self._register_mid(mid)
try: try:
async with async_timeout.timeout(TIMEOUT_ACK): async with asyncio.timeout(TIMEOUT_ACK):
await self._pending_operations[mid].wait() await self._pending_operations[mid].wait()
except asyncio.TimeoutError: except asyncio.TimeoutError:
_LOGGER.warning( _LOGGER.warning(

View file

@ -8,7 +8,6 @@ from pathlib import Path
import tempfile import tempfile
from typing import Any from typing import Any
import async_timeout
import voluptuous as vol import voluptuous as vol
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
@ -71,7 +70,7 @@ async def async_wait_for_mqtt_client(hass: HomeAssistant) -> bool:
return state_reached_future.result() return state_reached_future.result()
try: try:
async with async_timeout.timeout(AVAILABILITY_TIMEOUT): async with asyncio.timeout(AVAILABILITY_TIMEOUT):
# Await the client setup or an error state was received # Await the client setup or an error state was received
return await state_reached_future return await state_reached_future
except asyncio.TimeoutError: except asyncio.TimeoutError:

View file

@ -13,7 +13,6 @@ import threading
import time import time
from typing import Any, TypeVar, cast from typing import Any, TypeVar, cast
import async_timeout
import psutil_home_assistant as ha_psutil import psutil_home_assistant as ha_psutil
from sqlalchemy import create_engine, event as sqlalchemy_event, exc, select from sqlalchemy import create_engine, event as sqlalchemy_event, exc, select
from sqlalchemy.engine import Engine from sqlalchemy.engine import Engine
@ -1306,7 +1305,7 @@ class Recorder(threading.Thread):
task = DatabaseLockTask(database_locked, threading.Event(), False) task = DatabaseLockTask(database_locked, threading.Event(), False)
self.queue_task(task) self.queue_task(task)
try: try:
async with async_timeout.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 asyncio.TimeoutError as err:
task.database_unlock.set() task.database_unlock.set()

View file

@ -10,7 +10,6 @@ import logging
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from aiohttp import web from aiohttp import web
import async_timeout
import attr import attr
import numpy as np import numpy as np
@ -332,7 +331,7 @@ class StreamOutput:
async def part_recv(self, timeout: float | None = None) -> bool: async def part_recv(self, timeout: float | None = None) -> bool:
"""Wait for an event signalling the latest part segment.""" """Wait for an event signalling the latest part segment."""
try: try:
async with async_timeout.timeout(timeout): async with asyncio.timeout(timeout):
await self._part_event.wait() await self._part_event.wait()
except asyncio.TimeoutError: except asyncio.TimeoutError:
return False return False

View file

@ -9,7 +9,6 @@ import logging
from typing import Any from typing import Any
import aiohttp import aiohttp
import async_timeout
import voluptuous as vol import voluptuous as vol
from homeassistant.components import websocket_api from homeassistant.components import websocket_api
@ -73,7 +72,7 @@ async def get_integration_info(
"""Get integration system health.""" """Get integration system health."""
try: try:
assert registration.info_callback assert registration.info_callback
async with async_timeout.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 asyncio.TimeoutError:
data = {"error": {"type": "failed", "error": "timeout"}} data = {"error": {"type": "failed", "error": "timeout"}}

View file

@ -9,7 +9,6 @@ import logging
from typing import TYPE_CHECKING, Any, Final from typing import TYPE_CHECKING, Any, Final
from aiohttp import WSMsgType, web from aiohttp import WSMsgType, web
import async_timeout
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import HomeAssistantView
from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.const import EVENT_HOMEASSISTANT_STOP
@ -273,7 +272,7 @@ class WebSocketHandler:
logging_debug = logging.DEBUG logging_debug = logging.DEBUG
try: try:
async with async_timeout.timeout(10): async with asyncio.timeout(10):
await wsock.prepare(request) await wsock.prepare(request)
except asyncio.TimeoutError: except asyncio.TimeoutError:
self._logger.warning("Timeout preparing request from %s", request.remote) self._logger.warning("Timeout preparing request from %s", request.remote)
@ -302,7 +301,7 @@ class WebSocketHandler:
# Auth Phase # Auth Phase
try: try:
async with async_timeout.timeout(10): async with asyncio.timeout(10):
msg = await wsock.receive() msg = await wsock.receive()
except asyncio.TimeoutError as err: except asyncio.TimeoutError as err:
disconnect_warn = "Did not receive auth message within 10 seconds" disconnect_warn = "Did not receive auth message within 10 seconds"

View file

@ -29,7 +29,6 @@ from time import monotonic
from typing import TYPE_CHECKING, Any, Generic, ParamSpec, Self, TypeVar, cast, overload from typing import TYPE_CHECKING, Any, Generic, ParamSpec, Self, TypeVar, cast, overload
from urllib.parse import urlparse from urllib.parse import urlparse
import async_timeout
import voluptuous as vol import voluptuous as vol
import yarl import yarl
@ -806,7 +805,7 @@ class HomeAssistant:
) )
task.cancel("Home Assistant stage 2 shutdown") task.cancel("Home Assistant stage 2 shutdown")
try: try:
async with async_timeout.timeout(0.1): async with asyncio.timeout(0.1):
await task await task
except asyncio.CancelledError: except asyncio.CancelledError:
pass pass

View file

@ -13,7 +13,6 @@ import aiohttp
from aiohttp import web from aiohttp import web
from aiohttp.hdrs import CONTENT_TYPE, USER_AGENT from aiohttp.hdrs import CONTENT_TYPE, USER_AGENT
from aiohttp.web_exceptions import HTTPBadGateway, HTTPGatewayTimeout from aiohttp.web_exceptions import HTTPBadGateway, HTTPGatewayTimeout
import async_timeout
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.const import APPLICATION_NAME, EVENT_HOMEASSISTANT_CLOSE, __version__ from homeassistant.const import APPLICATION_NAME, EVENT_HOMEASSISTANT_CLOSE, __version__
@ -170,7 +169,7 @@ async def async_aiohttp_proxy_web(
) -> web.StreamResponse | None: ) -> web.StreamResponse | None:
"""Stream websession request to aiohttp web response.""" """Stream websession request to aiohttp web response."""
try: try:
async with async_timeout.timeout(timeout): async with asyncio.timeout(timeout):
req = await web_coro req = await web_coro
except asyncio.CancelledError: except asyncio.CancelledError:
@ -211,7 +210,7 @@ async def async_aiohttp_proxy_stream(
# Suppressing something went wrong fetching data, closed connection # Suppressing something went wrong fetching data, closed connection
with suppress(asyncio.TimeoutError, aiohttp.ClientError): with suppress(asyncio.TimeoutError, aiohttp.ClientError):
while hass.is_running: while hass.is_running:
async with async_timeout.timeout(timeout): async with asyncio.timeout(timeout):
data = await stream.read(buffer_size) data = await stream.read(buffer_size)
if not data: if not data:

View file

@ -16,7 +16,6 @@ import time
from typing import Any, cast from typing import Any, cast
from aiohttp import client, web from aiohttp import client, web
import async_timeout
import jwt import jwt
import voluptuous as vol import voluptuous as vol
from yarl import URL from yarl import URL
@ -287,7 +286,7 @@ class AbstractOAuth2FlowHandler(config_entries.ConfigFlow, metaclass=ABCMeta):
return self.async_external_step_done(next_step_id=next_step) return self.async_external_step_done(next_step_id=next_step)
try: try:
async with async_timeout.timeout(OAUTH_AUTHORIZE_URL_TIMEOUT_SEC): async with asyncio.timeout(OAUTH_AUTHORIZE_URL_TIMEOUT_SEC):
url = await self.async_generate_authorize_url() url = await self.async_generate_authorize_url()
except asyncio.TimeoutError as err: except asyncio.TimeoutError as err:
_LOGGER.error("Timeout generating authorize url: %s", err) _LOGGER.error("Timeout generating authorize url: %s", err)
@ -311,7 +310,7 @@ class AbstractOAuth2FlowHandler(config_entries.ConfigFlow, metaclass=ABCMeta):
_LOGGER.debug("Creating config entry from external data") _LOGGER.debug("Creating config entry from external data")
try: try:
async with async_timeout.timeout(OAUTH_TOKEN_TIMEOUT_SEC): async with asyncio.timeout(OAUTH_TOKEN_TIMEOUT_SEC):
token = await self.flow_impl.async_resolve_external_data( token = await self.flow_impl.async_resolve_external_data(
self.external_data self.external_data
) )

View file

@ -13,7 +13,6 @@ import logging
from types import MappingProxyType from types import MappingProxyType
from typing import Any, TypedDict, TypeVar, cast from typing import Any, TypedDict, TypeVar, cast
import async_timeout
import voluptuous as vol import voluptuous as vol
from homeassistant import exceptions from homeassistant import exceptions
@ -574,7 +573,7 @@ class _ScriptRun:
self._changed() self._changed()
trace_set_result(delay=delay, done=False) trace_set_result(delay=delay, done=False)
try: try:
async with async_timeout.timeout(delay): async with asyncio.timeout(delay):
await self._stop.wait() await self._stop.wait()
except asyncio.TimeoutError: except asyncio.TimeoutError:
trace_set_result(delay=delay, done=True) trace_set_result(delay=delay, done=True)
@ -602,9 +601,10 @@ class _ScriptRun:
@callback @callback
def async_script_wait(entity_id, from_s, to_s): def async_script_wait(entity_id, from_s, to_s):
"""Handle script after template condition is true.""" """Handle script after template condition is true."""
# pylint: disable=protected-access
wait_var = self._variables["wait"] wait_var = self._variables["wait"]
if to_context and to_context.deadline: if to_context and to_context._when:
wait_var["remaining"] = to_context.deadline - self._hass.loop.time() wait_var["remaining"] = to_context._when - self._hass.loop.time()
else: else:
wait_var["remaining"] = timeout wait_var["remaining"] = timeout
wait_var["completed"] = True wait_var["completed"] = True
@ -621,7 +621,7 @@ class _ScriptRun:
self._hass.async_create_task(flag.wait()) for flag in (self._stop, done) self._hass.async_create_task(flag.wait()) for flag in (self._stop, done)
] ]
try: try:
async with async_timeout.timeout(timeout) as to_context: async with asyncio.timeout(timeout) as to_context:
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
except asyncio.TimeoutError as ex: except asyncio.TimeoutError as ex:
self._variables["wait"]["remaining"] = 0.0 self._variables["wait"]["remaining"] = 0.0
@ -971,9 +971,10 @@ class _ScriptRun:
done = asyncio.Event() done = asyncio.Event()
async def async_done(variables, context=None): async def async_done(variables, context=None):
# pylint: disable=protected-access
wait_var = self._variables["wait"] wait_var = self._variables["wait"]
if to_context and to_context.deadline: if to_context and to_context._when:
wait_var["remaining"] = to_context.deadline - self._hass.loop.time() wait_var["remaining"] = to_context._when - self._hass.loop.time()
else: else:
wait_var["remaining"] = timeout wait_var["remaining"] = timeout
wait_var["trigger"] = variables["trigger"] wait_var["trigger"] = variables["trigger"]
@ -1000,7 +1001,7 @@ class _ScriptRun:
self._hass.async_create_task(flag.wait()) for flag in (self._stop, done) self._hass.async_create_task(flag.wait()) for flag in (self._stop, done)
] ]
try: try:
async with async_timeout.timeout(timeout) as to_context: async with asyncio.timeout(timeout) as to_context:
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
except asyncio.TimeoutError as ex: except asyncio.TimeoutError as ex:
self._variables["wait"]["remaining"] = 0.0 self._variables["wait"]["remaining"] = 0.0

View file

@ -34,7 +34,6 @@ from typing import (
from urllib.parse import urlencode as urllib_urlencode from urllib.parse import urlencode as urllib_urlencode
import weakref import weakref
import async_timeout
from awesomeversion import AwesomeVersion from awesomeversion import AwesomeVersion
import jinja2 import jinja2
from jinja2 import pass_context, pass_environment, pass_eval_context from jinja2 import pass_context, pass_environment, pass_eval_context
@ -651,7 +650,7 @@ class Template:
try: try:
template_render_thread = ThreadWithException(target=_render_template) template_render_thread = ThreadWithException(target=_render_template)
template_render_thread.start() template_render_thread.start()
async with async_timeout.timeout(timeout): async with asyncio.timeout(timeout):
await finish_event.wait() await finish_event.wait()
if self._exc_info: if self._exc_info:
raise TemplateError(self._exc_info[1].with_traceback(self._exc_info[2])) raise TemplateError(self._exc_info[1].with_traceback(self._exc_info[2]))

View file

@ -1,7 +1,7 @@
"""The tests for the group cover platform.""" """The tests for the group cover platform."""
import asyncio
from datetime import timedelta from datetime import timedelta
import async_timeout
import pytest import pytest
from homeassistant.components.cover import ( from homeassistant.components.cover import (
@ -828,7 +828,7 @@ async def test_nested_group(hass: HomeAssistant) -> None:
assert state.attributes.get(ATTR_ENTITY_ID) == ["cover.bedroom_group"] assert state.attributes.get(ATTR_ENTITY_ID) == ["cover.bedroom_group"]
# Test controlling the nested group # Test controlling the nested group
async with async_timeout.timeout(0.5): async with asyncio.timeout(0.5):
await hass.services.async_call( await hass.services.async_call(
DOMAIN, DOMAIN,
SERVICE_CLOSE_COVER, SERVICE_CLOSE_COVER,

View file

@ -1,7 +1,7 @@
"""The tests for the group fan platform.""" """The tests for the group fan platform."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
import async_timeout
import pytest import pytest
from homeassistant import config as hass_config from homeassistant import config as hass_config
@ -576,7 +576,7 @@ async def test_nested_group(hass: HomeAssistant) -> None:
assert state.attributes.get(ATTR_ENTITY_ID) == ["fan.bedroom_group"] assert state.attributes.get(ATTR_ENTITY_ID) == ["fan.bedroom_group"]
# Test controlling the nested group # Test controlling the nested group
async with async_timeout.timeout(0.5): async with asyncio.timeout(0.5):
await hass.services.async_call( await hass.services.async_call(
DOMAIN, DOMAIN,
SERVICE_TURN_ON, SERVICE_TURN_ON,

View file

@ -1,7 +1,7 @@
"""The tests for the Group Light platform.""" """The tests for the Group Light platform."""
import asyncio
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
import async_timeout
import pytest import pytest
from homeassistant import config as hass_config from homeassistant import config as hass_config
@ -1643,7 +1643,7 @@ async def test_nested_group(hass: HomeAssistant) -> None:
assert state.attributes.get(ATTR_ENTITY_ID) == ["light.bedroom_group"] assert state.attributes.get(ATTR_ENTITY_ID) == ["light.bedroom_group"]
# Test controlling the nested group # Test controlling the nested group
async with async_timeout.timeout(0.5): async with asyncio.timeout(0.5):
await hass.services.async_call( await hass.services.async_call(
LIGHT_DOMAIN, LIGHT_DOMAIN,
SERVICE_TOGGLE, SERVICE_TOGGLE,

View file

@ -1,7 +1,7 @@
"""The tests for the Media group platform.""" """The tests for the Media group platform."""
import asyncio
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
import async_timeout
import pytest import pytest
from homeassistant.components.group import DOMAIN from homeassistant.components.group import DOMAIN
@ -583,7 +583,7 @@ async def test_nested_group(hass: HomeAssistant) -> None:
assert state.attributes.get(ATTR_ENTITY_ID) == ["media_player.group_1"] assert state.attributes.get(ATTR_ENTITY_ID) == ["media_player.group_1"]
# Test controlling the nested group # Test controlling the nested group
async with async_timeout.timeout(0.5): async with asyncio.timeout(0.5):
await hass.services.async_call( await hass.services.async_call(
MEDIA_DOMAIN, MEDIA_DOMAIN,
SERVICE_TURN_OFF, SERVICE_TURN_OFF,

View file

@ -1,8 +1,7 @@
"""The tests for the Group Switch platform.""" """The tests for the Group Switch platform."""
import asyncio
from unittest.mock import patch from unittest.mock import patch
import async_timeout
from homeassistant import config as hass_config from homeassistant import config as hass_config
from homeassistant.components.group import DOMAIN, SERVICE_RELOAD from homeassistant.components.group import DOMAIN, SERVICE_RELOAD
from homeassistant.components.switch import ( from homeassistant.components.switch import (
@ -445,7 +444,7 @@ async def test_nested_group(hass: HomeAssistant) -> None:
assert state.attributes.get(ATTR_ENTITY_ID) == ["switch.some_group"] assert state.attributes.get(ATTR_ENTITY_ID) == ["switch.some_group"]
# Test controlling the nested group # Test controlling the nested group
async with async_timeout.timeout(0.5): async with asyncio.timeout(0.5):
await hass.services.async_call( await hass.services.async_call(
SWITCH_DOMAIN, SWITCH_DOMAIN,
SERVICE_TOGGLE, SERVICE_TOGGLE,

View file

@ -4,7 +4,6 @@ import asyncio
from datetime import timedelta from datetime import timedelta
from unittest.mock import patch from unittest.mock import patch
import async_timeout
from freezegun import freeze_time from freezegun import freeze_time
import pytest import pytest
@ -560,12 +559,12 @@ async def test_history_stream_significant_domain_historical_only(
"no_attributes": True, "no_attributes": True,
} }
) )
async with async_timeout.timeout(3): async with asyncio.timeout(3):
response = await client.receive_json() response = await client.receive_json()
assert response["success"] assert response["success"]
assert response["id"] == 1 assert response["id"] == 1
assert response["type"] == "result" assert response["type"] == "result"
async with async_timeout.timeout(3): async with asyncio.timeout(3):
response = await client.receive_json() response = await client.receive_json()
assert response == { assert response == {
"event": { "event": {
@ -591,13 +590,13 @@ async def test_history_stream_significant_domain_historical_only(
"minimal_response": True, "minimal_response": True,
} }
) )
async with async_timeout.timeout(3): async with asyncio.timeout(3):
response = await client.receive_json() response = await client.receive_json()
assert response["success"] assert response["success"]
assert response["id"] == 2 assert response["id"] == 2
assert response["type"] == "result" assert response["type"] == "result"
async with async_timeout.timeout(3): async with asyncio.timeout(3):
response = await client.receive_json() response = await client.receive_json()
sensor_test_history = response["event"]["states"]["climate.test"] sensor_test_history = response["event"]["states"]["climate.test"]
assert len(sensor_test_history) == 5 assert len(sensor_test_history) == 5
@ -626,13 +625,13 @@ async def test_history_stream_significant_domain_historical_only(
"no_attributes": False, "no_attributes": False,
} }
) )
async with async_timeout.timeout(3): async with asyncio.timeout(3):
response = await client.receive_json() response = await client.receive_json()
assert response["success"] assert response["success"]
assert response["id"] == 3 assert response["id"] == 3
assert response["type"] == "result" assert response["type"] == "result"
async with async_timeout.timeout(3): async with asyncio.timeout(3):
response = await client.receive_json() response = await client.receive_json()
sensor_test_history = response["event"]["states"]["climate.test"] sensor_test_history = response["event"]["states"]["climate.test"]
@ -663,13 +662,13 @@ async def test_history_stream_significant_domain_historical_only(
"no_attributes": False, "no_attributes": False,
} }
) )
async with async_timeout.timeout(3): async with asyncio.timeout(3):
response = await client.receive_json() response = await client.receive_json()
assert response["success"] assert response["success"]
assert response["id"] == 4 assert response["id"] == 4
assert response["type"] == "result" assert response["type"] == "result"
async with async_timeout.timeout(3): async with asyncio.timeout(3):
response = await client.receive_json() response = await client.receive_json()
sensor_test_history = response["event"]["states"]["climate.test"] sensor_test_history = response["event"]["states"]["climate.test"]
@ -708,13 +707,13 @@ async def test_history_stream_significant_domain_historical_only(
"no_attributes": False, "no_attributes": False,
} }
) )
async with async_timeout.timeout(3): async with asyncio.timeout(3):
response = await client.receive_json() response = await client.receive_json()
assert response["success"] assert response["success"]
assert response["id"] == 5 assert response["id"] == 5
assert response["type"] == "result" assert response["type"] == "result"
async with async_timeout.timeout(3): async with asyncio.timeout(3):
response = await client.receive_json() response = await client.receive_json()
sensor_test_history = response["event"]["states"]["climate.test"] sensor_test_history = response["event"]["states"]["climate.test"]

View file

@ -1,9 +1,9 @@
"""Tests for WebSocket API commands.""" """Tests for WebSocket API commands."""
import asyncio
from copy import deepcopy from copy import deepcopy
import datetime import datetime
from unittest.mock import ANY, AsyncMock, Mock, patch from unittest.mock import ANY, AsyncMock, Mock, patch
from async_timeout import timeout
import pytest import pytest
import voluptuous as vol import voluptuous as vol
@ -497,7 +497,7 @@ async def test_subscribe_unsubscribe_events(
hass.bus.async_fire("test_event", {"hello": "world"}) hass.bus.async_fire("test_event", {"hello": "world"})
hass.bus.async_fire("ignore_event") hass.bus.async_fire("ignore_event")
async with timeout(3): async with asyncio.timeout(3):
msg = await websocket_client.receive_json() msg = await websocket_client.receive_json()
assert msg["id"] == 5 assert msg["id"] == 5
@ -712,7 +712,7 @@ async def test_subscribe_unsubscribe_events_whitelist(
hass.bus.async_fire("themes_updated") hass.bus.async_fire("themes_updated")
async with timeout(3): async with asyncio.timeout(3):
msg = await websocket_client.receive_json() msg = await websocket_client.receive_json()
assert msg["id"] == 6 assert msg["id"] == 6
@ -1611,7 +1611,7 @@ async def test_subscribe_trigger(hass: HomeAssistant, websocket_client) -> None:
hass.bus.async_fire("test_event", {"hello": "world"}, context=context) hass.bus.async_fire("test_event", {"hello": "world"}, context=context)
hass.bus.async_fire("ignore_event") hass.bus.async_fire("ignore_event")
async with timeout(3): async with asyncio.timeout(3):
msg = await websocket_client.receive_json() msg = await websocket_client.receive_json()
assert msg["id"] == 5 assert msg["id"] == 5

View file

@ -140,7 +140,7 @@ async def test_abort_if_authorization_timeout(
flow.hass = hass flow.hass = hass
with patch( with patch(
"homeassistant.helpers.config_entry_oauth2_flow.async_timeout.timeout", "homeassistant.helpers.config_entry_oauth2_flow.asyncio.timeout",
side_effect=asyncio.TimeoutError, side_effect=asyncio.TimeoutError,
): ):
result = await flow.async_step_user() result = await flow.async_step_user()
@ -331,7 +331,7 @@ async def test_abort_on_oauth_timeout_error(
assert resp.headers["content-type"] == "text/html; charset=utf-8" assert resp.headers["content-type"] == "text/html; charset=utf-8"
with patch( with patch(
"homeassistant.helpers.config_entry_oauth2_flow.async_timeout.timeout", "homeassistant.helpers.config_entry_oauth2_flow.asyncio.timeout",
side_effect=asyncio.TimeoutError, side_effect=asyncio.TimeoutError,
): ):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])

View file

@ -8,7 +8,6 @@ from unittest.mock import patch
from astral import LocationInfo from astral import LocationInfo
import astral.sun import astral.sun
import async_timeout
from freezegun import freeze_time from freezegun import freeze_time
from freezegun.api import FrozenDateTimeFactory from freezegun.api import FrozenDateTimeFactory
import jinja2 import jinja2
@ -4361,7 +4360,7 @@ async def test_call_later(hass: HomeAssistant) -> None:
async_fire_time_changed_exact(hass, dt_util.utcnow() + timedelta(seconds=delay)) async_fire_time_changed_exact(hass, dt_util.utcnow() + timedelta(seconds=delay))
async with async_timeout.timeout(delay + delay_tolerance): async with asyncio.timeout(delay + delay_tolerance):
assert await future, "callback was called but the delay was wrong" assert await future, "callback was called but the delay was wrong"
@ -4381,7 +4380,7 @@ async def test_async_call_later(hass: HomeAssistant) -> None:
async_fire_time_changed_exact(hass, dt_util.utcnow() + timedelta(seconds=delay)) async_fire_time_changed_exact(hass, dt_util.utcnow() + timedelta(seconds=delay))
async with async_timeout.timeout(delay + delay_tolerance): async with asyncio.timeout(delay + delay_tolerance):
assert await future, "callback was called but the delay was wrong" assert await future, "callback was called but the delay was wrong"
assert isinstance(remove, Callable) assert isinstance(remove, Callable)
remove() remove()
@ -4403,7 +4402,7 @@ async def test_async_call_later_timedelta(hass: HomeAssistant) -> None:
async_fire_time_changed_exact(hass, dt_util.utcnow() + timedelta(seconds=delay)) async_fire_time_changed_exact(hass, dt_util.utcnow() + timedelta(seconds=delay))
async with async_timeout.timeout(delay + delay_tolerance): async with asyncio.timeout(delay + delay_tolerance):
assert await future, "callback was called but the delay was wrong" assert await future, "callback was called but the delay was wrong"
assert isinstance(remove, Callable) assert isinstance(remove, Callable)
remove() remove()
@ -4430,7 +4429,7 @@ async def test_async_call_later_cancel(hass: HomeAssistant) -> None:
async_fire_time_changed_exact(hass, dt_util.utcnow() + timedelta(seconds=delay)) async_fire_time_changed_exact(hass, dt_util.utcnow() + timedelta(seconds=delay))
with contextlib.suppress(asyncio.TimeoutError): with contextlib.suppress(asyncio.TimeoutError):
async with async_timeout.timeout(delay + delay_tolerance): async with asyncio.timeout(delay + delay_tolerance):
assert await future, "callback not canceled" assert await future, "callback not canceled"

View file

@ -9,7 +9,6 @@ from types import MappingProxyType
from unittest import mock from unittest import mock
from unittest.mock import AsyncMock, MagicMock, patch from unittest.mock import AsyncMock, MagicMock, patch
from async_timeout import timeout
import pytest import pytest
import voluptuous as vol import voluptuous as vol
@ -1000,7 +999,7 @@ async def test_wait_basic_times_out(hass: HomeAssistant, action_type) -> None:
assert script_obj.last_action == wait_alias assert script_obj.last_action == wait_alias
hass.states.async_set("switch.test", "not_on") hass.states.async_set("switch.test", "not_on")
async with timeout(0.1): async with asyncio.timeout(0.1):
await hass.async_block_till_done() await hass.async_block_till_done()
except asyncio.TimeoutError: except asyncio.TimeoutError:
timed_out = True timed_out = True
@ -1386,7 +1385,7 @@ async def test_wait_template_with_utcnow_no_match(hass: HomeAssistant) -> None:
): ):
async_fire_time_changed(hass, second_non_matching_time) async_fire_time_changed(hass, second_non_matching_time)
async with timeout(0.1): async with asyncio.timeout(0.1):
await hass.async_block_till_done() await hass.async_block_till_done()
except asyncio.TimeoutError: except asyncio.TimeoutError:
timed_out = True timed_out = True

View file

@ -14,7 +14,6 @@ import time
from typing import Any from typing import Any
from unittest.mock import MagicMock, Mock, PropertyMock, patch from unittest.mock import MagicMock, Mock, PropertyMock, patch
import async_timeout
import pytest import pytest
import voluptuous as vol import voluptuous as vol
@ -235,7 +234,7 @@ async def test_async_get_hass_can_be_called(hass: HomeAssistant) -> None:
assert can_call_async_get_hass() assert can_call_async_get_hass()
hass.async_create_task(_async_create_task(), "create_task") hass.async_create_task(_async_create_task(), "create_task")
async with async_timeout.timeout(1): async with asyncio.timeout(1):
await task_finished.wait() await task_finished.wait()
task_finished.clear() task_finished.clear()
@ -246,7 +245,7 @@ async def test_async_get_hass_can_be_called(hass: HomeAssistant) -> None:
task_finished.set() task_finished.set()
hass.async_add_job(_add_job) hass.async_add_job(_add_job)
async with async_timeout.timeout(1): async with asyncio.timeout(1):
await task_finished.wait() await task_finished.wait()
task_finished.clear() task_finished.clear()
@ -263,7 +262,7 @@ async def test_async_get_hass_can_be_called(hass: HomeAssistant) -> None:
hass.async_add_job(_callback) hass.async_add_job(_callback)
_schedule_callback_from_callback() _schedule_callback_from_callback()
async with async_timeout.timeout(1): async with asyncio.timeout(1):
await task_finished.wait() await task_finished.wait()
task_finished.clear() task_finished.clear()
@ -279,7 +278,7 @@ async def test_async_get_hass_can_be_called(hass: HomeAssistant) -> None:
hass.async_add_job(_coroutine()) hass.async_add_job(_coroutine())
_schedule_coroutine_from_callback() _schedule_coroutine_from_callback()
async with async_timeout.timeout(1): async with asyncio.timeout(1):
await task_finished.wait() await task_finished.wait()
task_finished.clear() task_finished.clear()
@ -295,7 +294,7 @@ async def test_async_get_hass_can_be_called(hass: HomeAssistant) -> None:
hass.async_add_job(_callback) hass.async_add_job(_callback)
await _schedule_callback_from_coroutine() await _schedule_callback_from_coroutine()
async with async_timeout.timeout(1): async with asyncio.timeout(1):
await task_finished.wait() await task_finished.wait()
task_finished.clear() task_finished.clear()
@ -310,7 +309,7 @@ async def test_async_get_hass_can_be_called(hass: HomeAssistant) -> None:
await hass.async_create_task(_coroutine()) await hass.async_create_task(_coroutine())
await _schedule_callback_from_coroutine() await _schedule_callback_from_coroutine()
async with async_timeout.timeout(1): async with asyncio.timeout(1):
await task_finished.wait() await task_finished.wait()
task_finished.clear() task_finished.clear()
@ -326,7 +325,7 @@ async def test_async_get_hass_can_be_called(hass: HomeAssistant) -> None:
hass.add_job(_async_add_job) hass.add_job(_async_add_job)
await hass.async_add_executor_job(_async_add_executor_job_add_job) await hass.async_add_executor_job(_async_add_executor_job_add_job)
async with async_timeout.timeout(1): async with asyncio.timeout(1):
await task_finished.wait() await task_finished.wait()
task_finished.clear() task_finished.clear()
@ -341,7 +340,7 @@ async def test_async_get_hass_can_be_called(hass: HomeAssistant) -> None:
hass.create_task(_async_create_task()) hass.create_task(_async_create_task())
await hass.async_add_executor_job(_async_add_executor_job_create_task) await hass.async_add_executor_job(_async_add_executor_job_create_task)
async with async_timeout.timeout(1): async with asyncio.timeout(1):
await task_finished.wait() await task_finished.wait()
task_finished.clear() task_finished.clear()
@ -359,7 +358,7 @@ async def test_async_get_hass_can_be_called(hass: HomeAssistant) -> None:
my_job_add_job = MyJobAddJob() my_job_add_job = MyJobAddJob()
my_job_add_job.start() my_job_add_job.start()
async with async_timeout.timeout(1): async with asyncio.timeout(1):
await task_finished.wait() await task_finished.wait()
task_finished.clear() task_finished.clear()
my_job_add_job.join() my_job_add_job.join()
@ -377,7 +376,7 @@ async def test_async_get_hass_can_be_called(hass: HomeAssistant) -> None:
my_job_create_task = MyJobCreateTask() my_job_create_task = MyJobCreateTask()
my_job_create_task.start() my_job_create_task.start()
async with async_timeout.timeout(1): async with asyncio.timeout(1):
await task_finished.wait() await task_finished.wait()
task_finished.clear() task_finished.clear()
my_job_create_task.join() my_job_create_task.join()