diff --git a/homeassistant/components/ntfy/event.py b/homeassistant/components/ntfy/event.py index 5a8dd59831dd..1e6fce8e129b 100644 --- a/homeassistant/components/ntfy/event.py +++ b/homeassistant/components/ntfy/event.py @@ -12,10 +12,14 @@ from aiontfy.exceptions import ( NtfyTimeoutError, ) -from homeassistant.components.event import EventEntity, EventEntityDescription +from homeassistant.components.event import ( + DOMAIN as EVENT_DOMAIN, + EventEntity, + EventEntityDescription, +) from homeassistant.config_entries import ConfigSubentry from homeassistant.core import HomeAssistant, callback -from homeassistant.helpers import issue_registry as ir +from homeassistant.helpers import entity_registry as er, issue_registry as ir from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import CONF_MESSAGE, CONF_PRIORITY, CONF_TAGS, CONF_TITLE, DOMAIN @@ -35,12 +39,34 @@ async def async_setup_entry( ) -> None: """Set up the event platform.""" + # Entities disabled while the entry was not loaded didn't delete their issue + for entity_entry in er.async_entries_for_config_entry( + er.async_get(hass), config_entry.entry_id + ): + if ( + entity_entry.domain == EVENT_DOMAIN + and entity_entry.disabled + and entity_entry.config_subentry_id is not None + ): + ir.async_delete_issue( + hass, + DOMAIN, + _topic_protected_issue_id( + config_entry.entry_id, entity_entry.config_subentry_id + ), + ) + for subentry_id, subentry in config_entry.subentries.items(): async_add_entities( [NtfyEventEntity(config_entry, subentry)], config_subentry_id=subentry_id ) +def _topic_protected_issue_id(entry_id: str, subentry_id: str) -> str: + """Return the id of the protected topic issue of a topic subentry.""" + return f"topic_protected_{entry_id}_{subentry_id}" + + class NtfyEventEntity(NtfyBaseEntity, EventEntity): """An event entity.""" @@ -59,8 +85,8 @@ class NtfyEventEntity(NtfyBaseEntity, EventEntity): """Initialize the entity.""" super().__init__(config_entry, subentry) self._ws: asyncio.Task | None = None - self._topic_protected_issue_id = ( - f"topic_protected_{config_entry.entry_id}_{subentry.subentry_id}" + self._topic_protected_issue_id = _topic_protected_issue_id( + config_entry.entry_id, subentry.subentry_id ) @callback @@ -88,10 +114,20 @@ class NtfyEventEntity(NtfyBaseEntity, EventEntity): "websocket_watchdog", ) + @override + async def async_removed_from_registry(self) -> None: + """Run when entity has been removed from the entity registry.""" + ir.async_delete_issue(self.hass, DOMAIN, self._topic_protected_issue_id) + @override async def async_will_remove_from_hass(self) -> None: """Run when entity will be removed from hass.""" - ir.async_delete_issue(self.hass, DOMAIN, self._topic_protected_issue_id) + # Core hides issues of a disabled config entry, keep them and their ignore + if self.registry_entry is not None and self.registry_entry.disabled_by not in ( + None, + er.RegistryEntryDisabler.CONFIG_ENTRY, + ): + ir.async_delete_issue(self.hass, DOMAIN, self._topic_protected_issue_id) async def ws_connect(self) -> None: """Connect websocket.""" diff --git a/tests/components/ntfy/test_event.py b/tests/components/ntfy/test_event.py index 82477f175252..329412ce2abd 100644 --- a/tests/components/ntfy/test_event.py +++ b/tests/components/ntfy/test_event.py @@ -1,7 +1,7 @@ """Tests for the ntfy event platform.""" import asyncio -from collections.abc import AsyncGenerator +from collections.abc import AsyncGenerator, Callable, Coroutine from datetime import UTC, datetime, timedelta from unittest.mock import AsyncMock, patch @@ -28,7 +28,11 @@ from pytest_homeassistant.typing import ClientSessionGenerator from syrupy.assertion import SnapshotAssertion from homeassistant.components.ntfy.const import CONF_TOPIC, DOMAIN, SUBENTRY_TYPE_TOPIC -from homeassistant.config_entries import ConfigEntryState, ConfigSubentryData +from homeassistant.config_entries import ( + ConfigEntryDisabler, + ConfigEntryState, + ConfigSubentryData, +) from homeassistant.const import ( CONF_TOKEN, CONF_URL, @@ -39,7 +43,11 @@ from homeassistant.const import ( Platform, ) from homeassistant.core import HomeAssistant -from homeassistant.helpers import entity_registry as er, issue_registry as ir +from homeassistant.helpers import ( + device_registry as dr, + entity_registry as er, + issue_registry as ir, +) from homeassistant.setup import async_setup_component TOPIC_PROTECTED_ISSUE_ID = "topic_protected_123456789_ABCDEF" @@ -435,11 +443,7 @@ async def test_event_topic_protected_issue_deleted_on_remove_not_loaded( async_fire_time_changed(hass) await hass.async_block_till_done() - # Keep the issue on unload, as it is kept across a restart - with patch( - "homeassistant.components.ntfy.event.NtfyEventEntity.async_will_remove_from_hass" - ): - assert await hass.config_entries.async_unload(config_entry.entry_id) + assert await hass.config_entries.async_unload(config_entry.entry_id) assert config_entry.state is ConfigEntryState.NOT_LOADED assert issue_registry.async_get_issue(DOMAIN, TOPIC_PROTECTED_ISSUE_ID) @@ -449,15 +453,44 @@ async def test_event_topic_protected_issue_deleted_on_remove_not_loaded( assert not issue_registry.async_get_issue(DOMAIN, TOPIC_PROTECTED_ISSUE_ID) -async def test_event_topic_protected_issue_deleted_on_entity_disable( +async def _disable_entity(hass: HomeAssistant) -> None: + """Disable the event entity.""" + er.async_get(hass).async_update_entity( + "event.mytopic", disabled_by=er.RegistryEntryDisabler.USER + ) + + +async def _disable_device(hass: HomeAssistant) -> None: + """Disable the device of the event entity.""" + assert (entity := er.async_get(hass).async_get("event.mytopic")) + assert entity.device_id + dr.async_get(hass).async_update_device( + entity.device_id, disabled_by=dr.DeviceEntryDisabler.USER + ) + + +async def _remove_entity(hass: HomeAssistant) -> None: + """Remove the event entity from the entity registry.""" + er.async_get(hass).async_remove("event.mytopic") + + +@pytest.mark.parametrize( + "remove_entity", + [ + pytest.param(_disable_entity, id="entity_disabled"), + pytest.param(_disable_device, id="device_disabled"), + pytest.param(_remove_entity, id="entity_removed"), + ], +) +async def test_event_topic_protected_issue_deleted_on_entity_disable_or_remove( hass: HomeAssistant, config_entry: MockConfigEntry, mock_aiontfy: AsyncMock, freezer: FrozenDateTimeFactory, issue_registry: ir.IssueRegistry, - entity_registry: er.EntityRegistry, + remove_entity: Callable[[HomeAssistant], Coroutine[None, None, None]], ) -> None: - """Test the protected topic issue is deleted when the entity is disabled.""" + """Test the issue is deleted when the entity is disabled or removed.""" mock_aiontfy.subscribe.side_effect = NtfyForbiddenError(403, 403, "forbidden") config_entry.add_to_hass(hass) @@ -470,11 +503,119 @@ async def test_event_topic_protected_issue_deleted_on_entity_disable( assert issue_registry.async_get_issue(DOMAIN, TOPIC_PROTECTED_ISSUE_ID) - entity_registry.async_update_entity( - "event.mytopic", disabled_by=er.RegistryEntryDisabler.USER - ) + await remove_entity(hass) await hass.async_block_till_done() assert "ABCDEF" in config_entry.subentries assert hass.states.get("event.mytopic") is None assert not issue_registry.async_get_issue(DOMAIN, TOPIC_PROTECTED_ISSUE_ID) + + +async def _reload_entry(hass: HomeAssistant, config_entry: MockConfigEntry) -> None: + """Reload the config entry.""" + assert await hass.config_entries.async_reload(config_entry.entry_id) + + +async def _disable_and_enable_entry( + hass: HomeAssistant, config_entry: MockConfigEntry +) -> None: + """Disable and re-enable the config entry.""" + assert await hass.config_entries.async_set_disabled_by( + config_entry.entry_id, ConfigEntryDisabler.USER + ) + await hass.async_block_till_done() + # Core hides the issue of the disabled entry instead of it being deleted + assert ( + issue := ir.async_get(hass).async_get_issue(DOMAIN, TOPIC_PROTECTED_ISSUE_ID) + ) + assert issue.dismissed_version is not None + assert await hass.config_entries.async_set_disabled_by(config_entry.entry_id, None) + + +@pytest.mark.parametrize( + "reload_entry", + [ + pytest.param(_reload_entry, id="reload"), + pytest.param(_disable_and_enable_entry, id="disable_enable"), + ], +) +async def test_event_topic_protected_issue_ignore_kept_on_reload( + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_aiontfy: AsyncMock, + freezer: FrozenDateTimeFactory, + issue_registry: ir.IssueRegistry, + reload_entry: Callable[ + [HomeAssistant, MockConfigEntry], Coroutine[None, None, None] + ], +) -> None: + """Test an ignored protected topic issue stays ignored when the entry reloads.""" + mock_aiontfy.subscribe.side_effect = NtfyForbiddenError(403, 403, "forbidden") + + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + freezer.tick(timedelta(seconds=10)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + ir.async_ignore_issue(hass, DOMAIN, TOPIC_PROTECTED_ISSUE_ID, True) + + await reload_entry(hass, config_entry) + await hass.async_block_till_done() + assert config_entry.state is ConfigEntryState.LOADED + + freezer.tick(timedelta(seconds=10)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert (issue := issue_registry.async_get_issue(DOMAIN, TOPIC_PROTECTED_ISSUE_ID)) + assert issue.config_entry_id == config_entry.entry_id + assert issue.config_subentry_id == "ABCDEF" + assert issue.dismissed_version is not None + assert mock_aiontfy.subscribe.call_count == 2 + + +@pytest.mark.parametrize( + "disable_entity", + [ + pytest.param(_disable_entity, id="entity_disabled"), + pytest.param(_disable_device, id="device_disabled"), + ], +) +async def test_event_topic_protected_issue_deleted_on_disable_while_entry_disabled( + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_aiontfy: AsyncMock, + freezer: FrozenDateTimeFactory, + issue_registry: ir.IssueRegistry, + disable_entity: Callable[[HomeAssistant], Coroutine[None, None, None]], +) -> None: + """Test the issue is deleted if the entity is disabled while the entry is.""" + mock_aiontfy.subscribe.side_effect = NtfyForbiddenError(403, 403, "forbidden") + + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + freezer.tick(timedelta(seconds=10)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert await hass.config_entries.async_set_disabled_by( + config_entry.entry_id, ConfigEntryDisabler.USER + ) + await hass.async_block_till_done() + assert issue_registry.async_get_issue(DOMAIN, TOPIC_PROTECTED_ISSUE_ID) + + await disable_entity(hass) + await hass.async_block_till_done() + assert issue_registry.async_get_issue(DOMAIN, TOPIC_PROTECTED_ISSUE_ID) + + assert await hass.config_entries.async_set_disabled_by(config_entry.entry_id, None) + await hass.async_block_till_done() + + assert config_entry.state is ConfigEntryState.LOADED + assert hass.states.get("event.mytopic") is None + assert not issue_registry.async_get_issue(DOMAIN, TOPIC_PROTECTED_ISSUE_ID)