From 0ffbe076beb9c9a0016cb9e6423fdcfce4440e43 Mon Sep 17 00:00:00 2001 From: rrooggiieerr Date: Tue, 11 Feb 2025 22:08:18 +0100 Subject: [PATCH] Fix timer.cancel action fires timer.cancelled event even on canceled timers (#134507) * Fixes https://github.com/home-assistant/core/issues/116105 * Fixes unit test in accordance to documentation Timer needs to be active before it can be canceled * Allow canceling of paused timers * Add test for canceling/finishing already canceled/finished timers * Add test for finishing a paused timer, this should not be possible * Revert finish related tests * Merge branch 'timer.cancelled_fix' of git@github.com:rrooggiieerr/homeassistant-core.git into timer.cancelled_fix --------- Co-authored-by: Franck Nijhof --- homeassistant/components/timer/__init__.py | 3 +++ tests/components/timer/test_init.py | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/homeassistant/components/timer/__init__.py b/homeassistant/components/timer/__init__.py index b472e94a5c3..3cf8307e9b3 100644 --- a/homeassistant/components/timer/__init__.py +++ b/homeassistant/components/timer/__init__.py @@ -374,6 +374,9 @@ class Timer(collection.CollectionEntity, RestoreEntity): @callback def async_cancel(self) -> None: """Cancel a timer.""" + if self._state == STATUS_IDLE: + return + if self._listener: self._listener() self._listener = None diff --git a/tests/components/timer/test_init.py b/tests/components/timer/test_init.py index 3e5ecc58b5a..6e68b354087 100644 --- a/tests/components/timer/test_init.py +++ b/tests/components/timer/test_init.py @@ -196,6 +196,12 @@ async def test_methods_and_events(hass: HomeAssistant) -> None: "event": EVENT_TIMER_CANCELLED, "data": {}, }, + { + "call": SERVICE_CANCEL, + "state": STATUS_IDLE, + "event": None, + "data": {}, + }, { "call": SERVICE_START, "state": STATUS_ACTIVE,