Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion custom_components/pyscript/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,14 @@ async def handle_exception(self, exc: Exception) -> None:

async def wait_until(self) -> dict[str, Any]:
"""Wait for dispatch and normalize the return payload."""
data = await self._future
try:
data = await self._future
except asyncio.CancelledError:
# dispatch() and handle_exception() stop the decorators; a cancelled wait reaches
# neither, so stop them here unless a trigger fired just before the cancel
if self.status is DecoratorManagerStatus.RUNNING:
await self.stop()
raise
if data.trigger == self.timeout_decorator:
ret = {"trigger_type": "timeout"}
else:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_decorator_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,26 @@ async def test_wait_until_ignores_exception_after_completion(hass):
assert await dm.wait_until() == {"value": 1}


@pytest.mark.asyncio
async def test_wait_until_stops_decorators_when_cancelled(hass):
"""Cancelling the waiting task should stop the wait's decorators."""
DecoratorManager.hass = hass
events: list[tuple[str, str]] = []
dm = WaitUntilDecoratorManager(DummyAstCtx())
dm.add(make_recording_decorator("trigger", events))
await dm.validate()
await dm.start()

waiter = asyncio.create_task(dm.wait_until())
await asyncio.sleep(0)
waiter.cancel()
with pytest.raises(asyncio.CancelledError):
await waiter

assert ("stop", "trigger") in events
assert dm.status is DecoratorManagerStatus.STOPPED


@pytest.mark.asyncio
async def test_function_decorator_manager_cancel_calls_result_handlers(hass):
"""Canceled calls should still notify result handlers with None."""
Expand Down
Loading