diff --git a/homeassistant/components/withings/__init__.py b/homeassistant/components/withings/__init__.py index a59a3abf3793..71829df1ef9d 100644 --- a/homeassistant/components/withings/__init__.py +++ b/homeassistant/components/withings/__init__.py @@ -162,7 +162,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: WithingsConfigEntry) -> if state is cloud.CloudConnectionState.CLOUD_DISCONNECTED: await webhook_manager.unregister_webhook(None) entry.async_on_unload( - async_call_later(hass, 30, webhook_manager.register_webhook) + async_call_later(hass, 30, webhook_manager.async_start_register_webhook) ) @callback @@ -170,7 +170,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: WithingsConfigEntry) -> """Register the webhook once Home Assistant answers for it.""" entry.async_on_unload( async_call_later( - hass, WEBHOOK_REGISTER_DELAY, webhook_manager.register_webhook + hass, + WEBHOOK_REGISTER_DELAY, + webhook_manager.async_start_register_webhook, ) ) @@ -274,6 +276,13 @@ class WithingsWebhookManager: except WithingsError as ex: LOGGER.warning("Failed to unsubscribe from Withings webhook: %s", ex) + @callback + def async_start_register_webhook(self, _: Any) -> None: + """Register webhooks in a task that is cancelled when the entry unloads.""" + self.entry.async_create_background_task( + self.hass, self.register_webhook(None), "withings_register_webhook" + ) + async def register_webhook( self, _: Any, diff --git a/tests/components/withings/__init__.py b/tests/components/withings/__init__.py index 6b398c3d2fad..6e8a18386d1e 100644 --- a/tests/components/withings/__init__.py +++ b/tests/components/withings/__init__.py @@ -69,7 +69,7 @@ async def prepare_webhook_setup( """Prepare webhooks by advancing past the registration delay.""" freezer.tick(timedelta(seconds=1)) async_fire_time_changed(hass) - await hass.async_block_till_done() + await hass.async_block_till_done(wait_background_tasks=True) def load_goals_fixture(fixture: str = "withings/goals.json") -> Goals: diff --git a/tests/components/withings/test_init.py b/tests/components/withings/test_init.py index e6915a3db460..e1349988b3da 100644 --- a/tests/components/withings/test_init.py +++ b/tests/components/withings/test_init.py @@ -1,5 +1,6 @@ """Tests for the Withings component.""" +import asyncio from datetime import timedelta from typing import Any from unittest.mock import AsyncMock, patch @@ -55,7 +56,7 @@ async def test_data_manager_webhook_subscription( await setup_integration(hass, webhook_config_entry) await hass.async_block_till_done() async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=1)) - await hass.async_block_till_done() + await hass.async_block_till_done(wait_background_tasks=True) assert withings.subscribe_notification.call_count == 6 @@ -900,3 +901,33 @@ async def test_webhook_subscription_invalid_params( assert "Webhook URL rejected by Withings" in caplog.text assert withings.subscribe_notification.call_count == 1 + + +async def test_unload_during_webhook_subscription( + hass: HomeAssistant, + withings: AsyncMock, + webhook_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test unloading cancels an in-flight webhook subscription.""" + subscribe_started = asyncio.Event() + release_subscribe = asyncio.Event() + + async def _subscribe_notification(*args: Any) -> None: + subscribe_started.set() + await release_subscribe.wait() + + withings.subscribe_notification.side_effect = _subscribe_notification + + await setup_integration(hass, webhook_config_entry) + await hass.async_block_till_done() + freezer.tick(timedelta(seconds=1)) + async_fire_time_changed(hass) + await subscribe_started.wait() + + assert await hass.config_entries.async_unload(webhook_config_entry.entry_id) + release_subscribe.set() + await hass.async_block_till_done() + + assert webhook_config_entry.state is ConfigEntryState.NOT_LOADED + assert withings.subscribe_notification.call_count == 1