1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-24 21:06:19 +00:00

Add ConfigFlow to Prowl integration (#133771)

Co-authored-by: Norbert Rittel <norbert@rittel.de>
This commit is contained in:
Marcus Gustavsson
2025-10-10 08:41:45 +01:00
committed by GitHub
parent eb04dda197
commit 54d30377d3
13 changed files with 551 additions and 16 deletions

View File

@@ -1 +1,41 @@
"""The prowl component."""
import logging
import prowlpy
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryError, ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv
from .const import DOMAIN, PLATFORMS
from .helpers import async_verify_key
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = cv.platform_only_config_schema(DOMAIN)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a Prowl service."""
try:
if not await async_verify_key(hass, entry.data[CONF_API_KEY]):
raise ConfigEntryError(
"Unable to validate Prowl API key (Key invalid or expired)"
)
except TimeoutError as ex:
raise ConfigEntryNotReady("API call to Prowl failed") from ex
except prowlpy.APIError as ex:
if str(ex).startswith("Not accepted: exceeded rate limit"):
raise ConfigEntryNotReady("Prowl API rate limit exceeded") from ex
raise ConfigEntryError("Failed to validate Prowl API key ({ex})") from ex
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@@ -0,0 +1,68 @@
"""The config flow for the Prowl component."""
from __future__ import annotations
import logging
from typing import Any
import prowlpy
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_API_KEY, CONF_NAME
from .const import DOMAIN
from .helpers import async_verify_key
_LOGGER = logging.getLogger(__name__)
class ProwlConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for the Prowl component."""
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle user configuration."""
errors = {}
if user_input:
api_key = user_input[CONF_API_KEY]
self._async_abort_entries_match({CONF_API_KEY: api_key})
errors = await self._validate_api_key(api_key)
if not errors:
return self.async_create_entry(
title=user_input[CONF_NAME],
data={
CONF_API_KEY: api_key,
},
)
return self.async_show_form(
step_id="user",
data_schema=self.add_suggested_values_to_schema(
vol.Schema(
{
vol.Required(CONF_API_KEY): str,
vol.Required(CONF_NAME): str,
},
),
user_input or {CONF_NAME: "Prowl"},
),
errors=errors,
)
async def _validate_api_key(self, api_key: str) -> dict[str, str]:
"""Validate the provided API key."""
ret = {}
try:
if not await async_verify_key(self.hass, api_key):
ret = {"base": "invalid_api_key"}
except TimeoutError:
ret = {"base": "api_timeout"}
except prowlpy.APIError:
ret = {"base": "bad_api_response"}
return ret

View File

@@ -1,3 +1,6 @@
"""Constants for the Prowl Notification service."""
from homeassistant.const import Platform
DOMAIN = "prowl"
PLATFORMS = [Platform.NOTIFY]

View File

@@ -0,0 +1,21 @@
"""Helper functions for Prowl."""
import asyncio
from functools import partial
import prowlpy
from homeassistant.core import HomeAssistant
async def async_verify_key(hass: HomeAssistant, api_key: str) -> bool:
"""Validate API key."""
prowl = await hass.async_add_executor_job(partial(prowlpy.Prowl, api_key))
try:
async with asyncio.timeout(10):
await hass.async_add_executor_job(prowl.verify_key)
return True
except prowlpy.APIError as ex:
if str(ex).startswith("Invalid API key"):
return False
raise

View File

@@ -2,6 +2,7 @@
"domain": "prowl",
"name": "Prowl",
"codeowners": [],
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/prowl",
"integration_type": "service",
"iot_class": "cloud_push",

View File

@@ -16,11 +16,14 @@ from homeassistant.components.notify import (
ATTR_TITLE_DEFAULT,
PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
BaseNotificationService,
NotifyEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
_LOGGER = logging.getLogger(__name__)
@@ -34,19 +37,31 @@ async def async_get_service(
discovery_info: DiscoveryInfoType | None = None,
) -> ProwlNotificationService:
"""Get the Prowl notification service."""
prowl = await hass.async_add_executor_job(
partial(prowlpy.Prowl, apikey=config[CONF_API_KEY])
return await hass.async_add_executor_job(
partial(ProwlNotificationService, hass, config[CONF_API_KEY])
)
return ProwlNotificationService(hass, prowl)
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the notify entities."""
prowl = ProwlNotificationEntity(hass, entry.title, entry.data[CONF_API_KEY])
async_add_entities([prowl])
class ProwlNotificationService(BaseNotificationService):
"""Implement the notification service for Prowl."""
"""Implement the notification service for Prowl.
def __init__(self, hass: HomeAssistant, prowl: prowlpy.Prowl) -> None:
This class is used for legacy configuration via configuration.yaml
"""
def __init__(self, hass: HomeAssistant, api_key: str) -> None:
"""Initialize the service."""
self._hass = hass
self._prowl = prowl
self._prowl = prowlpy.Prowl(api_key)
async def async_send_message(self, message: str, **kwargs: Any) -> None:
"""Send the message to the user."""
@@ -80,3 +95,47 @@ class ProwlNotificationService(BaseNotificationService):
) from ex
_LOGGER.error("Unexpected error when calling Prowl API: %s", str(ex))
raise HomeAssistantError("Unexpected error when calling Prowl API") from ex
class ProwlNotificationEntity(NotifyEntity):
"""Implement the notification service for Prowl.
This class is used for Prowl config entries.
"""
def __init__(self, hass: HomeAssistant, name: str, api_key: str) -> None:
"""Initialize the service."""
self._hass = hass
self._prowl = prowlpy.Prowl(api_key)
self._attr_name = name
self._attr_unique_id = name
async def async_send_message(self, message: str, title: str | None = None) -> None:
"""Send the message."""
_LOGGER.debug("Sending Prowl notification from entity %s", self.name)
try:
async with asyncio.timeout(10):
await self._hass.async_add_executor_job(
partial(
self._prowl.send,
application="Home-Assistant",
event=title or ATTR_TITLE_DEFAULT,
description=message,
priority=0,
url=None,
)
)
except TimeoutError as ex:
_LOGGER.error("Timeout accessing Prowl API")
raise HomeAssistantError("Timeout accessing Prowl API") from ex
except prowlpy.APIError as ex:
if str(ex).startswith("Invalid API key"):
_LOGGER.error("Invalid API key for Prowl service")
raise HomeAssistantError("Invalid API key for Prowl service") from ex
if str(ex).startswith("Not accepted"):
_LOGGER.error("Prowl returned: exceeded rate limit")
raise HomeAssistantError(
"Prowl service reported: exceeded rate limit"
) from ex
_LOGGER.error("Unexpected error when calling Prowl API: %s", str(ex))
raise HomeAssistantError("Unexpected error when calling Prowl API") from ex

View File

@@ -0,0 +1,21 @@
{
"config": {
"step": {
"user": {
"description": "Enter the Prowl API key and its name.",
"data": {
"api_key": "[%key:common::config_flow::data::api_key%]",
"name": "[%key:common::config_flow::data::name%]"
}
}
},
"error": {
"invalid_api_key": "[%key:common::config_flow::error::invalid_api_key%]",
"api_timeout": "[%key:common::config_flow::error::timeout_connect%]",
"bad_api_response": "[%key:common::config_flow::error::unknown%]"
},
"abort": {
"already_configured": "API key is already configured"
}
}
}

View File

@@ -512,6 +512,7 @@ FLOWS = {
"profiler",
"progettihwsw",
"prosegur",
"prowl",
"proximity",
"prusalink",
"ps4",

View File

@@ -5185,7 +5185,7 @@
"prowl": {
"name": "Prowl",
"integration_type": "service",
"config_flow": false,
"config_flow": true,
"iot_class": "cloud_push"
},
"proximity": {

View File

@@ -7,10 +7,22 @@ import pytest
from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN
from homeassistant.components.prowl.const import DOMAIN
from homeassistant.const import CONF_API_KEY, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
TEST_NAME = "TestProwl"
TEST_SERVICE = TEST_NAME.lower()
ENTITY_ID = f"{NOTIFY_DOMAIN}.{TEST_SERVICE}"
TEST_API_KEY = "f00f" * 10
OTHER_API_KEY = "beef" * 10
CONF_INPUT = {CONF_API_KEY: TEST_API_KEY, CONF_NAME: TEST_NAME}
CONF_INPUT_NEW_KEY = {CONF_API_KEY: OTHER_API_KEY}
INVALID_API_KEY_ERROR = {"base": "invalid_api_key"}
TIMEOUT_ERROR = {"base": "api_timeout"}
BAD_API_RESPONSE = {"base": "bad_api_response"}
@pytest.fixture
@@ -34,6 +46,20 @@ async def configure_prowl_through_yaml(
await hass.async_block_till_done()
@pytest.fixture
async def prowl_notification_entity(
hass: HomeAssistant, mock_prowlpy: Mock, mock_prowlpy_config_entry: MockConfigEntry
) -> Generator[MockConfigEntry]:
"""Configure a Prowl Notification Entity."""
mock_prowlpy.verify_key.return_value = True
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()
return mock_prowlpy_config_entry
@pytest.fixture
def mock_prowlpy() -> Generator[Mock]:
"""Mock the prowlpy library."""
@@ -41,3 +67,11 @@ def mock_prowlpy() -> Generator[Mock]:
with patch("homeassistant.components.prowl.notify.prowlpy.Prowl") as MockProwl:
mock_instance = MockProwl.return_value
yield mock_instance
@pytest.fixture
async def mock_prowlpy_config_entry(hass: HomeAssistant) -> MockConfigEntry:
"""Fixture to create a mocked ConfigEntry."""
return MockConfigEntry(
title=TEST_NAME, domain=DOMAIN, data={CONF_API_KEY: TEST_API_KEY}
)

View File

@@ -0,0 +1,106 @@
"""Test Prowl config flow."""
from unittest.mock import Mock
import prowlpy
from homeassistant import config_entries
from homeassistant.components.prowl.const import DOMAIN
from homeassistant.const import CONF_API_KEY, CONF_NAME
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
async def test_flow_user(hass: HomeAssistant, mock_prowlpy: Mock) -> None:
"""Test user initialized flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
assert mock_prowlpy.verify_key.call_count > 0
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == CONF_INPUT[CONF_NAME]
assert result["data"] == {CONF_API_KEY: CONF_INPUT[CONF_API_KEY]}
async def test_flow_duplicate_api_key(hass: HomeAssistant, mock_prowlpy: Mock) -> None:
"""Test user initialized flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
assert result["type"] is FlowResultType.ABORT
async def test_flow_user_bad_key(hass: HomeAssistant, mock_prowlpy: Mock) -> None:
"""Test user submitting a bad API key."""
mock_prowlpy.verify_key.side_effect = prowlpy.APIError("Invalid API key")
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
assert mock_prowlpy.verify_key.call_count > 0
assert result["type"] is FlowResultType.FORM
assert result["errors"] == INVALID_API_KEY_ERROR
async def test_flow_user_prowl_timeout(hass: HomeAssistant, mock_prowlpy: Mock) -> None:
"""Test Prowl API timeout."""
mock_prowlpy.verify_key.side_effect = TimeoutError
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
assert mock_prowlpy.verify_key.call_count > 0
assert result["type"] is FlowResultType.FORM
assert result["errors"] == TIMEOUT_ERROR
async def test_flow_api_failure(hass: HomeAssistant, mock_prowlpy: Mock) -> None:
"""Test Prowl API failure."""
mock_prowlpy.verify_key.side_effect = prowlpy.APIError(BAD_API_RESPONSE)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
assert mock_prowlpy.verify_key.call_count > 0
assert result["type"] is FlowResultType.FORM
assert result["errors"] == BAD_API_RESPONSE

View File

@@ -0,0 +1,91 @@
"""Testing the Prowl initialisation."""
from unittest.mock import Mock
import prowlpy
import pytest
from homeassistant.components import notify
from homeassistant.components.prowl.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from .conftest import ENTITY_ID, TEST_API_KEY
from tests.common import MockConfigEntry
async def test_load_reload_unload_config_entry(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
mock_prowlpy: Mock,
) -> None:
"""Test the Prowl configuration entry loading/reloading/unloading."""
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 mock_prowlpy_config_entry.state is ConfigEntryState.LOADED
assert mock_prowlpy.verify_key.call_count > 0
await hass.config_entries.async_reload(mock_prowlpy_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_prowlpy_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_prowlpy_config_entry.entry_id)
await hass.async_block_till_done()
assert not hass.data.get(DOMAIN)
assert mock_prowlpy_config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
("prowlpy_side_effect", "expected_config_state"),
[
(TimeoutError, ConfigEntryState.SETUP_RETRY),
(
prowlpy.APIError(f"Invalid API key: {TEST_API_KEY}"),
ConfigEntryState.SETUP_ERROR,
),
(
prowlpy.APIError("Not accepted: exceeded rate limit"),
ConfigEntryState.SETUP_RETRY,
),
(prowlpy.APIError("Internal server error"), ConfigEntryState.SETUP_ERROR),
],
)
async def test_config_entry_failures(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
mock_prowlpy: Mock,
prowlpy_side_effect,
expected_config_state: ConfigEntryState,
) -> None:
"""Test the Prowl configuration entry dealing with bad API key."""
mock_prowlpy.verify_key.side_effect = prowlpy_side_effect
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 mock_prowlpy_config_entry.state is expected_config_state
assert mock_prowlpy.verify_key.call_count > 0
@pytest.mark.usefixtures("configure_prowl_through_yaml")
async def test_both_yaml_and_config_entry(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
) -> None:
"""Test having both YAML config and a config entry works."""
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 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

View File

@@ -6,12 +6,14 @@ from unittest.mock import Mock
import prowlpy
import pytest
from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN
from homeassistant.components import notify
from homeassistant.components.prowl.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from .conftest import TEST_API_KEY
from .conftest import ENTITY_ID, TEST_API_KEY
from tests.common import MockConfigEntry
SERVICE_DATA = {"message": "Test Notification", "title": "Test Title"}
@@ -30,9 +32,9 @@ async def test_send_notification_service(
mock_prowlpy: Mock,
) -> None:
"""Set up Prowl, call notify service, and check API call."""
assert hass.services.has_service(NOTIFY_DOMAIN, DOMAIN)
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
await hass.services.async_call(
NOTIFY_DOMAIN,
notify.DOMAIN,
DOMAIN,
SERVICE_DATA,
blocking=True,
@@ -41,6 +43,94 @@ async def test_send_notification_service(
mock_prowlpy.send.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
async def test_send_notification_entity_service(
hass: HomeAssistant,
mock_prowlpy: Mock,
mock_prowlpy_config_entry: MockConfigEntry,
) -> None:
"""Set up Prowl via config entry, call notify service, and check API call."""
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.services.has_service(notify.DOMAIN, notify.SERVICE_SEND_MESSAGE)
await hass.services.async_call(
notify.DOMAIN,
notify.SERVICE_SEND_MESSAGE,
{
"entity_id": ENTITY_ID,
notify.ATTR_MESSAGE: SERVICE_DATA["message"],
notify.ATTR_TITLE: SERVICE_DATA["title"],
},
blocking=True,
)
mock_prowlpy.send.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
@pytest.mark.parametrize(
("prowlpy_side_effect", "raised_exception", "exception_message"),
[
(
prowlpy.APIError("Internal server error"),
HomeAssistantError,
"Unexpected error when calling Prowl API",
),
(
TimeoutError,
HomeAssistantError,
"Timeout accessing Prowl API",
),
(
prowlpy.APIError(f"Invalid API key: {TEST_API_KEY}"),
HomeAssistantError,
"Invalid API key for Prowl service",
),
(
prowlpy.APIError(
"Not accepted: Your IP address has exceeded the API limit"
),
HomeAssistantError,
"Prowl service reported: exceeded rate limit",
),
(
SyntaxError(),
SyntaxError,
None,
),
],
)
async def test_fail_send_notification_entity_service(
hass: HomeAssistant,
mock_prowlpy: Mock,
mock_prowlpy_config_entry: MockConfigEntry,
prowlpy_side_effect: Exception,
raised_exception: type[Exception],
exception_message: str | None,
) -> None:
"""Set up Prowl via config entry, call notify service, and check API call."""
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()
mock_prowlpy.send.side_effect = prowlpy_side_effect
assert hass.services.has_service(notify.DOMAIN, notify.SERVICE_SEND_MESSAGE)
with pytest.raises(raised_exception, match=exception_message):
await hass.services.async_call(
notify.DOMAIN,
notify.SERVICE_SEND_MESSAGE,
{
"entity_id": ENTITY_ID,
notify.ATTR_MESSAGE: SERVICE_DATA["message"],
notify.ATTR_TITLE: SERVICE_DATA["title"],
},
blocking=True,
)
mock_prowlpy.send.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
@pytest.mark.parametrize(
("prowlpy_side_effect", "raised_exception", "exception_message"),
[
@@ -84,10 +174,10 @@ async def test_fail_send_notification(
"""Sending a message via Prowl with a failure."""
mock_prowlpy.send.side_effect = prowlpy_side_effect
assert hass.services.has_service(NOTIFY_DOMAIN, DOMAIN)
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
with pytest.raises(raised_exception, match=exception_message):
await hass.services.async_call(
NOTIFY_DOMAIN,
notify.DOMAIN,
DOMAIN,
SERVICE_DATA,
blocking=True,
@@ -121,13 +211,13 @@ async def test_other_exception_send_notification(
"""Sending a message via Prowl with a general unhandled exception."""
mock_prowlpy.send.side_effect = SyntaxError
assert hass.services.has_service(NOTIFY_DOMAIN, DOMAIN)
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
with pytest.raises(SyntaxError):
await hass.services.async_call(
NOTIFY_DOMAIN,
notify.DOMAIN,
DOMAIN,
SERVICE_DATA,
blocking=True,
)
mock_prowlpy.send.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
mock_prowlpy.send.assert_called_once_with(**expected_send_parameters)