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

Updated prowlpy to 1.1.1 and changed the usage to do asynchronous calls (#154193)

This commit is contained in:
Marcus Gustavsson
2025-10-12 20:17:43 +01:00
committed by GitHub
parent c9d67d596b
commit 9b9c55b37b
9 changed files with 84 additions and 62 deletions

View File

@@ -1,19 +1,19 @@
"""Helper functions for Prowl."""
import asyncio
from functools import partial
import prowlpy
from homeassistant.core import HomeAssistant
from homeassistant.helpers.httpx_client import get_async_client
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))
prowl = prowlpy.AsyncProwl(api_key, client=get_async_client(hass))
try:
async with asyncio.timeout(10):
await hass.async_add_executor_job(prowl.verify_key)
await prowl.verify_key()
return True
except prowlpy.APIError as ex:
if str(ex).startswith("Invalid API key"):

View File

@@ -8,5 +8,5 @@
"iot_class": "cloud_push",
"loggers": ["prowl"],
"quality_scale": "legacy",
"requirements": ["prowlpy==1.0.2"]
"requirements": ["prowlpy==1.1.1"]
}

View File

@@ -3,10 +3,10 @@
from __future__ import annotations
import asyncio
from functools import partial
import logging
from typing import Any
import httpx
import prowlpy
import voluptuous as vol
@@ -24,6 +24,7 @@ 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.httpx_client import get_async_client
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
_LOGGER = logging.getLogger(__name__)
@@ -37,9 +38,7 @@ async def async_get_service(
discovery_info: DiscoveryInfoType | None = None,
) -> ProwlNotificationService:
"""Get the Prowl notification service."""
return await hass.async_add_executor_job(
partial(ProwlNotificationService, hass, config[CONF_API_KEY])
)
return ProwlNotificationService(hass, config[CONF_API_KEY], get_async_client(hass))
async def async_setup_entry(
@@ -48,7 +47,9 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the notify entities."""
prowl = ProwlNotificationEntity(hass, entry.title, entry.data[CONF_API_KEY])
prowl = ProwlNotificationEntity(
hass, entry.title, entry.data[CONF_API_KEY], get_async_client(hass)
)
async_add_entities([prowl])
@@ -58,10 +59,12 @@ class ProwlNotificationService(BaseNotificationService):
This class is used for legacy configuration via configuration.yaml
"""
def __init__(self, hass: HomeAssistant, api_key: str) -> None:
def __init__(
self, hass: HomeAssistant, api_key: str, httpx_client: httpx.AsyncClient
) -> None:
"""Initialize the service."""
self._hass = hass
self._prowl = prowlpy.Prowl(api_key)
self._prowl = prowlpy.AsyncProwl(api_key, client=httpx_client)
async def async_send_message(self, message: str, **kwargs: Any) -> None:
"""Send the message to the user."""
@@ -71,15 +74,12 @@ class ProwlNotificationService(BaseNotificationService):
try:
async with asyncio.timeout(10):
await self._hass.async_add_executor_job(
partial(
self._prowl.send,
application="Home-Assistant",
event=kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT),
description=message,
priority=data.get("priority", 0),
url=data.get("url"),
)
await self._prowl.post(
application="Home-Assistant",
event=kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT),
description=message,
priority=data.get("priority", 0),
url=data.get("url"),
)
except TimeoutError as ex:
_LOGGER.error("Timeout accessing Prowl API")
@@ -103,10 +103,16 @@ class ProwlNotificationEntity(NotifyEntity):
This class is used for Prowl config entries.
"""
def __init__(self, hass: HomeAssistant, name: str, api_key: str) -> None:
def __init__(
self,
hass: HomeAssistant,
name: str,
api_key: str,
httpx_client: httpx.AsyncClient,
) -> None:
"""Initialize the service."""
self._hass = hass
self._prowl = prowlpy.Prowl(api_key)
self._prowl = prowlpy.AsyncProwl(api_key, client=httpx_client)
self._attr_name = name
self._attr_unique_id = name
@@ -115,15 +121,12 @@ class ProwlNotificationEntity(NotifyEntity):
_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,
)
await self._prowl.post(
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")

2
requirements_all.txt generated
View File

@@ -1744,7 +1744,7 @@ proliphix==0.4.1
prometheus-client==0.21.0
# homeassistant.components.prowl
prowlpy==1.0.2
prowlpy==1.1.1
# homeassistant.components.proxmoxve
proxmoxer==2.0.1

View File

@@ -1479,7 +1479,7 @@ prayer-times-calculator-offline==1.0.3
prometheus-client==0.21.0
# homeassistant.components.prowl
prowlpy==1.0.2
prowlpy==1.1.1
# homeassistant.components.hardware
# homeassistant.components.recorder

View File

@@ -1,7 +1,7 @@
"""Test fixtures for Prowl."""
from collections.abc import Generator
from unittest.mock import Mock, patch
from unittest.mock import AsyncMock, patch
import pytest
@@ -27,7 +27,7 @@ BAD_API_RESPONSE = {"base": "bad_api_response"}
@pytest.fixture
async def configure_prowl_through_yaml(
hass: HomeAssistant, mock_prowlpy: Generator[Mock]
hass: HomeAssistant, mock_prowlpy: Generator[AsyncMock]
) -> Generator[None]:
"""Configure the notify domain with YAML for the Prowl platform."""
await async_setup_component(
@@ -48,7 +48,9 @@ async def configure_prowl_through_yaml(
@pytest.fixture
async def prowl_notification_entity(
hass: HomeAssistant, mock_prowlpy: Mock, mock_prowlpy_config_entry: MockConfigEntry
hass: HomeAssistant,
mock_prowlpy: AsyncMock,
mock_prowlpy_config_entry: MockConfigEntry,
) -> Generator[MockConfigEntry]:
"""Configure a Prowl Notification Entity."""
mock_prowlpy.verify_key.return_value = True
@@ -61,11 +63,24 @@ async def prowl_notification_entity(
@pytest.fixture
def mock_prowlpy() -> Generator[Mock]:
def mock_prowlpy() -> Generator[AsyncMock]:
"""Mock the prowlpy library."""
mock_instance = AsyncMock()
with patch("homeassistant.components.prowl.notify.prowlpy.Prowl") as MockProwl:
mock_instance = MockProwl.return_value
with (
patch(
"homeassistant.components.prowl.notify.prowlpy.AsyncProwl",
return_value=mock_instance,
),
patch(
"homeassistant.components.prowl.helpers.prowlpy.AsyncProwl",
return_value=mock_instance,
),
patch(
"homeassistant.components.prowl.__init__.prowlpy.AsyncProwl",
return_value=mock_instance,
),
):
yield mock_instance

View File

@@ -1,6 +1,6 @@
"""Test Prowl config flow."""
from unittest.mock import Mock
from unittest.mock import AsyncMock
import prowlpy
@@ -13,7 +13,7 @@ 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:
async def test_flow_user(hass: HomeAssistant, mock_prowlpy: AsyncMock) -> None:
"""Test user initialized flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -30,7 +30,9 @@ async def test_flow_user(hass: HomeAssistant, mock_prowlpy: Mock) -> None:
assert result["data"] == {CONF_API_KEY: CONF_INPUT[CONF_API_KEY]}
async def test_flow_duplicate_api_key(hass: HomeAssistant, mock_prowlpy: Mock) -> None:
async def test_flow_duplicate_api_key(
hass: HomeAssistant, mock_prowlpy: AsyncMock
) -> None:
"""Test user initialized flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -52,7 +54,7 @@ async def test_flow_duplicate_api_key(hass: HomeAssistant, mock_prowlpy: Mock) -
assert result["type"] is FlowResultType.ABORT
async def test_flow_user_bad_key(hass: HomeAssistant, mock_prowlpy: Mock) -> None:
async def test_flow_user_bad_key(hass: HomeAssistant, mock_prowlpy: AsyncMock) -> None:
"""Test user submitting a bad API key."""
mock_prowlpy.verify_key.side_effect = prowlpy.APIError("Invalid API key")
@@ -70,7 +72,9 @@ async def test_flow_user_bad_key(hass: HomeAssistant, mock_prowlpy: Mock) -> Non
assert result["errors"] == INVALID_API_KEY_ERROR
async def test_flow_user_prowl_timeout(hass: HomeAssistant, mock_prowlpy: Mock) -> None:
async def test_flow_user_prowl_timeout(
hass: HomeAssistant, mock_prowlpy: AsyncMock
) -> None:
"""Test Prowl API timeout."""
mock_prowlpy.verify_key.side_effect = TimeoutError
@@ -88,7 +92,7 @@ async def test_flow_user_prowl_timeout(hass: HomeAssistant, mock_prowlpy: Mock)
assert result["errors"] == TIMEOUT_ERROR
async def test_flow_api_failure(hass: HomeAssistant, mock_prowlpy: Mock) -> None:
async def test_flow_api_failure(hass: HomeAssistant, mock_prowlpy: AsyncMock) -> None:
"""Test Prowl API failure."""
mock_prowlpy.verify_key.side_effect = prowlpy.APIError(BAD_API_RESPONSE)

View File

@@ -1,6 +1,6 @@
"""Testing the Prowl initialisation."""
from unittest.mock import Mock
from unittest.mock import AsyncMock
import prowlpy
import pytest
@@ -18,7 +18,7 @@ from tests.common import MockConfigEntry
async def test_load_reload_unload_config_entry(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
mock_prowlpy: Mock,
mock_prowlpy: AsyncMock,
) -> None:
"""Test the Prowl configuration entry loading/reloading/unloading."""
mock_prowlpy_config_entry.add_to_hass(hass)
@@ -57,7 +57,7 @@ async def test_load_reload_unload_config_entry(
async def test_config_entry_failures(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
mock_prowlpy: Mock,
mock_prowlpy: AsyncMock,
prowlpy_side_effect,
expected_config_state: ConfigEntryState,
) -> None:

View File

@@ -1,7 +1,7 @@
"""Test the Prowl notifications."""
from typing import Any
from unittest.mock import Mock
from unittest.mock import AsyncMock
import prowlpy
import pytest
@@ -29,7 +29,7 @@ EXPECTED_SEND_PARAMETERS = {
@pytest.mark.usefixtures("configure_prowl_through_yaml")
async def test_send_notification_service(
hass: HomeAssistant,
mock_prowlpy: Mock,
mock_prowlpy: AsyncMock,
) -> None:
"""Set up Prowl, call notify service, and check API call."""
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
@@ -40,12 +40,12 @@ async def test_send_notification_service(
blocking=True,
)
mock_prowlpy.send.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
mock_prowlpy.post.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
async def test_send_notification_entity_service(
hass: HomeAssistant,
mock_prowlpy: Mock,
mock_prowlpy: AsyncMock,
mock_prowlpy_config_entry: MockConfigEntry,
) -> None:
"""Set up Prowl via config entry, call notify service, and check API call."""
@@ -65,7 +65,7 @@ async def test_send_notification_entity_service(
blocking=True,
)
mock_prowlpy.send.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
mock_prowlpy.post.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
@pytest.mark.parametrize(
@@ -102,7 +102,7 @@ async def test_send_notification_entity_service(
)
async def test_fail_send_notification_entity_service(
hass: HomeAssistant,
mock_prowlpy: Mock,
mock_prowlpy: AsyncMock,
mock_prowlpy_config_entry: MockConfigEntry,
prowlpy_side_effect: Exception,
raised_exception: type[Exception],
@@ -113,7 +113,7 @@ async def test_fail_send_notification_entity_service(
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
mock_prowlpy.post.side_effect = prowlpy_side_effect
assert hass.services.has_service(notify.DOMAIN, notify.SERVICE_SEND_MESSAGE)
with pytest.raises(raised_exception, match=exception_message):
@@ -128,7 +128,7 @@ async def test_fail_send_notification_entity_service(
blocking=True,
)
mock_prowlpy.send.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
mock_prowlpy.post.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
@pytest.mark.parametrize(
@@ -166,13 +166,13 @@ async def test_fail_send_notification_entity_service(
@pytest.mark.usefixtures("configure_prowl_through_yaml")
async def test_fail_send_notification(
hass: HomeAssistant,
mock_prowlpy: Mock,
mock_prowlpy: AsyncMock,
prowlpy_side_effect: Exception,
raised_exception: type[Exception],
exception_message: str | None,
) -> None:
"""Sending a message via Prowl with a failure."""
mock_prowlpy.send.side_effect = prowlpy_side_effect
mock_prowlpy.post.side_effect = prowlpy_side_effect
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
with pytest.raises(raised_exception, match=exception_message):
@@ -183,7 +183,7 @@ async def test_fail_send_notification(
blocking=True,
)
mock_prowlpy.send.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
mock_prowlpy.post.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
@pytest.mark.parametrize(
@@ -204,12 +204,12 @@ async def test_fail_send_notification(
@pytest.mark.usefixtures("configure_prowl_through_yaml")
async def test_other_exception_send_notification(
hass: HomeAssistant,
mock_prowlpy: Mock,
mock_prowlpy: AsyncMock,
service_data: dict[str, Any],
expected_send_parameters: dict[str, Any],
) -> None:
"""Sending a message via Prowl with a general unhandled exception."""
mock_prowlpy.send.side_effect = SyntaxError
mock_prowlpy.post.side_effect = SyntaxError
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
with pytest.raises(SyntaxError):
@@ -220,4 +220,4 @@ async def test_other_exception_send_notification(
blocking=True,
)
mock_prowlpy.send.assert_called_once_with(**expected_send_parameters)
mock_prowlpy.post.assert_called_once_with(**expected_send_parameters)