init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""The tests for notification platforms."""

View File

@@ -0,0 +1,33 @@
"""Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from typing import Any
from homeassistant.components.notify import (
ATTR_DATA,
ATTR_MESSAGE,
ATTR_TITLE,
DOMAIN,
SERVICE_NOTIFY,
)
from homeassistant.core import HomeAssistant
from homeassistant.loader import bind_hass
@bind_hass
def send_message(
hass: HomeAssistant, message: str, title: str | None = None, data: Any = None
) -> None:
"""Send a notification message."""
info = {ATTR_MESSAGE: message}
if title is not None:
info[ATTR_TITLE] = title
if data is not None:
info[ATTR_DATA] = data
hass.services.call(DOMAIN, SERVICE_NOTIFY, info)

View File

@@ -0,0 +1,23 @@
"""Fixtures for Notify platform tests."""
from collections.abc import Generator
import pytest
from homeassistant.config_entries import ConfigFlow
from homeassistant.core import HomeAssistant
from tests.common import mock_config_flow, mock_platform
class MockFlow(ConfigFlow):
"""Test flow."""
@pytest.fixture
def config_flow_fixture(hass: HomeAssistant) -> Generator[None]:
"""Mock config flow."""
mock_platform(hass, "test.config_flow")
with mock_config_flow("test", MockFlow):
yield

View File

@@ -0,0 +1,267 @@
"""The tests for notify entity platform."""
import copy
from unittest.mock import MagicMock
import pytest
import voluptuous as vol
from homeassistant.components import notify
from homeassistant.components.notify import (
DOMAIN,
SERVICE_SEND_MESSAGE,
NotifyEntity,
NotifyEntityDescription,
NotifyEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant, State
from tests.common import (
MockConfigEntry,
MockEntity,
MockModule,
mock_integration,
mock_platform,
mock_restore_cache,
setup_test_component_platform,
)
TEST_KWARGS = {notify.ATTR_MESSAGE: "Test message"}
TEST_KWARGS_TITLE = {notify.ATTR_MESSAGE: "Test message", notify.ATTR_TITLE: "My title"}
class MockNotifyEntity(MockEntity, NotifyEntity):
"""Mock Email notitier entity to use in tests."""
send_message_mock_calls = MagicMock()
async def async_send_message(self, message: str, title: str | None = None) -> None:
"""Send a notification message."""
self.send_message_mock_calls(message, title=title)
class MockNotifyEntityNonAsync(MockEntity, NotifyEntity):
"""Mock Email notitier entity to use in tests."""
send_message_mock_calls = MagicMock()
def send_message(self, message: str, title: str | None = None) -> None:
"""Send a notification message."""
self.send_message_mock_calls(message, title=title)
async def help_async_setup_entry_init(
hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Set up test config entry."""
await hass.config_entries.async_forward_entry_setups(config_entry, [DOMAIN])
return True
async def help_async_unload_entry(
hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Unload test config emntry."""
return await hass.config_entries.async_unload_platforms(
config_entry, [Platform.NOTIFY]
)
@pytest.mark.parametrize(
"entity",
[
MockNotifyEntityNonAsync(name="test", entity_id="notify.test"),
MockNotifyEntity(name="test", entity_id="notify.test"),
],
ids=["non_async", "async"],
)
async def test_send_message_service(
hass: HomeAssistant, config_flow_fixture: None, entity: NotifyEntity
) -> None:
"""Test send_message service."""
config_entry = MockConfigEntry(domain="test")
config_entry.add_to_hass(hass)
mock_integration(
hass,
MockModule(
"test",
async_setup_entry=help_async_setup_entry_init,
async_unload_entry=help_async_unload_entry,
),
)
setup_test_component_platform(hass, DOMAIN, [entity], from_config_entry=True)
assert await hass.config_entries.async_setup(config_entry.entry_id)
state = hass.states.get("notify.test")
assert state.state is STATE_UNKNOWN
await hass.services.async_call(
DOMAIN,
SERVICE_SEND_MESSAGE,
copy.deepcopy(TEST_KWARGS) | {"entity_id": "notify.test"},
blocking=True,
)
await hass.async_block_till_done()
entity.send_message_mock_calls.assert_called_once()
entity.send_message_mock_calls.reset_mock()
# Test schema: `None` message fails
with pytest.raises(vol.Invalid) as exc:
await hass.services.async_call(
notify.DOMAIN,
notify.SERVICE_SEND_MESSAGE,
{"entity_id": "notify.test", notify.ATTR_MESSAGE: None},
)
assert (
str(exc.value) == "string value is None for dictionary value @ data['message']"
)
entity.send_message_mock_calls.assert_not_called()
# Test schema: No message fails
with pytest.raises(vol.Invalid) as exc:
await hass.services.async_call(
notify.DOMAIN, notify.SERVICE_SEND_MESSAGE, {"entity_id": "notify.test"}
)
assert str(exc.value) == "required key not provided @ data['message']"
entity.send_message_mock_calls.assert_not_called()
# Test unloading the entry succeeds
assert await hass.config_entries.async_unload(config_entry.entry_id)
@pytest.mark.parametrize(
"entity",
[
MockNotifyEntityNonAsync(
name="test",
entity_id="notify.test",
supported_features=NotifyEntityFeature.TITLE,
),
MockNotifyEntity(
name="test",
entity_id="notify.test",
supported_features=NotifyEntityFeature.TITLE,
),
],
ids=["non_async", "async"],
)
async def test_send_message_service_with_title(
hass: HomeAssistant, config_flow_fixture: None, entity: NotifyEntity
) -> None:
"""Test send_message service."""
config_entry = MockConfigEntry(domain="test")
config_entry.add_to_hass(hass)
mock_integration(
hass,
MockModule(
"test",
async_setup_entry=help_async_setup_entry_init,
async_unload_entry=help_async_unload_entry,
),
)
setup_test_component_platform(hass, DOMAIN, [entity], from_config_entry=True)
assert await hass.config_entries.async_setup(config_entry.entry_id)
state = hass.states.get("notify.test")
assert state.state is STATE_UNKNOWN
await hass.services.async_call(
DOMAIN,
SERVICE_SEND_MESSAGE,
copy.deepcopy(TEST_KWARGS_TITLE) | {"entity_id": "notify.test"},
blocking=True,
)
await hass.async_block_till_done()
entity.send_message_mock_calls.assert_called_once_with(
TEST_KWARGS_TITLE[notify.ATTR_MESSAGE],
title=TEST_KWARGS_TITLE[notify.ATTR_TITLE],
)
@pytest.mark.parametrize(
("state", "init_state"),
[
("2021-01-01T23:59:59+00:00", "2021-01-01T23:59:59+00:00"),
(STATE_UNAVAILABLE, STATE_UNKNOWN),
],
)
async def test_restore_state(
hass: HomeAssistant, config_flow_fixture: None, state: str, init_state: str
) -> None:
"""Test we restore state integration."""
mock_restore_cache(hass, (State("notify.test", state),))
mock_integration(
hass,
MockModule(
"test",
async_setup_entry=help_async_setup_entry_init,
),
)
entity = MockNotifyEntity(name="test", entity_id="notify.test")
setup_test_component_platform(hass, DOMAIN, [entity], from_config_entry=True)
config_entry = MockConfigEntry(domain="test")
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
state = hass.states.get("notify.test")
assert state is not None
assert state.state is init_state
async def test_name(hass: HomeAssistant, config_flow_fixture: None) -> None:
"""Test notify name."""
mock_platform(hass, "test.config_flow")
mock_integration(
hass,
MockModule(
"test",
async_setup_entry=help_async_setup_entry_init,
),
)
# Unnamed notify entity -> no name
entity1 = NotifyEntity()
entity1.entity_id = "notify.test1"
# Unnamed notify entity and has_entity_name True -> unnamed
entity2 = NotifyEntity()
entity2.entity_id = "notify.test3"
entity2._attr_has_entity_name = True
# Named notify entity and has_entity_name True -> named
entity3 = NotifyEntity()
entity3.entity_id = "notify.test4"
entity3.entity_description = NotifyEntityDescription("test", has_entity_name=True)
setup_test_component_platform(
hass, DOMAIN, [entity1, entity2, entity3], from_config_entry=True
)
config_entry = MockConfigEntry(domain="test")
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(entity1.entity_id)
assert state
assert state.attributes == {"supported_features": NotifyEntityFeature(0)}
state = hass.states.get(entity2.entity_id)
assert state
assert state.attributes == {"supported_features": NotifyEntityFeature(0)}
state = hass.states.get(entity3.entity_id)
assert state
assert state.attributes == {"supported_features": NotifyEntityFeature(0)}

View File

@@ -0,0 +1,632 @@
"""The tests for legacy notify services."""
import asyncio
from collections.abc import Callable, Coroutine, Mapping
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock, Mock, patch
import pytest
import voluptuous as vol
import yaml
from homeassistant import config as hass_config
from homeassistant.components import notify
from homeassistant.const import SERVICE_RELOAD, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.discovery import async_load_platform
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.setup import async_setup_component
from tests.common import MockPlatform, mock_platform
class NotificationService(notify.BaseNotificationService):
"""A test class for legacy notification services."""
def __init__(
self,
hass: HomeAssistant,
target_list: dict[str, Any] | None = None,
name="notify",
) -> None:
"""Initialize the service."""
async def _async_make_reloadable(hass: HomeAssistant) -> None:
"""Initialize the reload service."""
await async_setup_reload_service(hass, name, [notify.DOMAIN])
self.hass = hass
self.target_list = target_list or {"a": 1, "b": 2}
hass.async_create_task(_async_make_reloadable(hass))
@property
def targets(self):
"""Return a dictionary of devices."""
return self.target_list
class MockNotifyPlatform(MockPlatform):
"""Help to set up a legacy test notify service."""
def __init__(self, async_get_service: Any = None, get_service: Any = None) -> None:
"""Return a legacy notify service."""
super().__init__()
if get_service:
self.get_service = get_service
if async_get_service:
self.async_get_service = async_get_service
def mock_notify_platform(
hass: HomeAssistant,
tmp_path: Path,
integration: str = "notify",
async_get_service: Callable[
[HomeAssistant, ConfigType, DiscoveryInfoType | None],
Coroutine[Any, Any, notify.BaseNotificationService],
]
| None = None,
get_service: Callable[
[HomeAssistant, ConfigType, DiscoveryInfoType | None],
notify.BaseNotificationService,
]
| None = None,
):
"""Specialize the mock platform for legacy notify service."""
loaded_platform = MockNotifyPlatform(async_get_service, get_service)
mock_platform(hass, f"{integration}.notify", loaded_platform)
return loaded_platform
async def help_setup_notify(
hass: HomeAssistant, tmp_path: Path, targets: dict[str, None] | None = None
) -> MagicMock:
"""Help set up a platform notify service."""
send_message_mock = MagicMock()
class _TestNotifyService(notify.BaseNotificationService):
def __init__(self, targets: dict[str, None] | None) -> None:
"""Initialize service."""
self._targets = targets
super().__init__()
@property
def targets(self) -> Mapping[str, Any] | None:
"""Return a dictionary of registered targets."""
return self._targets
def send_message(self, message: str, **kwargs: Any) -> None:
"""Send a message."""
send_message_mock(message, kwargs)
async def async_get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> notify.BaseNotificationService:
"""Get notify service for mocked platform."""
return _TestNotifyService(targets)
# Mock platform with service
mock_notify_platform(hass, tmp_path, "test", async_get_service=async_get_service)
# Setup the platform
await async_setup_component(hass, "notify", {"notify": [{"platform": "test"}]})
await hass.async_block_till_done()
# Return mock for assertion service calls
return send_message_mock
async def test_same_targets(hass: HomeAssistant) -> None:
"""Test not changing the targets in a legacy notify service."""
test = NotificationService(hass)
await test.async_setup(hass, "notify", "test")
await test.async_register_services()
await hass.async_block_till_done()
assert hasattr(test, "registered_targets")
assert test.registered_targets == {"test_a": 1, "test_b": 2}
await test.async_register_services()
await hass.async_block_till_done()
assert test.registered_targets == {"test_a": 1, "test_b": 2}
async def test_change_targets(hass: HomeAssistant) -> None:
"""Test changing the targets in a legacy notify service."""
test = NotificationService(hass)
await test.async_setup(hass, "notify", "test")
await test.async_register_services()
await hass.async_block_till_done()
assert hasattr(test, "registered_targets")
assert test.registered_targets == {"test_a": 1, "test_b": 2}
test.target_list = {"a": 0}
await test.async_register_services()
await hass.async_block_till_done()
assert test.target_list == {"a": 0}
assert test.registered_targets == {"test_a": 0}
async def test_add_targets(hass: HomeAssistant) -> None:
"""Test adding the targets in a legacy notify service."""
test = NotificationService(hass)
await test.async_setup(hass, "notify", "test")
await test.async_register_services()
await hass.async_block_till_done()
assert hasattr(test, "registered_targets")
assert test.registered_targets == {"test_a": 1, "test_b": 2}
test.target_list = {"a": 1, "b": 2, "c": 3}
await test.async_register_services()
await hass.async_block_till_done()
assert test.target_list == {"a": 1, "b": 2, "c": 3}
assert test.registered_targets == {"test_a": 1, "test_b": 2, "test_c": 3}
async def test_remove_targets(hass: HomeAssistant) -> None:
"""Test removing targets from the targets in a legacy notify service."""
test = NotificationService(hass)
await test.async_setup(hass, "notify", "test")
await test.async_register_services()
await hass.async_block_till_done()
assert hasattr(test, "registered_targets")
assert test.registered_targets == {"test_a": 1, "test_b": 2}
test.target_list = {"c": 1}
await test.async_register_services()
await hass.async_block_till_done()
assert test.target_list == {"c": 1}
assert test.registered_targets == {"test_c": 1}
async def test_invalid_platform(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
"""Test service setup with an invalid platform."""
mock_notify_platform(hass, tmp_path, "testnotify1")
# Setup the platform
await async_setup_component(
hass, "notify", {"notify": [{"platform": "testnotify1"}]}
)
await hass.async_block_till_done()
assert "Invalid notify platform" in caplog.text
caplog.clear()
# Setup the second testnotify2 platform dynamically
mock_notify_platform(hass, tmp_path, "testnotify2")
await async_load_platform(
hass,
"notify",
"testnotify2",
{},
hass_config={"notify": [{"platform": "testnotify2"}]},
)
await hass.async_block_till_done()
assert "Invalid notify platform" in caplog.text
async def test_invalid_service(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
"""Test service setup with an invalid service object or platform."""
def get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> notify.BaseNotificationService | None:
"""Return None for an invalid notify service."""
return None
mock_notify_platform(hass, tmp_path, "testnotify", get_service=get_service)
# Setup the second testnotify2 platform dynamically
await async_load_platform(
hass,
"notify",
"testnotify",
{},
hass_config={"notify": [{"platform": "testnotify"}]},
)
await hass.async_block_till_done()
assert "Failed to initialize notification service testnotify" in caplog.text
caplog.clear()
await async_load_platform(
hass,
"notify",
"testnotifyinvalid",
{"notify": [{"platform": "testnotifyinvalid"}]},
hass_config={"notify": [{"platform": "testnotifyinvalid"}]},
)
await hass.async_block_till_done()
assert "Unknown notification service specified" in caplog.text
async def test_platform_setup_with_error(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
"""Test service setup with an invalid setup."""
async def async_get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> notify.BaseNotificationService | None:
"""Return None for an invalid notify service."""
raise Exception("Setup error") # noqa: TRY002
mock_notify_platform(
hass, tmp_path, "testnotify", async_get_service=async_get_service
)
# Setup the second testnotify2 platform dynamically
await async_load_platform(
hass,
"notify",
"testnotify",
{},
hass_config={"notify": [{"platform": "testnotify"}]},
)
await hass.async_block_till_done()
assert "Error setting up platform testnotify" in caplog.text
async def test_reload_with_notify_builtin_platform_reload(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test reload using the legacy notify platform reload method."""
async def async_get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> NotificationService:
"""Get notify service for mocked platform."""
targetlist = {"a": 1, "b": 2}
return NotificationService(hass, targetlist, "testnotify")
# platform with service
mock_notify_platform(
hass, tmp_path, "testnotify", async_get_service=async_get_service
)
# Perform a reload using the notify module for testnotify (without services)
await notify.async_reload(hass, "testnotify")
# Setup the platform
await async_setup_component(
hass, "notify", {"notify": [{"platform": "testnotify"}]}
)
await hass.async_block_till_done()
assert hass.services.has_service(notify.DOMAIN, "testnotify_a")
assert hass.services.has_service(notify.DOMAIN, "testnotify_b")
# Perform a reload using the notify module for testnotify (with services)
await notify.async_reload(hass, "testnotify")
assert hass.services.has_service(notify.DOMAIN, "testnotify_a")
assert hass.services.has_service(notify.DOMAIN, "testnotify_b")
async def test_setup_platform_and_reload(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test service setup and reload."""
get_service_called = Mock()
async def async_get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> NotificationService:
"""Get notify service for mocked platform."""
get_service_called(config, discovery_info)
targetlist = {"a": 1, "b": 2}
return NotificationService(hass, targetlist, "testnotify")
async def async_get_service2(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> NotificationService:
"""Get legacy notify service for mocked platform."""
get_service_called(config, discovery_info)
targetlist = {"c": 3, "d": 4}
return NotificationService(hass, targetlist, "testnotify2")
# Mock first platform
mock_notify_platform(
hass, tmp_path, "testnotify", async_get_service=async_get_service
)
# Initialize a second platform testnotify2
mock_notify_platform(
hass, tmp_path, "testnotify2", async_get_service=async_get_service2
)
# Setup the testnotify platform
await async_setup_component(
hass, "notify", {"notify": [{"platform": "testnotify"}]}
)
await hass.async_block_till_done()
assert hass.services.has_service("testnotify", SERVICE_RELOAD)
assert hass.services.has_service(notify.DOMAIN, "testnotify_a")
assert hass.services.has_service(notify.DOMAIN, "testnotify_b")
assert get_service_called.call_count == 1
assert get_service_called.call_args[0][0] == {"platform": "testnotify"}
assert get_service_called.call_args[0][1] is None
get_service_called.reset_mock()
# Setup the second testnotify2 platform dynamically
await async_load_platform(
hass,
"notify",
"testnotify2",
{},
hass_config={"notify": [{"platform": "testnotify"}]},
)
await hass.async_block_till_done()
assert hass.services.has_service("testnotify2", SERVICE_RELOAD)
assert hass.services.has_service(notify.DOMAIN, "testnotify2_c")
assert hass.services.has_service(notify.DOMAIN, "testnotify2_d")
assert get_service_called.call_count == 1
assert get_service_called.call_args[0][0] == {}
assert get_service_called.call_args[0][1] == {}
get_service_called.reset_mock()
# Perform a reload
new_yaml_config_file = tmp_path / "configuration.yaml"
new_yaml_config = yaml.dump({"notify": [{"platform": "testnotify"}]})
new_yaml_config_file.write_text(new_yaml_config)
with patch.object(hass_config, "YAML_CONFIG_FILE", new_yaml_config_file):
await hass.services.async_call(
"testnotify",
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.services.async_call(
"testnotify2",
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
# Check if the notify services from setup still exist
assert hass.services.has_service(notify.DOMAIN, "testnotify_a")
assert hass.services.has_service(notify.DOMAIN, "testnotify_b")
assert get_service_called.call_count == 1
assert get_service_called.call_args[0][0] == {"platform": "testnotify"}
assert get_service_called.call_args[0][1] is None
# Check if the dynamically notify services from setup were removed
assert not hass.services.has_service(notify.DOMAIN, "testnotify2_c")
assert not hass.services.has_service(notify.DOMAIN, "testnotify2_d")
async def test_setup_platform_before_notify_setup(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test trying to setup a platform before legacy notify service is setup."""
get_service_called = Mock()
async def async_get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> NotificationService:
"""Get notify service for mocked platform."""
get_service_called(config, discovery_info)
targetlist = {"a": 1, "b": 2}
return NotificationService(hass, targetlist, "testnotify")
async def async_get_service2(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> NotificationService:
"""Get notify service for mocked platform."""
get_service_called(config, discovery_info)
targetlist = {"c": 3, "d": 4}
return NotificationService(hass, targetlist, "testnotify2")
# Mock first platform
mock_notify_platform(
hass, tmp_path, "testnotify", async_get_service=async_get_service
)
# Initialize a second platform testnotify2
mock_notify_platform(
hass, tmp_path, "testnotify2", async_get_service=async_get_service2
)
hass_config = {"notify": [{"platform": "testnotify"}]}
# Setup the second testnotify2 platform from discovery
load_coro = async_load_platform(
hass, Platform.NOTIFY, "testnotify2", {}, hass_config=hass_config
)
# Setup the testnotify platform
setup_coro = async_setup_component(hass, "notify", hass_config)
load_task = asyncio.create_task(load_coro)
setup_task = asyncio.create_task(setup_coro)
await asyncio.gather(load_task, setup_task)
await hass.async_block_till_done()
assert hass.services.has_service(notify.DOMAIN, "testnotify_a")
assert hass.services.has_service(notify.DOMAIN, "testnotify_b")
assert hass.services.has_service(notify.DOMAIN, "testnotify2_c")
assert hass.services.has_service(notify.DOMAIN, "testnotify2_d")
async def test_setup_platform_after_notify_setup(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test trying to setup a platform after legacy notify service is set up."""
get_service_called = Mock()
async def async_get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> NotificationService:
"""Get notify service for mocked platform."""
get_service_called(config, discovery_info)
targetlist = {"a": 1, "b": 2}
return NotificationService(hass, targetlist, "testnotify")
async def async_get_service2(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> NotificationService:
"""Get notify service for mocked platform."""
get_service_called(config, discovery_info)
targetlist = {"c": 3, "d": 4}
return NotificationService(hass, targetlist, "testnotify2")
# Mock first platform
mock_notify_platform(
hass, tmp_path, "testnotify", async_get_service=async_get_service
)
# Initialize a second platform testnotify2
mock_notify_platform(
hass, tmp_path, "testnotify2", async_get_service=async_get_service2
)
hass_config = {"notify": [{"platform": "testnotify"}]}
# Setup the second testnotify2 platform from discovery
load_coro = async_load_platform(
hass, Platform.NOTIFY, "testnotify2", {}, hass_config=hass_config
)
# Setup the testnotify platform
setup_coro = async_setup_component(hass, "notify", hass_config)
setup_task = asyncio.create_task(setup_coro)
load_task = asyncio.create_task(load_coro)
await asyncio.gather(load_task, setup_task)
await hass.async_block_till_done()
assert hass.services.has_service(notify.DOMAIN, "testnotify_a")
assert hass.services.has_service(notify.DOMAIN, "testnotify_b")
assert hass.services.has_service(notify.DOMAIN, "testnotify2_c")
assert hass.services.has_service(notify.DOMAIN, "testnotify2_d")
async def test_sending_none_message(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test send with None as message."""
send_message_mock = await help_setup_notify(hass, tmp_path)
with pytest.raises(vol.Invalid) as exc:
await hass.services.async_call(
notify.DOMAIN, notify.SERVICE_NOTIFY, {notify.ATTR_MESSAGE: None}
)
assert (
str(exc.value) == "string value is None for dictionary value @ data['message']"
)
send_message_mock.assert_not_called()
async def test_method_forwards_correct_data(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test that all data from the service gets forwarded to service."""
send_message_mock = await help_setup_notify(hass, tmp_path)
data = {
notify.ATTR_MESSAGE: "my message",
notify.ATTR_TITLE: "my title",
notify.ATTR_DATA: {"hello": "world"},
}
await hass.services.async_call(notify.DOMAIN, notify.SERVICE_NOTIFY, data)
await hass.async_block_till_done()
send_message_mock.assert_called_once_with(
"my message", {"title": "my title", "data": {"hello": "world"}}
)
async def test_calling_notify_from_script_loaded_from_yaml_without_title(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test if we can call a notify from a script."""
send_message_mock = await help_setup_notify(hass, tmp_path)
step = {
"service": "notify.notify",
"data": {
"data": {"push": {"sound": "US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav"}}
},
"data_template": {"message": "Test 123 {{ 2 + 2 }}\n"},
}
await async_setup_component(
hass, "script", {"script": {"test": {"sequence": step}}}
)
await hass.services.async_call("script", "test")
await hass.async_block_till_done()
send_message_mock.assert_called_once_with(
"Test 123 4",
{"data": {"push": {"sound": "US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav"}}},
)
async def test_calling_notify_from_script_loaded_from_yaml_with_title(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test if we can call a notify from a script."""
send_message_mock = await help_setup_notify(hass, tmp_path)
step = {
"service": "notify.notify",
"data": {
"data": {"push": {"sound": "US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav"}}
},
"data_template": {"message": "Test 123 {{ 2 + 2 }}\n", "title": "Test"},
}
await async_setup_component(
hass, "script", {"script": {"test": {"sequence": step}}}
)
await hass.services.async_call("script", "test")
await hass.async_block_till_done()
send_message_mock.assert_called_once_with(
"Test 123 4",
{
"title": "Test",
"data": {
"push": {"sound": "US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav"}
},
},
)
async def test_targets_are_services(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test that all targets are exposed as individual services."""
await help_setup_notify(hass, tmp_path, targets={"a": 1, "b": 2})
assert hass.services.has_service("notify", "notify") is not None
assert hass.services.has_service("notify", "test_a") is not None
assert hass.services.has_service("notify", "test_b") is not None
async def test_messages_to_targets_route(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test message routing to specific target services."""
send_message_mock = await help_setup_notify(
hass, tmp_path, targets={"target_name": "test target id"}
)
await hass.services.async_call(
"notify",
"test_target_name",
{"message": "my message", "title": "my title", "data": {"hello": "world"}},
)
await hass.async_block_till_done()
send_message_mock.assert_called_once_with(
"my message",
{"target": ["test target id"], "title": "my title", "data": {"hello": "world"}},
)

View File

@@ -0,0 +1,67 @@
"""The tests for the notify.persistent_notification service."""
from homeassistant.components import notify
from homeassistant.components.persistent_notification import DOMAIN as PN_DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import async_get_persistent_notifications
async def test_async_send_message(hass: HomeAssistant) -> None:
"""Test sending a message to notify.persistent_notification service."""
await async_setup_component(hass, PN_DOMAIN, {"core": {}})
await async_setup_component(hass, notify.DOMAIN, {})
await hass.async_block_till_done()
message = {"message": "Hello", "title": "Test notification"}
await hass.services.async_call(
notify.DOMAIN, notify.SERVICE_PERSISTENT_NOTIFICATION, message
)
await hass.async_block_till_done()
notifications = async_get_persistent_notifications(hass)
assert len(notifications) == 1
notification = notifications[list(notifications)[0]]
assert notification["message"] == "Hello"
assert notification["title"] == "Test notification"
async def test_async_supports_notification_id(hass: HomeAssistant) -> None:
"""Test that notify.persistent_notification supports notification_id."""
await async_setup_component(hass, PN_DOMAIN, {"core": {}})
await async_setup_component(hass, notify.DOMAIN, {})
await hass.async_block_till_done()
message = {
"message": "Hello",
"title": "Test notification",
"data": {"notification_id": "my_id"},
}
await hass.services.async_call(
notify.DOMAIN, notify.SERVICE_PERSISTENT_NOTIFICATION, message
)
await hass.async_block_till_done()
notifications = async_get_persistent_notifications(hass)
assert len(notifications) == 1
# Send second message with same ID
message = {
"message": "Goodbye",
"title": "Notification was updated",
"data": {"notification_id": "my_id"},
}
await hass.services.async_call(
notify.DOMAIN, notify.SERVICE_PERSISTENT_NOTIFICATION, message
)
await hass.async_block_till_done()
notifications = async_get_persistent_notifications(hass)
assert len(notifications) == 1
notification = notifications[list(notifications)[0]]
assert notification["message"] == "Goodbye"
assert notification["title"] == "Notification was updated"

View File

@@ -0,0 +1,81 @@
"""Test repairs for notify entity component."""
from unittest.mock import AsyncMock
import pytest
from homeassistant.components.notify import (
DOMAIN as NOTIFY_DOMAIN,
migrate_notify_issue,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry as ir
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, MockModule, mock_integration
from tests.components.repairs import (
async_process_repairs_platforms,
process_repair_fix_flow,
start_repair_fix_flow,
)
from tests.typing import ClientSessionGenerator
THERMOSTAT_ID = 0
@pytest.mark.usefixtures("config_flow_fixture")
@pytest.mark.parametrize(
("service_name", "translation_key"),
[(None, "migrate_notify_test"), ("bla", "migrate_notify_test_bla")],
)
async def test_notify_migration_repair_flow(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
issue_registry: ir.IssueRegistry,
service_name: str | None,
translation_key: str,
) -> None:
"""Test the notify service repair flow is triggered."""
await async_setup_component(hass, NOTIFY_DOMAIN, {})
await hass.async_block_till_done()
await async_process_repairs_platforms(hass)
http_client = await hass_client()
await hass.async_block_till_done()
config_entry = MockConfigEntry(domain="test")
config_entry.add_to_hass(hass)
mock_integration(
hass,
MockModule(
"test",
async_setup_entry=AsyncMock(return_value=True),
),
)
assert await hass.config_entries.async_setup(config_entry.entry_id)
# Simulate legacy service being used and issue being registered
migrate_notify_issue(hass, "test", "Test", "2024.12.0", service_name=service_name)
await hass.async_block_till_done()
# Assert the issue is present
assert issue_registry.async_get_issue(
domain=NOTIFY_DOMAIN,
issue_id=translation_key,
)
assert len(issue_registry.issues) == 1
data = await start_repair_fix_flow(http_client, NOTIFY_DOMAIN, translation_key)
flow_id = data["flow_id"]
assert data["step_id"] == "confirm"
data = await process_repair_fix_flow(http_client, flow_id)
assert data["type"] == "create_entry"
# Test confirm step in repair flow
await hass.async_block_till_done()
# Assert the issue is no longer present
assert not issue_registry.async_get_issue(
domain=NOTIFY_DOMAIN,
issue_id=translation_key,
)
assert len(issue_registry.issues) == 0