Use builtin TimeoutError [core + helpers] (#109684)

This commit is contained in:
Marc Mueller 2024-02-05 12:09:54 +01:00 committed by GitHub
parent a9147cf3dd
commit cd0ee98dba
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 70 additions and 74 deletions

View file

@ -217,7 +217,7 @@ async def async_setup_hass(
) )
# Ask integrations to shut down. It's messy but we can't # Ask integrations to shut down. It's messy but we can't
# do a clean stop without knowing what is broken # do a clean stop without knowing what is broken
with contextlib.suppress(asyncio.TimeoutError): with contextlib.suppress(TimeoutError):
async with hass.timeout.async_timeout(10): async with hass.timeout.async_timeout(10):
await hass.async_stop() await hass.async_stop()
@ -738,7 +738,7 @@ async def _async_set_up_integrations(
STAGE_1_TIMEOUT, cool_down=COOLDOWN_TIME STAGE_1_TIMEOUT, cool_down=COOLDOWN_TIME
): ):
await async_setup_multi_components(hass, stage_1_domains, config) await async_setup_multi_components(hass, stage_1_domains, config)
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning("Setup timed out for stage 1 - moving forward") _LOGGER.warning("Setup timed out for stage 1 - moving forward")
# Add after dependencies when setting up stage 2 domains # Add after dependencies when setting up stage 2 domains
@ -751,7 +751,7 @@ async def _async_set_up_integrations(
STAGE_2_TIMEOUT, cool_down=COOLDOWN_TIME STAGE_2_TIMEOUT, cool_down=COOLDOWN_TIME
): ):
await async_setup_multi_components(hass, stage_2_domains, config) await async_setup_multi_components(hass, stage_2_domains, config)
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning("Setup timed out for stage 2 - moving forward") _LOGGER.warning("Setup timed out for stage 2 - moving forward")
# Wrap up startup # Wrap up startup
@ -759,7 +759,7 @@ async def _async_set_up_integrations(
try: try:
async with hass.timeout.async_timeout(WRAP_UP_TIMEOUT, cool_down=COOLDOWN_TIME): async with hass.timeout.async_timeout(WRAP_UP_TIMEOUT, cool_down=COOLDOWN_TIME):
await hass.async_block_till_done() await hass.async_block_till_done()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning("Setup timed out for bootstrap - moving forward") _LOGGER.warning("Setup timed out for bootstrap - moving forward")
watch_task.cancel() watch_task.cancel()

View file

@ -875,7 +875,7 @@ class HomeAssistant:
tasks.append(task_or_none) tasks.append(task_or_none)
if tasks: if tasks:
await asyncio.gather(*tasks, return_exceptions=True) await asyncio.gather(*tasks, return_exceptions=True)
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning( _LOGGER.warning(
"Timed out waiting for shutdown jobs to complete, the shutdown will" "Timed out waiting for shutdown jobs to complete, the shutdown will"
" continue" " continue"
@ -906,7 +906,7 @@ class HomeAssistant:
try: try:
async with self.timeout.async_timeout(STOP_STAGE_SHUTDOWN_TIMEOUT): async with self.timeout.async_timeout(STOP_STAGE_SHUTDOWN_TIMEOUT):
await self.async_block_till_done() await self.async_block_till_done()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning( _LOGGER.warning(
"Timed out waiting for integrations to stop, the shutdown will" "Timed out waiting for integrations to stop, the shutdown will"
" continue" " continue"
@ -919,7 +919,7 @@ class HomeAssistant:
try: try:
async with self.timeout.async_timeout(FINAL_WRITE_STAGE_SHUTDOWN_TIMEOUT): async with self.timeout.async_timeout(FINAL_WRITE_STAGE_SHUTDOWN_TIMEOUT):
await self.async_block_till_done() await self.async_block_till_done()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning( _LOGGER.warning(
"Timed out waiting for final writes to complete, the shutdown will" "Timed out waiting for final writes to complete, the shutdown will"
" continue" " continue"
@ -951,7 +951,7 @@ class HomeAssistant:
await task await task
except asyncio.CancelledError: except asyncio.CancelledError:
pass pass
except asyncio.TimeoutError: except TimeoutError:
# Task may be shielded from cancellation. # Task may be shielded from cancellation.
_LOGGER.exception( _LOGGER.exception(
"Task %s could not be canceled during final shutdown stage", task "Task %s could not be canceled during final shutdown stage", task
@ -971,7 +971,7 @@ class HomeAssistant:
try: try:
async with self.timeout.async_timeout(CLOSE_STAGE_SHUTDOWN_TIMEOUT): async with self.timeout.async_timeout(CLOSE_STAGE_SHUTDOWN_TIMEOUT):
await self.async_block_till_done() await self.async_block_till_done()
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.warning( _LOGGER.warning(
"Timed out waiting for close event to be processed, the shutdown will" "Timed out waiting for close event to be processed, the shutdown will"
" continue" " continue"

View file

@ -187,7 +187,7 @@ async def async_aiohttp_proxy_web(
# The user cancelled the request # The user cancelled the request
return None return None
except asyncio.TimeoutError as err: except TimeoutError as err:
# Timeout trying to start the web request # Timeout trying to start the web request
raise HTTPGatewayTimeout() from err raise HTTPGatewayTimeout() from err
@ -219,7 +219,7 @@ async def async_aiohttp_proxy_stream(
await response.prepare(request) await response.prepare(request)
# Suppressing something went wrong fetching data, closed connection # Suppressing something went wrong fetching data, closed connection
with suppress(asyncio.TimeoutError, aiohttp.ClientError): with suppress(TimeoutError, aiohttp.ClientError):
while hass.is_running: while hass.is_running:
async with asyncio.timeout(timeout): async with asyncio.timeout(timeout):
data = await stream.read(buffer_size) data = await stream.read(buffer_size)

View file

@ -294,7 +294,7 @@ class AbstractOAuth2FlowHandler(config_entries.ConfigFlow, metaclass=ABCMeta):
try: try:
async with asyncio.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 TimeoutError as err:
_LOGGER.error("Timeout generating authorize url: %s", err) _LOGGER.error("Timeout generating authorize url: %s", err)
return self.async_abort(reason="authorize_url_timeout") return self.async_abort(reason="authorize_url_timeout")
except NoURLAvailableError: except NoURLAvailableError:
@ -320,7 +320,7 @@ class AbstractOAuth2FlowHandler(config_entries.ConfigFlow, metaclass=ABCMeta):
token = await self.flow_impl.async_resolve_external_data( token = await self.flow_impl.async_resolve_external_data(
self.external_data self.external_data
) )
except asyncio.TimeoutError as err: except TimeoutError as err:
_LOGGER.error("Timeout resolving OAuth token: %s", err) _LOGGER.error("Timeout resolving OAuth token: %s", err)
return self.async_abort(reason="oauth_timeout") return self.async_abort(reason="oauth_timeout")
except (ClientResponseError, ClientError) as err: except (ClientResponseError, ClientError) as err:

View file

@ -370,7 +370,7 @@ class EntityPlatform:
EVENT_HOMEASSISTANT_STARTED, setup_again EVENT_HOMEASSISTANT_STARTED, setup_again
) )
return False return False
except asyncio.TimeoutError: except TimeoutError:
logger.error( logger.error(
( (
"Setup of platform %s is taking longer than %s seconds." "Setup of platform %s is taking longer than %s seconds."
@ -513,7 +513,7 @@ class EntityPlatform:
try: try:
async with self.hass.timeout.async_timeout(timeout, self.domain): async with self.hass.timeout.async_timeout(timeout, self.domain):
await asyncio.gather(*tasks) await asyncio.gather(*tasks)
except asyncio.TimeoutError: except TimeoutError:
self.logger.warning( self.logger.warning(
"Timed out adding entities for domain %s with platform %s after %ds", "Timed out adding entities for domain %s with platform %s after %ds",
self.domain, self.domain,

View file

@ -542,7 +542,7 @@ class ServiceIntentHandler(IntentHandler):
""" """
try: try:
await asyncio.wait({task}, timeout=self.service_timeout) await asyncio.wait({task}, timeout=self.service_timeout)
except asyncio.TimeoutError: except TimeoutError:
pass pass
except asyncio.CancelledError: except asyncio.CancelledError:
# Task calling us was cancelled, so cancel service call task, and wait for # Task calling us was cancelled, so cancel service call task, and wait for

View file

@ -595,7 +595,7 @@ class _ScriptRun:
try: try:
async with asyncio.timeout(delay): async with asyncio.timeout(delay):
await self._stop.wait() await self._stop.wait()
except asyncio.TimeoutError: except TimeoutError:
trace_set_result(delay=delay, done=True) trace_set_result(delay=delay, done=True)
async def _async_wait_template_step(self): async def _async_wait_template_step(self):
@ -643,7 +643,7 @@ class _ScriptRun:
try: try:
async with asyncio.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 TimeoutError as ex:
self._variables["wait"]["remaining"] = 0.0 self._variables["wait"]["remaining"] = 0.0
if not self._action.get(CONF_CONTINUE_ON_TIMEOUT, True): if not self._action.get(CONF_CONTINUE_ON_TIMEOUT, True):
self._log(_TIMEOUT_MSG) self._log(_TIMEOUT_MSG)
@ -1023,7 +1023,7 @@ class _ScriptRun:
try: try:
async with asyncio.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 TimeoutError as ex:
self._variables["wait"]["remaining"] = 0.0 self._variables["wait"]["remaining"] = 0.0
if not self._action.get(CONF_CONTINUE_ON_TIMEOUT, True): if not self._action.get(CONF_CONTINUE_ON_TIMEOUT, True):
self._log(_TIMEOUT_MSG) self._log(_TIMEOUT_MSG)

View file

@ -665,7 +665,7 @@ class Template:
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]))
except asyncio.TimeoutError: except TimeoutError:
template_render_thread.raise_exc(TimeoutError) template_render_thread.raise_exc(TimeoutError)
return True return True
finally: finally:

View file

@ -312,7 +312,7 @@ class DataUpdateCoordinator(BaseDataUpdateCoordinatorProtocol, Generic[_DataT]):
try: try:
self.data = await self._async_update_data() self.data = await self._async_update_data()
except (asyncio.TimeoutError, requests.exceptions.Timeout) as err: except (TimeoutError, requests.exceptions.Timeout) as err:
self.last_exception = err self.last_exception = err
if self.last_update_success: if self.last_update_success:
if log_failures: if log_failures:

View file

@ -331,7 +331,7 @@ async def _async_setup_component(
if task: if task:
async with hass.timeout.async_timeout(SLOW_SETUP_MAX_WAIT, domain): async with hass.timeout.async_timeout(SLOW_SETUP_MAX_WAIT, domain):
result = await task result = await task
except asyncio.TimeoutError: except TimeoutError:
_LOGGER.error( _LOGGER.error(
( (
"Setup of '%s' is taking longer than %s seconds." "Setup of '%s' is taking longer than %s seconds."

View file

@ -4,7 +4,6 @@ detect_location_info and elevation are mocked by default during tests.
""" """
from __future__ import annotations from __future__ import annotations
import asyncio
from functools import lru_cache from functools import lru_cache
import math import math
from typing import Any, NamedTuple from typing import Any, NamedTuple
@ -165,7 +164,7 @@ async def _get_whoami(session: aiohttp.ClientSession) -> dict[str, Any] | None:
resp = await session.get( resp = await session.get(
WHOAMI_URL_DEV if HA_VERSION.endswith("0.dev0") else WHOAMI_URL, timeout=30 WHOAMI_URL_DEV if HA_VERSION.endswith("0.dev0") else WHOAMI_URL, timeout=30
) )
except (aiohttp.ClientError, asyncio.TimeoutError): except (aiohttp.ClientError, TimeoutError):
return None return None
try: try:

View file

@ -179,7 +179,7 @@ class _GlobalTaskContext:
# Timeout on exit # Timeout on exit
if exc_type is asyncio.CancelledError and self.state == _State.TIMEOUT: if exc_type is asyncio.CancelledError and self.state == _State.TIMEOUT:
raise asyncio.TimeoutError raise TimeoutError
self._state = _State.EXIT self._state = _State.EXIT
self._wait_zone.set() self._wait_zone.set()
@ -294,7 +294,7 @@ class _ZoneTaskContext:
# Timeout on exit # Timeout on exit
if exc_type is asyncio.CancelledError and self.state == _State.TIMEOUT: if exc_type is asyncio.CancelledError and self.state == _State.TIMEOUT:
raise asyncio.TimeoutError raise TimeoutError
self._state = _State.EXIT self._state = _State.EXIT
return None return None

View file

@ -1,5 +1,4 @@
"""Test the aiohttp client helper.""" """Test the aiohttp client helper."""
import asyncio
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
import aiohttp import aiohttp
@ -249,7 +248,7 @@ async def test_async_aiohttp_proxy_stream_timeout(
aioclient_mock: AiohttpClientMocker, camera_client aioclient_mock: AiohttpClientMocker, camera_client
) -> None: ) -> None:
"""Test that it fetches the given url.""" """Test that it fetches the given url."""
aioclient_mock.get("http://example.com/mjpeg_stream", exc=asyncio.TimeoutError()) aioclient_mock.get("http://example.com/mjpeg_stream", exc=TimeoutError())
resp = await camera_client.get("/api/camera_proxy_stream/camera.mjpeg_camera") resp = await camera_client.get("/api/camera_proxy_stream/camera.mjpeg_camera")
assert resp.status == 504 assert resp.status == 504

View file

@ -1,5 +1,4 @@
"""Tests for the Somfy config flow.""" """Tests for the Somfy config flow."""
import asyncio
from http import HTTPStatus from http import HTTPStatus
import logging import logging
import time import time
@ -143,7 +142,7 @@ async def test_abort_if_authorization_timeout(
with patch( with patch(
"homeassistant.helpers.config_entry_oauth2_flow.asyncio.timeout", "homeassistant.helpers.config_entry_oauth2_flow.asyncio.timeout",
side_effect=asyncio.TimeoutError, side_effect=TimeoutError,
): ):
result = await flow.async_step_user() result = await flow.async_step_user()
@ -336,7 +335,7 @@ async def test_abort_on_oauth_timeout_error(
with patch( with patch(
"homeassistant.helpers.config_entry_oauth2_flow.asyncio.timeout", "homeassistant.helpers.config_entry_oauth2_flow.asyncio.timeout",
side_effect=asyncio.TimeoutError, side_effect=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

@ -4417,7 +4417,7 @@ async def test_async_call_later_cancel(hass: HomeAssistant) -> None:
# fast forward time beyond scheduled # fast forward time beyond scheduled
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(TimeoutError):
async with asyncio.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

@ -654,7 +654,7 @@ async def test_delay_basic(hass: HomeAssistant) -> None:
assert script_obj.is_running assert script_obj.is_running
assert script_obj.last_action == delay_alias assert script_obj.last_action == delay_alias
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -695,7 +695,7 @@ async def test_multiple_runs_delay(hass: HomeAssistant) -> None:
assert script_obj.is_running assert script_obj.is_running
assert len(events) == 1 assert len(events) == 1
assert events[-1].data["value"] == 1 assert events[-1].data["value"] == 1
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -725,7 +725,7 @@ async def test_delay_template_ok(hass: HomeAssistant) -> None:
await asyncio.wait_for(delay_started_flag.wait(), 1) await asyncio.wait_for(delay_started_flag.wait(), 1)
assert script_obj.is_running assert script_obj.is_running
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -792,7 +792,7 @@ async def test_delay_template_complex_ok(hass: HomeAssistant) -> None:
hass.async_create_task(script_obj.async_run(context=Context())) hass.async_create_task(script_obj.async_run(context=Context()))
await asyncio.wait_for(delay_started_flag.wait(), 1) await asyncio.wait_for(delay_started_flag.wait(), 1)
assert script_obj.is_running assert script_obj.is_running
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -859,7 +859,7 @@ async def test_cancel_delay(hass: HomeAssistant) -> None:
assert script_obj.is_running assert script_obj.is_running
assert len(events) == 0 assert len(events) == 0
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -908,7 +908,7 @@ async def test_wait_basic(hass: HomeAssistant, action_type) -> None:
assert script_obj.is_running assert script_obj.is_running
assert script_obj.last_action == wait_alias assert script_obj.last_action == wait_alias
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -991,7 +991,7 @@ async def test_wait_for_trigger_variables(hass: HomeAssistant) -> None:
assert script_obj.last_action == wait_alias assert script_obj.last_action == wait_alias
hass.states.async_set("switch.test", "off") hass.states.async_set("switch.test", "off")
await hass.async_block_till_done() await hass.async_block_till_done()
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -1028,7 +1028,7 @@ async def test_wait_basic_times_out(hass: HomeAssistant, action_type) -> None:
async with asyncio.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 TimeoutError:
timed_out = True timed_out = True
await script_obj.async_stop() await script_obj.async_stop()
@ -1101,7 +1101,7 @@ async def test_multiple_runs_wait(hass: HomeAssistant, action_type) -> None:
hass.async_create_task(script_obj.async_run()) hass.async_create_task(script_obj.async_run())
await asyncio.wait_for(wait_started_flag.wait(), 1) await asyncio.wait_for(wait_started_flag.wait(), 1)
await asyncio.sleep(0) await asyncio.sleep(0)
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -1142,7 +1142,7 @@ async def test_cancel_wait(hass: HomeAssistant, action_type) -> None:
assert script_obj.is_running assert script_obj.is_running
assert len(events) == 0 assert len(events) == 0
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -1252,7 +1252,7 @@ async def test_wait_timeout(
assert script_obj.is_running assert script_obj.is_running
assert len(events) == 0 assert len(events) == 0
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -1320,7 +1320,7 @@ async def test_wait_continue_on_timeout(
assert script_obj.is_running assert script_obj.is_running
assert len(events) == 0 assert len(events) == 0
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -1363,7 +1363,7 @@ async def test_wait_template_variables_in(hass: HomeAssistant) -> None:
await asyncio.wait_for(wait_started_flag.wait(), 1) await asyncio.wait_for(wait_started_flag.wait(), 1)
assert script_obj.is_running assert script_obj.is_running
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -1404,7 +1404,7 @@ async def test_wait_template_with_utcnow(hass: HomeAssistant) -> None:
match_time = start_time.replace(hour=12) match_time = start_time.replace(hour=12)
with freeze_time(match_time): with freeze_time(match_time):
async_fire_time_changed(hass, match_time) async_fire_time_changed(hass, match_time)
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -1444,7 +1444,7 @@ async def test_wait_template_with_utcnow_no_match(hass: HomeAssistant) -> None:
async with asyncio.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 TimeoutError:
timed_out = True timed_out = True
await script_obj.async_stop() await script_obj.async_stop()
@ -1505,7 +1505,7 @@ async def test_wait_variables_out(hass: HomeAssistant, mode, action_type) -> Non
assert script_obj.is_running assert script_obj.is_running
assert len(events) == 0 assert len(events) == 0
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -2450,7 +2450,7 @@ async def test_repeat_conditional(
wait_started.clear() wait_started.clear()
hass.states.async_set("sensor.test", "done") hass.states.async_set("sensor.test", "done")
await asyncio.wait_for(hass.async_block_till_done(), 1) await asyncio.wait_for(hass.async_block_till_done(), 1)
except asyncio.TimeoutError: except TimeoutError:
await script_obj.async_stop() await script_obj.async_stop()
raise raise
@ -4069,7 +4069,7 @@ async def test_script_mode_single(
assert "Already running" in caplog.text assert "Already running" in caplog.text
assert script_obj.is_running assert script_obj.is_running
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -4204,7 +4204,7 @@ async def test_script_mode_2(
) )
for message in messages for message in messages
) )
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -4299,7 +4299,7 @@ async def test_script_mode_queued(hass: HomeAssistant) -> None:
assert script_obj.runs == 1 assert script_obj.runs == 1
assert len(events) == 3 assert len(events) == 3
assert events[2].data["value"] == 1 assert events[2].data["value"] == 1
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -4351,7 +4351,7 @@ async def test_script_mode_queued_cancel(hass: HomeAssistant) -> None:
assert not script_obj.is_running assert not script_obj.is_running
assert script_obj.runs == 0 assert script_obj.runs == 0
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
@ -4412,7 +4412,7 @@ async def test_shutdown_at(
assert script_obj.is_running assert script_obj.is_running
assert script_obj.last_action == delay_alias assert script_obj.last_action == delay_alias
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:
@ -4448,7 +4448,7 @@ async def test_shutdown_after(
assert script_obj.is_running assert script_obj.is_running
assert script_obj.last_action == delay_alias assert script_obj.last_action == delay_alias
except (AssertionError, asyncio.TimeoutError): except (AssertionError, TimeoutError):
await script_obj.async_stop() await script_obj.async_stop()
raise raise
else: else:

View file

@ -1,5 +1,4 @@
"""Tests for the update coordinator.""" """Tests for the update coordinator."""
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
from unittest.mock import AsyncMock, Mock, patch from unittest.mock import AsyncMock, Mock, patch
@ -22,7 +21,7 @@ from tests.common import MockConfigEntry, async_fire_time_changed
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
KNOWN_ERRORS: list[tuple[Exception, type[Exception], str]] = [ KNOWN_ERRORS: list[tuple[Exception, type[Exception], str]] = [
(asyncio.TimeoutError(), asyncio.TimeoutError, "Timeout fetching test data"), (TimeoutError(), TimeoutError, "Timeout fetching test data"),
( (
requests.exceptions.Timeout(), requests.exceptions.Timeout(),
requests.exceptions.Timeout, requests.exceptions.Timeout,

View file

@ -410,7 +410,7 @@ async def test_stage_shutdown(hass: HomeAssistant) -> None:
async def test_stage_shutdown_timeouts(hass: HomeAssistant) -> None: async def test_stage_shutdown_timeouts(hass: HomeAssistant) -> None:
"""Simulate a shutdown, test timeouts at each step.""" """Simulate a shutdown, test timeouts at each step."""
with patch.object(hass.timeout, "async_timeout", side_effect=asyncio.TimeoutError): with patch.object(hass.timeout, "async_timeout", side_effect=TimeoutError):
await hass.async_stop() await hass.async_stop()
assert hass.state is CoreState.stopped assert hass.state is CoreState.stopped

View file

@ -13,7 +13,7 @@ async def test_simple_global_timeout() -> None:
"""Test a simple global timeout.""" """Test a simple global timeout."""
timeout = TimeoutManager() timeout = TimeoutManager()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1): async with timeout.async_timeout(0.1):
await asyncio.sleep(0.3) await asyncio.sleep(0.3)
@ -22,7 +22,7 @@ async def test_simple_global_timeout_with_executor_job(hass: HomeAssistant) -> N
"""Test a simple global timeout with executor job.""" """Test a simple global timeout with executor job."""
timeout = TimeoutManager() timeout = TimeoutManager()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1): async with timeout.async_timeout(0.1):
await hass.async_add_executor_job(lambda: time.sleep(0.2)) await hass.async_add_executor_job(lambda: time.sleep(0.2))
@ -107,7 +107,7 @@ async def test_mix_global_timeout_freeze_and_zone_freeze_other_zone_inside_execu
with timeout.freeze("not_recorder"): with timeout.freeze("not_recorder"):
time.sleep(0.3) time.sleep(0.3)
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1): async with timeout.async_timeout(0.1):
async with timeout.async_timeout( async with timeout.async_timeout(
0.2, zone_name="recorder" 0.2, zone_name="recorder"
@ -125,7 +125,7 @@ async def test_mix_global_timeout_freeze_and_zone_freeze_inside_executor_job_sec
with timeout.freeze("recorder"): with timeout.freeze("recorder"):
time.sleep(0.3) time.sleep(0.3)
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1): async with timeout.async_timeout(0.1):
async with timeout.async_timeout(0.2, zone_name="recorder"): async with timeout.async_timeout(0.2, zone_name="recorder"):
await hass.async_add_executor_job(_some_sync_work) await hass.async_add_executor_job(_some_sync_work)
@ -146,7 +146,7 @@ async def test_simple_global_timeout_freeze_reset() -> None:
"""Test a simple global timeout freeze reset.""" """Test a simple global timeout freeze reset."""
timeout = TimeoutManager() timeout = TimeoutManager()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.2): async with timeout.async_timeout(0.2):
async with timeout.async_freeze(): async with timeout.async_freeze():
await asyncio.sleep(0.1) await asyncio.sleep(0.1)
@ -157,7 +157,7 @@ async def test_simple_zone_timeout() -> None:
"""Test a simple zone timeout.""" """Test a simple zone timeout."""
timeout = TimeoutManager() timeout = TimeoutManager()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1, "test"): async with timeout.async_timeout(0.1, "test"):
await asyncio.sleep(0.3) await asyncio.sleep(0.3)
@ -166,7 +166,7 @@ async def test_multiple_zone_timeout() -> None:
"""Test a simple zone timeout.""" """Test a simple zone timeout."""
timeout = TimeoutManager() timeout = TimeoutManager()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1, "test"): async with timeout.async_timeout(0.1, "test"):
async with timeout.async_timeout(0.5, "test"): async with timeout.async_timeout(0.5, "test"):
await asyncio.sleep(0.3) await asyncio.sleep(0.3)
@ -176,7 +176,7 @@ async def test_different_zone_timeout() -> None:
"""Test a simple zone timeout.""" """Test a simple zone timeout."""
timeout = TimeoutManager() timeout = TimeoutManager()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1, "test"): async with timeout.async_timeout(0.1, "test"):
async with timeout.async_timeout(0.5, "other"): async with timeout.async_timeout(0.5, "other"):
await asyncio.sleep(0.3) await asyncio.sleep(0.3)
@ -202,7 +202,7 @@ async def test_simple_zone_timeout_freeze_reset() -> None:
"""Test a simple zone timeout freeze reset.""" """Test a simple zone timeout freeze reset."""
timeout = TimeoutManager() timeout = TimeoutManager()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.2, "test"): async with timeout.async_timeout(0.2, "test"):
async with timeout.async_freeze("test"): async with timeout.async_freeze("test"):
await asyncio.sleep(0.1) await asyncio.sleep(0.1)
@ -242,7 +242,7 @@ async def test_mix_zone_timeout() -> None:
timeout = TimeoutManager() timeout = TimeoutManager()
async with timeout.async_timeout(0.1): async with timeout.async_timeout(0.1):
with suppress(asyncio.TimeoutError): with suppress(TimeoutError):
async with timeout.async_timeout(0.2, "test"): async with timeout.async_timeout(0.2, "test"):
await asyncio.sleep(0.4) await asyncio.sleep(0.4)
@ -251,9 +251,9 @@ async def test_mix_zone_timeout_trigger_global() -> None:
"""Test a mix zone timeout global with trigger it.""" """Test a mix zone timeout global with trigger it."""
timeout = TimeoutManager() timeout = TimeoutManager()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1): async with timeout.async_timeout(0.1):
with suppress(asyncio.TimeoutError): with suppress(TimeoutError):
async with timeout.async_timeout(0.1, "test"): async with timeout.async_timeout(0.1, "test"):
await asyncio.sleep(0.3) await asyncio.sleep(0.3)
@ -265,7 +265,7 @@ async def test_mix_zone_timeout_trigger_global_cool_down() -> None:
timeout = TimeoutManager() timeout = TimeoutManager()
async with timeout.async_timeout(0.1, cool_down=0.3): async with timeout.async_timeout(0.1, cool_down=0.3):
with suppress(asyncio.TimeoutError): with suppress(TimeoutError):
async with timeout.async_timeout(0.1, "test"): async with timeout.async_timeout(0.1, "test"):
await asyncio.sleep(0.3) await asyncio.sleep(0.3)
@ -300,7 +300,7 @@ async def test_simple_zone_timeout_freeze_without_timeout_cleanup2(
async with timeout.async_freeze("test"): async with timeout.async_freeze("test"):
await asyncio.sleep(0.2) await asyncio.sleep(0.2)
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1): async with timeout.async_timeout(0.1):
hass.async_create_task(background()) hass.async_create_task(background())
await asyncio.sleep(0.3) await asyncio.sleep(0.3)
@ -310,7 +310,7 @@ async def test_simple_zone_timeout_freeze_without_timeout_exeption() -> None:
"""Test a simple zone timeout freeze on a zone that does not have a timeout set.""" """Test a simple zone timeout freeze on a zone that does not have a timeout set."""
timeout = TimeoutManager() timeout = TimeoutManager()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1): async with timeout.async_timeout(0.1):
with suppress(RuntimeError): with suppress(RuntimeError):
async with timeout.async_freeze("test"): async with timeout.async_freeze("test"):
@ -323,7 +323,7 @@ async def test_simple_zone_timeout_zone_with_timeout_exeption() -> None:
"""Test a simple zone timeout freeze on a zone that does not have a timeout set.""" """Test a simple zone timeout freeze on a zone that does not have a timeout set."""
timeout = TimeoutManager() timeout = TimeoutManager()
with pytest.raises(asyncio.TimeoutError): with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1): async with timeout.async_timeout(0.1):
with suppress(RuntimeError): with suppress(RuntimeError):
async with timeout.async_timeout(0.3, "test"): async with timeout.async_timeout(0.3, "test"):