Deprecate YAML configuration of the prowl notify platform (#184225)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jan Bouwhuis
2026-10-23 00:22:50 +02:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 8bee57d3a3
commit 681d2cd35b
6 changed files with 834 additions and 24 deletions
+110 -5
View File
@@ -4,19 +4,91 @@ import logging
import prowlpy
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN, SERVICE_NOTIFY
from homeassistant.config import config_per_platform
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_NAME, Platform
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryError, ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers import config_validation as cv, discovery
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import slugify
from homeassistant.util.hass_dict import HassKey
from .const import DOMAIN, PLATFORMS
from .const import (
CONF_ENTRY,
CONF_LEGACY_SERVICE_NAME,
CONF_NAMES,
CONF_SETUP,
DATA_LEGACY_SETUPS,
DOMAIN,
PLATFORMS,
)
from .helpers import async_verify_key
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = cv.platform_only_config_schema(DOMAIN)
DATA_HASS_CONFIG: HassKey[ConfigType] = HassKey(f"{DOMAIN}_hass_config")
DATA_YAML_API_KEYS: HassKey[set[str]] = HassKey(f"{DOMAIN}_yaml_api_keys")
DATA_YAML_SERVICE_NAMES: HassKey[set[str]] = HassKey(f"{DOMAIN}_yaml_service_names")
def _yaml_name(p_config: ConfigType) -> str | None:
"""Return the name of a YAML notify platform as the notify schema reads it."""
# The config is not validated yet when an entry sets up the component first
if (name := p_config.get(CONF_NAME)) is None:
return None
return str(name)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Prowl component."""
hass.data[DATA_HASS_CONFIG] = config
yaml_configs = [
p_config
for platform, p_config in config_per_platform(config, NOTIFY_DOMAIN)
if platform == DOMAIN and CONF_API_KEY in p_config
]
# YAML names per API key, in YAML order, to import one entry per API key
names_by_api_key: dict[str, list[str | None]] = {}
for p_config in yaml_configs:
names = names_by_api_key.setdefault(str(p_config[CONF_API_KEY]), [])
if (name := _yaml_name(p_config)) not in names:
names.append(name)
hass.data[DATA_YAML_API_KEYS] = set(names_by_api_key)
# Matches the service names the legacy notify loader uses for YAML platforms;
# YAML of any notify platform wins over an entry-backed legacy action. Other
# platforms are not validated here; the loader skips blocks without a platform
hass.data[DATA_YAML_SERVICE_NAMES] = {
slugify(_yaml_name(p_config) or SERVICE_NOTIFY)
for platform, p_config in config_per_platform(config, NOTIFY_DOMAIN)
if platform is not None and isinstance(p_config, dict)
}
for api_key, names in names_by_api_key.items():
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_API_KEY: api_key, CONF_NAMES: names},
)
)
if names_by_api_key:
async_create_issue(
hass,
HOMEASSISTANT_DOMAIN,
f"deprecated_yaml_{DOMAIN}",
breaks_in_ha_version="2027.5.0",
is_fixable=False,
issue_domain=DOMAIN,
severity=IssueSeverity.WARNING,
translation_key="deprecated_yaml",
translation_placeholders={"domain": DOMAIN, "integration_title": "Prowl"},
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Set up a Prowl service."""
@@ -32,6 +104,39 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
raise ConfigEntryNotReady("Prowl API rate limit exceeded") from ex
raise ConfigEntryError(f"Failed to validate Prowl API key ({ex})") from ex
# A composed title (several YAML names) is not the legacy service name
legacy_service_name = entry.data.get(CONF_LEGACY_SERVICE_NAME, entry.title)
# While YAML for this API key or service name is present, YAML sets up the
# legacy service
if (
entry.source == SOURCE_IMPORT
and entry.data[CONF_API_KEY] not in hass.data[DATA_YAML_API_KEYS]
and slugify(legacy_service_name) not in hass.data[DATA_YAML_SERVICE_NAMES]
):
# A delayed setup from before an unload or reload must not register
setup = object()
legacy_setups = hass.data.setdefault(DATA_LEGACY_SETUPS, {})
legacy_setups[entry.entry_id] = setup
@callback
def _async_invalidate_legacy_setup() -> None:
if legacy_setups.get(entry.entry_id) is setup:
del legacy_setups[entry.entry_id]
entry.async_on_unload(_async_invalidate_legacy_setup)
# Owned by the entry, so unloading cancels a pending setup
entry.async_create_background_task(
hass,
discovery.async_load_platform(
hass,
Platform.NOTIFY,
DOMAIN,
{CONF_NAME: legacy_service_name, CONF_ENTRY: entry, CONF_SETUP: setup},
hass.data[DATA_HASS_CONFIG],
),
name=f"{DOMAIN} legacy notify setup",
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
+25 -1
View File
@@ -6,10 +6,11 @@ from typing import Any, override
import probatio
import prowlpy
from homeassistant.components.notify import SERVICE_NOTIFY
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_API_KEY
from .const import DOMAIN
from .const import CONF_LEGACY_SERVICE_NAME, CONF_NAMES, DOMAIN
from .helpers import async_verify_key
_LOGGER = logging.getLogger(__name__)
@@ -51,6 +52,29 @@ class ProwlConfigFlow(ConfigFlow, domain=DOMAIN):
errors=errors,
)
async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
"""Import a YAML notify platform configuration."""
api_key = import_data[CONF_API_KEY]
self._async_abort_entries_match({CONF_API_KEY: api_key})
# Not validated: API key or connection problems surface on entry setup
names: list[str | None] = import_data[CONF_NAMES]
if names[0] and len(names) == 1:
# The title is the name of the legacy notify service
return self.async_create_entry(
title=names[0],
data={CONF_API_KEY: api_key},
)
# YAML without a name provides the notify.notify service
service_names = [name or SERVICE_NOTIFY for name in names]
return self.async_create_entry(
title=", ".join(service_names) if len(names) > 1 else "Prowl",
data={
CONF_API_KEY: api_key,
CONF_LEGACY_SERVICE_NAME: service_names[0],
},
)
async def _validate_api_key(self, api_key: str) -> dict[str, str]:
"""Validate the provided API key."""
ret = {}
+8
View File
@@ -1,6 +1,14 @@
"""Constants for the Prowl Notification service."""
from homeassistant.const import Platform
from homeassistant.util.hass_dict import HassKey
DOMAIN = "prowl"
PLATFORMS = [Platform.NOTIFY]
CONF_ENTRY = "entry"
CONF_SETUP = "setup"
# Current legacy notify setup per imported entry; only that setup may register
DATA_LEGACY_SETUPS: HassKey[dict[str, object]] = HassKey(f"{DOMAIN}_legacy_setups")
CONF_LEGACY_SERVICE_NAME = "legacy_service_name"
CONF_NAMES = "names"
+57 -5
View File
@@ -12,11 +12,12 @@ from homeassistant.components.notify import (
ATTR_DATA,
ATTR_TITLE,
ATTR_TITLE_DEFAULT,
DOMAIN as NOTIFY_DOMAIN,
PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
BaseNotificationService,
NotifyEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
@@ -25,6 +26,8 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.httpx_client import get_async_client
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import CONF_ENTRY, CONF_LEGACY_SERVICE_NAME, CONF_SETUP, DATA_LEGACY_SETUPS
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend(
@@ -38,7 +41,21 @@ async def async_get_service(
discovery_info: DiscoveryInfoType | None = None,
) -> ProwlNotificationService:
"""Get the Prowl notification service."""
return ProwlNotificationService(hass, config[CONF_API_KEY], get_async_client(hass))
if discovery_info is None:
# YAML keeps providing the legacy service while it is present
return ProwlNotificationService(
hass, config[CONF_API_KEY], get_async_client(hass)
)
entry: ConfigEntry = discovery_info[CONF_ENTRY]
service = ProwlNotificationService(
hass,
entry.data[CONF_API_KEY],
get_async_client(hass),
(entry.entry_id, discovery_info[CONF_SETUP]),
)
entry.async_on_unload(service.async_unregister_services)
return service
async def async_setup_entry(
@@ -47,8 +64,13 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the notify entities."""
# A title composed of several YAML names is not used as entity name
name = "Prowl" if CONF_LEGACY_SERVICE_NAME in entry.data else entry.title
# Imported titles can collide (YAML without a name is titled like UI entries);
# entries set up in the UI keep their existing unique ID
unique_id = entry.entry_id if entry.source == SOURCE_IMPORT else entry.title
prowl = ProwlNotificationEntity(
hass, entry.title, entry.data[CONF_API_KEY], get_async_client(hass)
hass, name, unique_id, entry.data[CONF_API_KEY], get_async_client(hass)
)
async_add_entities([prowl])
@@ -60,11 +82,40 @@ class ProwlNotificationService(BaseNotificationService):
"""
def __init__(
self, hass: HomeAssistant, api_key: str, httpx_client: httpx2.AsyncClient
self,
hass: HomeAssistant,
api_key: str,
httpx_client: httpx2.AsyncClient,
legacy_setup: tuple[str, object] | None = None,
) -> None:
"""Initialize the service."""
self._hass = hass
self._prowl = prowlpy.AsyncProwl(api_key, client=httpx_client)
# Entry ID and setup of an entry-backed legacy service
self._legacy_setup = legacy_setup
self._owns_service = False
@override
async def async_register_services(self) -> None:
"""Register the legacy action for a current setup if the name is free."""
# The notify loader sets the service up in its own task, so the entry
# can unload or reload before registration
if self._legacy_setup is not None:
entry_id, setup = self._legacy_setup
if self.hass.data.get(DATA_LEGACY_SETUPS, {}).get(entry_id) is not setup:
return
if self.hass.services.has_service(NOTIFY_DOMAIN, self._service_name):
return
await super().async_register_services()
self._owns_service = True
@override
async def async_unregister_services(self) -> None:
"""Unregister the legacy action only if this service registered it."""
if not self._owns_service:
return
self._owns_service = False
await super().async_unregister_services()
@override
async def async_send_message(self, message: str, **kwargs: Any) -> None:
@@ -106,6 +157,7 @@ class ProwlNotificationEntity(NotifyEntity):
self,
hass: HomeAssistant,
name: str,
unique_id: str,
api_key: str,
httpx_client: httpx2.AsyncClient,
) -> None:
@@ -113,7 +165,7 @@ class ProwlNotificationEntity(NotifyEntity):
self._hass = hass
self._prowl = prowlpy.AsyncProwl(api_key, client=httpx_client)
self._attr_name = name
self._attr_unique_id = name
self._attr_unique_id = unique_id
@override
async def async_send_message(self, message: str, title: str | None = None) -> None:
+89 -2
View File
@@ -3,14 +3,26 @@
from unittest.mock import AsyncMock
import prowlpy
import pytest
from pytest_homeassistant.common import MockConfigEntry
from homeassistant import config_entries
from homeassistant.components.prowl.const import DOMAIN
from homeassistant.components.prowl.const import (
CONF_LEGACY_SERVICE_NAME,
CONF_NAMES,
DOMAIN,
)
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import BAD_API_RESPONSE, CONF_INPUT, INVALID_API_KEY_ERROR, TIMEOUT_ERROR
from .conftest import (
BAD_API_RESPONSE,
CONF_INPUT,
INVALID_API_KEY_ERROR,
TEST_API_KEY,
TIMEOUT_ERROR,
)
async def test_flow_user(hass: HomeAssistant, mock_prowlpy: AsyncMock) -> None:
@@ -129,3 +141,78 @@ async def test_flow_api_failure(hass: HomeAssistant, mock_prowlpy: AsyncMock) ->
user_input=CONF_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(
("names", "expected_title", "expected_data"),
[
pytest.param(["My Prowl"], "My Prowl", CONF_INPUT, id="with_name"),
pytest.param(
[None],
"Prowl",
{**CONF_INPUT, CONF_LEGACY_SERVICE_NAME: "notify"},
id="without_name",
),
pytest.param(
["one", "two"],
"one, two",
{**CONF_INPUT, CONF_LEGACY_SERVICE_NAME: "one"},
id="several_names",
),
pytest.param(
[None, "two"],
"notify, two",
{**CONF_INPUT, CONF_LEGACY_SERVICE_NAME: "notify"},
id="several_names_first_without_name",
),
],
)
@pytest.mark.usefixtures("mock_prowlpy")
async def test_flow_import(
hass: HomeAssistant,
names: list[str | None],
expected_title: str,
expected_data: dict[str, str],
) -> None:
"""Test importing the YAML configuration of an API key."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={CONF_API_KEY: TEST_API_KEY, CONF_NAMES: names},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == expected_title
assert result["data"] == expected_data
@pytest.mark.parametrize(
"source",
[
pytest.param(config_entries.SOURCE_USER, id="set_up_in_ui"),
pytest.param(config_entries.SOURCE_IMPORT, id="imported_before"),
],
)
async def test_flow_import_existing_entry(
hass: HomeAssistant,
mock_prowlpy: AsyncMock,
source: str,
) -> None:
"""Test importing YAML for an API key that already has an entry."""
entry = MockConfigEntry(
domain=DOMAIN, title="Prowl", data=CONF_INPUT, source=source
)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={CONF_API_KEY: TEST_API_KEY, CONF_NAMES: ["prowl"]},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert entry.title == "Prowl"
assert entry.data == CONF_INPUT
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
mock_prowlpy.verify_key.assert_not_called()
+545 -11
View File
@@ -1,17 +1,23 @@
"""Testing the Prowl initialisation."""
from unittest.mock import AsyncMock
import asyncio
from typing import Any
from unittest.mock import AsyncMock, patch
import prowlpy
import pytest
from pytest_homeassistant.common import MockConfigEntry
from homeassistant.components import notify
from homeassistant.components.prowl.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.components.prowl.const import CONF_LEGACY_SERVICE_NAME, DOMAIN
from homeassistant.components.prowl.notify import ProwlNotificationService
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER, ConfigEntryState
from homeassistant.const import CONF_API_KEY, CONF_NAME, CONF_PLATFORM
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
from homeassistant.helpers import issue_registry as ir
from homeassistant.setup import async_setup_component
from .conftest import ENTITY_ID, TEST_API_KEY
from .conftest import ENTITY_ID, OTHER_API_KEY, TEST_API_KEY, TEST_NAME
async def test_load_reload_unload_config_entry(
@@ -71,20 +77,548 @@ async def test_config_entry_failures(
assert mock_prowlpy.verify_key.call_count > 0
async def _setup_yaml(hass: HomeAssistant, platform_config: dict[str, str]) -> None:
"""Set up the Prowl notify platform from YAML."""
await async_setup_component(
hass,
notify.DOMAIN,
{notify.DOMAIN: [{CONF_PLATFORM: DOMAIN, **platform_config}]},
)
await hass.async_block_till_done()
@pytest.mark.usefixtures("configure_prowl_through_yaml")
async def test_both_yaml_and_config_entry(
async def test_yaml_import(
hass: HomeAssistant,
mock_prowlpy: AsyncMock,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test the YAML configuration is imported and the legacy action keeps working."""
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
entry = entries[0]
assert entry.state is ConfigEntryState.LOADED
assert entry.source == SOURCE_IMPORT
assert entry.title == DOMAIN
assert entry.data == {CONF_API_KEY: TEST_API_KEY}
assert issue_registry.async_get_issue(
HOMEASSISTANT_DOMAIN, f"deprecated_yaml_{DOMAIN}"
)
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
await hass.services.async_call(
notify.DOMAIN, DOMAIN, {notify.ATTR_MESSAGE: "Test"}, blocking=True
)
mock_prowlpy.post.assert_called_once()
# YAML provides the legacy service while it is present, not the entry
await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
@pytest.mark.usefixtures("mock_prowlpy")
async def test_yaml_import_without_name(hass: HomeAssistant) -> None:
"""Test the legacy action keeps its default name after the import."""
await _setup_yaml(hass, {CONF_API_KEY: TEST_API_KEY})
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].title == "Prowl"
assert entries[0].data == {
CONF_API_KEY: TEST_API_KEY,
CONF_LEGACY_SERVICE_NAME: notify.SERVICE_NOTIFY,
}
assert hass.services.has_service(notify.DOMAIN, notify.SERVICE_NOTIFY)
@pytest.mark.usefixtures("mock_prowlpy")
async def test_yaml_import_existing_config_entry(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
) -> None:
"""Test having both YAML config and a config entry works."""
"""Test YAML for an API key that was already set up in the UI."""
mock_prowlpy_config_entry.add_to_hass(hass)
await _setup_yaml(hass, {CONF_API_KEY: TEST_API_KEY, CONF_NAME: DOMAIN})
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert mock_prowlpy_config_entry.state is ConfigEntryState.LOADED
# The existing entry is not changed: YAML keeps providing the legacy action
assert mock_prowlpy_config_entry.title == TEST_NAME
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
assert hass.states.get(ENTITY_ID) is not None
@pytest.mark.parametrize(
("prowlpy_side_effect", "expected_state"),
[
pytest.param(
prowlpy.APIError("Invalid API key: foo"),
ConfigEntryState.SETUP_ERROR,
id="invalid_api_key",
),
pytest.param(TimeoutError, ConfigEntryState.SETUP_RETRY, id="timeout"),
],
)
async def test_yaml_import_entry_setup_failure(
hass: HomeAssistant,
mock_prowlpy: AsyncMock,
issue_registry: ir.IssueRegistry,
prowlpy_side_effect: Exception | type[Exception],
expected_state: ConfigEntryState,
) -> None:
"""Test the import is not blocked by API problems and YAML keeps working."""
mock_prowlpy.verify_key.side_effect = prowlpy_side_effect
await _setup_yaml(hass, {CONF_API_KEY: TEST_API_KEY, CONF_NAME: DOMAIN})
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].state is expected_state
assert issue_registry.async_get_issue(
HOMEASSISTANT_DOMAIN, f"deprecated_yaml_{DOMAIN}"
)
assert len(issue_registry.issues) == 1
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
await hass.services.async_call(
notify.DOMAIN, DOMAIN, {notify.ATTR_MESSAGE: "Test"}, blocking=True
)
mock_prowlpy.post.assert_called_once()
@pytest.mark.usefixtures("mock_prowlpy")
async def test_config_entry_without_legacy_service(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
) -> None:
"""Test a config entry set up in the UI does not get a legacy action."""
mock_prowlpy_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_prowlpy_config_entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID) is not None
assert not hass.services.has_service(notify.DOMAIN, DOMAIN)
assert not hass.services.has_service(notify.DOMAIN, notify.SERVICE_NOTIFY)
@pytest.mark.parametrize(
("config", "issue_expected"),
[
pytest.param(
{
notify.DOMAIN: [
{CONF_PLATFORM: DOMAIN, CONF_API_KEY: OTHER_API_KEY},
]
},
True,
id="yaml_configured",
),
pytest.param(
{notify.DOMAIN: [{CONF_PLATFORM: "other", CONF_API_KEY: "key"}]},
False,
id="other_notify_platform",
),
pytest.param({}, False, id="no_yaml"),
],
)
@pytest.mark.usefixtures("mock_prowlpy")
async def test_yaml_deprecation_issue(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
issue_registry: ir.IssueRegistry,
config: dict[str, Any],
issue_expected: bool,
) -> None:
"""Test the YAML deprecation issue is raised while YAML is present."""
mock_prowlpy_config_entry.add_to_hass(hass)
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
assert mock_prowlpy_config_entry.state is ConfigEntryState.LOADED
assert (
issue_registry.async_get_issue(
HOMEASSISTANT_DOMAIN, f"deprecated_yaml_{DOMAIN}"
)
is not None
) is issue_expected
@pytest.mark.parametrize(
("title", "extra_data", "service"),
[
pytest.param("prowl", {}, "prowl", id="yaml_name"),
pytest.param("My Prowl", {}, "my_prowl", id="slugified"),
pytest.param(
"one, two",
{CONF_LEGACY_SERVICE_NAME: "one"},
"one",
id="several_yaml_names",
),
pytest.param(
"Prowl",
{CONF_LEGACY_SERVICE_NAME: "notify"},
"notify",
id="yaml_without_name",
),
],
)
async def test_legacy_service_from_config_entry(
hass: HomeAssistant,
mock_prowlpy: AsyncMock,
title: str,
extra_data: dict[str, str],
service: str,
) -> None:
"""Test an imported entry sets up the legacy action after YAML is removed."""
entry = MockConfigEntry(
domain=DOMAIN,
title=title,
data={CONF_API_KEY: TEST_API_KEY, **extra_data},
source=SOURCE_IMPORT,
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
# The legacy action is set up in a background task of the entry
await hass.async_block_till_done(wait_background_tasks=True)
assert entry.state is ConfigEntryState.LOADED
assert hass.services.has_service(notify.DOMAIN, service)
await hass.services.async_call(
notify.DOMAIN, service, {notify.ATTR_MESSAGE: "Test"}, blocking=True
)
mock_prowlpy.post.assert_called_once()
await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert not hass.services.has_service(notify.DOMAIN, service)
@pytest.mark.usefixtures("mock_prowlpy")
async def test_legacy_service_setup_cancelled_on_unload(hass: HomeAssistant) -> None:
"""Test unloading an imported entry cancels a pending legacy action setup."""
started = asyncio.Event()
cancelled = asyncio.Event()
async def pending_load_platform(*args: Any) -> None:
started.set()
try:
await asyncio.Event().wait()
except asyncio.CancelledError:
cancelled.set()
raise
entry = MockConfigEntry(
domain=DOMAIN,
title="prowl",
data={CONF_API_KEY: TEST_API_KEY},
source=SOURCE_IMPORT,
)
entry.add_to_hass(hass)
with patch(
"homeassistant.components.prowl.discovery.async_load_platform",
pending_load_platform,
):
await hass.config_entries.async_setup(entry.entry_id)
await started.wait()
await hass.config_entries.async_unload(entry.entry_id)
assert cancelled.is_set()
assert not hass.services.has_service(notify.DOMAIN, "prowl")
@pytest.mark.parametrize(
"notify_block",
[
pytest.param(None, id="empty"),
pytest.param("not a mapping", id="string"),
pytest.param({CONF_PLATFORM: "group", CONF_NAME: 123}, id="name_not_a_string"),
],
)
@pytest.mark.usefixtures("mock_prowlpy")
async def test_setup_with_invalid_yaml_notify_block(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
notify_block: Any,
) -> None:
"""Test an unvalidated YAML notify block of another platform keeps setup working."""
mock_prowlpy_config_entry.add_to_hass(hass)
assert await async_setup_component(hass, DOMAIN, {notify.DOMAIN: [notify_block]})
await hass.async_block_till_done()
assert mock_prowlpy_config_entry.state is ConfigEntryState.LOADED
# Ensure we have the YAML entity service
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
# Ensure we have the config entry entity service
assert hass.states.get(ENTITY_ID) is not None
@pytest.mark.usefixtures("mock_prowlpy")
async def test_yaml_import_of_unvalidated_values(hass: HomeAssistant) -> None:
"""Test YAML values are imported as the notify schema reads them."""
# Setting up the component directly passes the YAML before notify validates it
config = {
notify.DOMAIN: [{CONF_PLATFORM: DOMAIN, CONF_API_KEY: 1234, CONF_NAME: 0}]
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].title == "0"
assert entries[0].data == {CONF_API_KEY: "1234"}
@pytest.mark.usefixtures("mock_prowlpy")
async def test_yaml_notify_block_without_platform_does_not_reserve_name(
hass: HomeAssistant,
) -> None:
"""Test a YAML notify block without a platform leaves its name to the entry."""
entry = MockConfigEntry(
domain=DOMAIN,
title="phone",
data={CONF_API_KEY: TEST_API_KEY},
source=SOURCE_IMPORT,
)
entry.add_to_hass(hass)
with patch(
"homeassistant.components.prowl.discovery.async_load_platform"
) as mock_load_platform:
assert await async_setup_component(
hass, DOMAIN, {notify.DOMAIN: [{CONF_NAME: "phone"}]}
)
await hass.async_block_till_done(wait_background_tasks=True)
assert entry.state is ConfigEntryState.LOADED
mock_load_platform.assert_called_once()
@pytest.mark.usefixtures("mock_prowlpy")
async def test_other_yaml_notify_platform_name_wins_over_imported_entry(
hass: HomeAssistant,
) -> None:
"""Test an imported entry leaves a name used by other YAML notify platforms."""
entry = MockConfigEntry(
domain=DOMAIN,
title="phone",
data={CONF_API_KEY: TEST_API_KEY},
source=SOURCE_IMPORT,
)
entry.add_to_hass(hass)
config = {
notify.DOMAIN: [
{
CONF_PLATFORM: "group",
CONF_NAME: "phone",
"services": [{"action": "persistent_notification"}],
}
]
}
with patch(
"homeassistant.components.prowl.discovery.async_load_platform"
) as mock_load_platform:
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done(wait_background_tasks=True)
assert entry.state is ConfigEntryState.LOADED
mock_load_platform.assert_not_called()
@pytest.mark.usefixtures("mock_prowlpy")
async def test_legacy_service_not_registered_after_unload(hass: HomeAssistant) -> None:
"""Test the notify loader does not register the action of an unloaded entry."""
started = asyncio.Event()
release = asyncio.Event()
original_setup = ProwlNotificationService.async_setup
async def paused_setup(self: ProwlNotificationService, *args: Any) -> None:
await original_setup(self, *args)
started.set()
await release.wait()
entry = MockConfigEntry(
domain=DOMAIN,
title="prowl",
data={CONF_API_KEY: TEST_API_KEY},
source=SOURCE_IMPORT,
)
entry.add_to_hass(hass)
with patch.object(ProwlNotificationService, "async_setup", paused_setup):
await hass.config_entries.async_setup(entry.entry_id)
# The notify loader is now between setting up and registering the action
await started.wait()
await hass.config_entries.async_unload(entry.entry_id)
release.set()
await hass.async_block_till_done(wait_background_tasks=True)
assert entry.state is ConfigEntryState.NOT_LOADED
assert not hass.services.has_service(notify.DOMAIN, "prowl")
@pytest.mark.usefixtures("mock_prowlpy")
async def test_legacy_service_of_setup_before_reload_not_registered(
hass: HomeAssistant,
) -> None:
"""Test a delayed legacy setup from before a reload does not register."""
release = asyncio.Event()
started: list[asyncio.Event] = []
original_setup = ProwlNotificationService.async_setup
async def paused_setup(self: ProwlNotificationService, *args: Any) -> None:
await original_setup(self, *args)
started[-1].set()
await release.wait()
entry = MockConfigEntry(
domain=DOMAIN,
title="prowl",
data={CONF_API_KEY: TEST_API_KEY},
source=SOURCE_IMPORT,
)
entry.add_to_hass(hass)
with patch.object(ProwlNotificationService, "async_setup", paused_setup):
started.append(asyncio.Event())
await hass.config_entries.async_setup(entry.entry_id)
await started[-1].wait()
await hass.config_entries.async_unload(entry.entry_id)
# Reload before the notify loader resumes the setup from before the unload
started.append(asyncio.Event())
await hass.config_entries.async_setup(entry.entry_id)
await started[-1].wait()
release.set()
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.services.has_service(notify.DOMAIN, "prowl")
# The current setup owns the action, so unloading removes it
await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert not hass.services.has_service(notify.DOMAIN, "prowl")
@pytest.mark.usefixtures("mock_prowlpy")
async def test_legacy_service_unload_keeps_action_of_other_entry(
hass: HomeAssistant,
) -> None:
"""Test unloading an entry that lost a name collision keeps the other action."""
entries = [
MockConfigEntry(
domain=DOMAIN,
title="phone",
data={CONF_API_KEY: api_key},
source=SOURCE_IMPORT,
)
for api_key in (TEST_API_KEY, OTHER_API_KEY)
]
for entry in entries:
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.services.has_service(notify.DOMAIN, "phone")
# The second entry did not register notify.phone, the first one owns it
await hass.config_entries.async_unload(entries[1].entry_id)
await hass.async_block_till_done()
assert hass.services.has_service(notify.DOMAIN, "phone")
await hass.config_entries.async_unload(entries[0].entry_id)
await hass.async_block_till_done()
assert not hass.services.has_service(notify.DOMAIN, "phone")
@pytest.mark.usefixtures("mock_prowlpy")
async def test_imported_and_ui_entries_with_the_same_title(
hass: HomeAssistant,
) -> None:
"""Test an imported entry titled like a UI entry still gets a notify entity."""
for source, api_key in (
(SOURCE_USER, TEST_API_KEY),
(SOURCE_IMPORT, OTHER_API_KEY),
):
entry = MockConfigEntry(
domain=DOMAIN,
title="Prowl",
data={CONF_API_KEY: api_key},
source=source,
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done(wait_background_tasks=True)
assert len(hass.states.async_entity_ids(notify.DOMAIN)) == 2
@pytest.mark.usefixtures("mock_prowlpy")
async def test_legacy_service_keeps_other_yaml_notify_platforms(
hass: HomeAssistant,
) -> None:
"""Test the legacy action from an entry keeps other YAML notify platforms."""
entry = MockConfigEntry(
domain=DOMAIN,
title="prowl",
data={CONF_API_KEY: TEST_API_KEY},
source=SOURCE_IMPORT,
)
entry.add_to_hass(hass)
config = {
notify.DOMAIN: [
{CONF_PLATFORM: DOMAIN, CONF_API_KEY: OTHER_API_KEY, CONF_NAME: "other"}
]
}
# The entry sets up notify before it is set up from the YAML config
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.services.has_service(notify.DOMAIN, "prowl")
assert hass.services.has_service(notify.DOMAIN, "other")
@pytest.mark.usefixtures("mock_prowlpy")
async def test_yaml_service_name_wins_over_imported_entry(hass: HomeAssistant) -> None:
"""Test YAML keeps its legacy action after an API key rotation."""
stale_entry = MockConfigEntry(
domain=DOMAIN,
title="phone",
data={CONF_API_KEY: TEST_API_KEY},
source=SOURCE_IMPORT,
)
stale_entry.add_to_hass(hass)
config = {
notify.DOMAIN: [
{CONF_PLATFORM: DOMAIN, CONF_API_KEY: OTHER_API_KEY, CONF_NAME: "phone"}
]
}
assert await async_setup_component(hass, notify.DOMAIN, config)
await hass.async_block_till_done()
assert hass.services.has_service(notify.DOMAIN, "phone")
# An entry-backed legacy action would be removed with its entry
await hass.config_entries.async_unload(stale_entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service(notify.DOMAIN, "phone")
@pytest.mark.usefixtures("mock_prowlpy")
async def test_yaml_import_multiple_names(hass: HomeAssistant) -> None:
"""Test several YAML notifiers with the same API key create one entry."""
await async_setup_component(
hass,
notify.DOMAIN,
{
notify.DOMAIN: [
{CONF_PLATFORM: DOMAIN, CONF_API_KEY: TEST_API_KEY, CONF_NAME: "one"},
{CONF_PLATFORM: DOMAIN, CONF_API_KEY: TEST_API_KEY, CONF_NAME: "two"},
]
},
)
await hass.async_block_till_done()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].title == "one, two"
assert entries[0].data == {
CONF_API_KEY: TEST_API_KEY,
CONF_LEGACY_SERVICE_NAME: "one",
}
assert hass.states.async_entity_ids(notify.DOMAIN) == ["notify.prowl"]
# YAML provides both legacy actions while it is present
assert hass.services.has_service(notify.DOMAIN, "one")
assert hass.services.has_service(notify.DOMAIN, "two")