diff --git a/homeassistant/components/withings/__init__.py b/homeassistant/components/withings/__init__.py index 246bcc134d0..597517693c0 100644 --- a/homeassistant/components/withings/__init__.py +++ b/homeassistant/components/withings/__init__.py @@ -5,6 +5,7 @@ For more details about this platform, please refer to the documentation at from __future__ import annotations from collections.abc import Awaitable, Callable +import contextlib from typing import Any from aiohttp.hdrs import METH_HEAD, METH_POST @@ -214,9 +215,12 @@ async def update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: async def async_cloudhook_generate_url(hass: HomeAssistant, entry: ConfigEntry) -> str: """Generate the full URL for a webhook_id.""" if CONF_CLOUDHOOK_URL not in entry.data: - webhook_url = await cloud.async_create_cloudhook( - hass, entry.data[CONF_WEBHOOK_ID] - ) + webhook_id = entry.data[CONF_WEBHOOK_ID] + # Some users already have their webhook as cloudhook. + # We remove them to be sure we can create a new one. + with contextlib.suppress(ValueError): + await cloud.async_delete_cloudhook(hass, webhook_id) + webhook_url = await cloud.async_create_cloudhook(hass, webhook_id) data = {**entry.data, CONF_CLOUDHOOK_URL: webhook_url} hass.config_entries.async_update_entry(entry, data=data) return webhook_url diff --git a/tests/components/withings/test_init.py b/tests/components/withings/test_init.py index a3918a6ff19..1c562182ae7 100644 --- a/tests/components/withings/test_init.py +++ b/tests/components/withings/test_init.py @@ -421,6 +421,7 @@ async def test_setup_with_cloud( assert hass.components.cloud.async_active_subscription() is True assert hass.components.cloud.async_is_connected() is True fake_create_cloudhook.assert_called_once() + fake_delete_cloudhook.assert_called_once() assert ( hass.config_entries.async_entries("withings")[0].data["cloudhook_url"] @@ -432,7 +433,7 @@ async def test_setup_with_cloud( for config_entry in hass.config_entries.async_entries("withings"): await hass.config_entries.async_remove(config_entry.entry_id) - fake_delete_cloudhook.assert_called_once() + fake_delete_cloudhook.call_count == 2 await hass.async_block_till_done() assert not hass.config_entries.async_entries(DOMAIN)