From 779ef3c8e18d684f18d36255122c4b8316dd13a5 Mon Sep 17 00:00:00 2001 From: Eduard van Valkenburg Date: Sat, 12 Jun 2021 13:14:35 +0200 Subject: [PATCH] Add timedelta option for async_call_later (#50164) --- homeassistant/helpers/event.py | 8 ++++---- tests/helpers/test_event.py | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/homeassistant/helpers/event.py b/homeassistant/helpers/event.py index 48dd05d2311..85eebf05298 100644 --- a/homeassistant/helpers/event.py +++ b/homeassistant/helpers/event.py @@ -1214,13 +1214,13 @@ track_point_in_utc_time = threaded_listener_factory(async_track_point_in_utc_tim @bind_hass def async_call_later( hass: HomeAssistant, - delay: float, + delay: float | timedelta, action: HassJob | Callable[..., Awaitable[None] | None], ) -> CALLBACK_TYPE: """Add a listener that is called in .""" - return async_track_point_in_utc_time( - hass, action, dt_util.utcnow() + timedelta(seconds=delay) - ) + if not isinstance(delay, timedelta): + delay = timedelta(seconds=delay) + return async_track_point_in_utc_time(hass, action, dt_util.utcnow() + delay) call_later = threaded_listener_factory(async_call_later) diff --git a/tests/helpers/test_event.py b/tests/helpers/test_event.py index e134c5e327d..fb7464d405f 100644 --- a/tests/helpers/test_event.py +++ b/tests/helpers/test_event.py @@ -3049,6 +3049,27 @@ async def test_async_call_later(hass): assert remove is mock() +async def test_async_call_later_timedelta(hass): + """Test calling an action later with a timedelta.""" + + def action(): + pass + + now = datetime(2017, 12, 19, 15, 40, 0, tzinfo=dt_util.UTC) + + with patch( + "homeassistant.helpers.event.async_track_point_in_utc_time" + ) as mock, patch("homeassistant.util.dt.utcnow", return_value=now): + remove = async_call_later(hass, timedelta(seconds=3), action) + + assert len(mock.mock_calls) == 1 + p_hass, p_action, p_point = mock.mock_calls[0][1] + assert p_hass is hass + assert p_action is action + assert p_point == now + timedelta(seconds=3) + assert remove is mock() + + async def test_track_state_change_event_chain_multple_entity(hass): """Test that adding a new state tracker inside a tracker does not fire right away.""" tracker_called = []