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 the Button integration."""

View File

@@ -0,0 +1,51 @@
"""Fixtures for the button entity component tests."""
import logging
import pytest
from homeassistant.components.button import DOMAIN, ButtonEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import TEST_DOMAIN
from tests.common import MockEntity, MockPlatform, mock_platform
_LOGGER = logging.getLogger(__name__)
class MockButtonEntity(MockEntity, ButtonEntity):
"""Mock Button class."""
def press(self) -> None:
"""Press the button."""
_LOGGER.info("The button has been pressed")
@pytest.fixture
async def setup_platform(hass: HomeAssistant) -> None:
"""Set up the button entity platform."""
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up test button platform."""
async_add_entities(
[
MockButtonEntity(
name="button 1",
unique_id="unique_button_1",
),
]
)
mock_platform(
hass,
f"{TEST_DOMAIN}.{DOMAIN}",
MockPlatform(async_setup_platform=async_setup_platform),
)

View File

@@ -0,0 +1,3 @@
"""Constants for the button entity component tests."""
TEST_DOMAIN = "test"

View File

@@ -0,0 +1,190 @@
"""The tests for Button device actions."""
import pytest
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.button import DOMAIN
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import (
MockConfigEntry,
async_get_device_automations,
async_mock_service,
)
async def test_get_actions(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected actions from a button."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
expected_actions = [
{
"domain": DOMAIN,
"type": "press",
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
]
actions = await async_get_device_automations(
hass, DeviceAutomationType.ACTION, device_entry.id
)
assert actions == unordered(expected_actions)
@pytest.mark.parametrize(
("hidden_by", "entity_category"),
[
(er.RegistryEntryHider.INTEGRATION, None),
(er.RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
],
)
async def test_get_actions_hidden_auxiliary(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by: er.RegistryEntryHider | None,
entity_category: EntityCategory | None,
) -> None:
"""Test we get the expected actions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
)
expected_actions = []
expected_actions += [
{
"domain": DOMAIN,
"type": action,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": True},
}
for action in ("press",)
]
actions = await async_get_device_automations(
hass, DeviceAutomationType.ACTION, device_entry.id
)
assert actions == unordered(expected_actions)
async def test_action(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for press action."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "event",
"event_type": "test_event",
},
"action": {
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "press",
},
},
]
},
)
press_calls = async_mock_service(hass, DOMAIN, "press")
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(press_calls) == 1
assert press_calls[0].domain == DOMAIN
assert press_calls[0].service == "press"
assert press_calls[0].data == {"entity_id": entry.entity_id}
async def test_action_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for press action."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "event",
"event_type": "test_event",
},
"action": {
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.entity_id,
"type": "press",
},
},
]
},
)
press_calls = async_mock_service(hass, DOMAIN, "press")
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(press_calls) == 1
assert press_calls[0].domain == DOMAIN
assert press_calls[0].service == "press"
assert press_calls[0].data == {"entity_id": entry.entity_id}

View File

@@ -0,0 +1,215 @@
"""The tests for Button device triggers."""
from __future__ import annotations
import pytest
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.button import DOMAIN
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, async_get_device_automations
async def test_get_triggers(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected triggers from a button."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": "pressed",
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert triggers == unordered(expected_triggers)
@pytest.mark.parametrize(
("hidden_by", "entity_category"),
[
(er.RegistryEntryHider.INTEGRATION, None),
(er.RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
],
)
async def test_get_triggers_hidden_auxiliary(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by: er.RegistryEntryHider | None,
entity_category: EntityCategory | None,
) -> None:
"""Test we get the expected triggers from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": True},
}
for trigger in ("pressed",)
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert triggers == unordered(expected_triggers)
async def test_if_fires_on_state_change(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for turn_on and turn_off triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, "unknown")
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "pressed",
},
"action": {
"service": "test.automation",
"data": {
"some": (
"to - {{ trigger.platform }} "
"- {{ trigger.entity_id }} "
"- {{ trigger.from_state.state }} "
"- {{ trigger.to_state.state }} "
"- {{ trigger.for }} "
"- {{ trigger.id }}"
)
},
},
}
]
},
)
# Test triggering device trigger with a to state
hass.states.async_set(entry.entity_id, "2021-01-01T23:59:59+00:00")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== f"to - device - {entry.entity_id} - unknown - 2021-01-01T23:59:59+00:00 - None - 0"
)
async def test_if_fires_on_state_change_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for turn_on and turn_off triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, "unknown")
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.entity_id,
"type": "pressed",
},
"action": {
"service": "test.automation",
"data": {
"some": (
"to - {{ trigger.platform }} "
"- {{ trigger.entity_id }} "
"- {{ trigger.from_state.state }} "
"- {{ trigger.to_state.state }} "
"- {{ trigger.for }} "
"- {{ trigger.id }}"
)
},
},
}
]
},
)
# Test triggering device trigger with a to state
hass.states.async_set(entry.entity_id, "2021-01-01T23:59:59+00:00")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== f"to - device - {entry.entity_id} - unknown - 2021-01-01T23:59:59+00:00 - None - 0"
)

View File

@@ -0,0 +1,208 @@
"""The tests for the Button component."""
from collections.abc import Generator
from datetime import timedelta
from unittest.mock import MagicMock
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components.button import (
DOMAIN,
SERVICE_PRESS,
ButtonDeviceClass,
ButtonEntity,
ButtonEntityDescription,
)
from homeassistant.config_entries import ConfigEntry, ConfigFlow
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_PLATFORM,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from .const import TEST_DOMAIN
from tests.common import (
MockConfigEntry,
MockModule,
MockPlatform,
mock_config_flow,
mock_integration,
mock_platform,
mock_restore_cache,
)
async def test_button(hass: HomeAssistant) -> None:
"""Test getting data from the mocked button entity."""
button = ButtonEntity()
assert button.state is None
button.hass = hass
with pytest.raises(NotImplementedError):
await button.async_press()
button.press = MagicMock()
await button.async_press()
assert button.press.called
@pytest.mark.usefixtures("enable_custom_integrations", "setup_platform")
async def test_custom_integration(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test we integration."""
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
assert hass.states.get("button.button_1").state == STATE_UNKNOWN
now = dt_util.utcnow()
await hass.services.async_call(
DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.button_1"},
blocking=True,
)
assert hass.states.get("button.button_1").state == now.isoformat()
assert "The button has been pressed" in caplog.text
now_isoformat = dt_util.utcnow().isoformat()
assert hass.states.get("button.button_1").state == now_isoformat
new_time = dt_util.utcnow() + timedelta(weeks=1)
freezer.move_to(new_time)
await hass.services.async_call(
DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.button_1"},
blocking=True,
)
new_time_isoformat = new_time.isoformat()
assert hass.states.get("button.button_1").state == new_time_isoformat
@pytest.mark.usefixtures("enable_custom_integrations", "setup_platform")
async def test_restore_state(hass: HomeAssistant) -> None:
"""Test we restore state integration."""
mock_restore_cache(hass, (State("button.button_1", "2021-01-01T23:59:59+00:00"),))
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
assert hass.states.get("button.button_1").state == "2021-01-01T23:59:59+00:00"
@pytest.mark.usefixtures("enable_custom_integrations", "setup_platform")
async def test_restore_state_does_not_restore_unavailable(hass: HomeAssistant) -> None:
"""Test we restore state integration except for unavailable."""
mock_restore_cache(hass, (State("button.button_1", STATE_UNAVAILABLE),))
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
assert hass.states.get("button.button_1").state == STATE_UNKNOWN
class MockFlow(ConfigFlow):
"""Test flow."""
@pytest.fixture(autouse=True)
def config_flow_fixture(hass: HomeAssistant) -> Generator[None]:
"""Mock config flow."""
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
with mock_config_flow(TEST_DOMAIN, MockFlow):
yield
async def test_name(hass: HomeAssistant) -> None:
"""Test button name."""
async def 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
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
mock_integration(
hass,
MockModule(
TEST_DOMAIN,
async_setup_entry=async_setup_entry_init,
),
)
# Unnamed button without device class -> no name
entity1 = ButtonEntity()
entity1.entity_id = "button.test1"
# Unnamed button with device class but has_entity_name False -> no name
entity2 = ButtonEntity()
entity2.entity_id = "button.test2"
entity2._attr_device_class = ButtonDeviceClass.RESTART
# Unnamed button with device class and has_entity_name True -> named
entity3 = ButtonEntity()
entity3.entity_id = "button.test3"
entity3._attr_device_class = ButtonDeviceClass.RESTART
entity3._attr_has_entity_name = True
# Unnamed button with device class and has_entity_name True -> named
entity4 = ButtonEntity()
entity4.entity_id = "sensor.test4"
entity4.entity_description = ButtonEntityDescription(
"test",
ButtonDeviceClass.RESTART,
has_entity_name=True,
)
async def async_setup_entry_platform(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up test button platform via config entry."""
async_add_entities([entity1, entity2, entity3, entity4])
mock_platform(
hass,
f"{TEST_DOMAIN}.{DOMAIN}",
MockPlatform(async_setup_entry=async_setup_entry_platform),
)
config_entry = MockConfigEntry(domain=TEST_DOMAIN)
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 == {}
state = hass.states.get(entity2.entity_id)
assert state
assert state.attributes == {"device_class": "restart"}
state = hass.states.get(entity3.entity_id)
assert state
assert state.attributes == {"device_class": "restart", "friendly_name": "Restart"}
state = hass.states.get(entity4.entity_id)
assert state
assert state.attributes == {"device_class": "restart", "friendly_name": "Restart"}