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 @@
"""Tests for the text component."""

View File

@@ -0,0 +1,45 @@
"""Common test helpers for the text entity component tests."""
from typing import Any
from homeassistant.components.text import RestoreText, TextEntity
class MockTextEntity(TextEntity):
"""Mock text class."""
def __init__(
self, native_value="test", native_min=None, native_max=None, pattern=None
) -> None:
"""Initialize mock text entity."""
self._attr_native_value = native_value
if native_min is not None:
self._attr_native_min = native_min
if native_max is not None:
self._attr_native_max = native_max
if pattern is not None:
self._attr_pattern = pattern
def set_value(self, value: str) -> None:
"""Change the selected option."""
self._attr_native_value = value
class MockRestoreText(MockTextEntity, RestoreText):
"""Mock RestoreText class."""
def __init__(self, name: str, **values: Any) -> None:
"""Initialize the MockRestoreText."""
super().__init__(**values)
self._attr_name = name
async def async_added_to_hass(self) -> None:
"""Restore native_*."""
await super().async_added_to_hass()
if (last_text_data := await self.async_get_last_text_data()) is None:
return
self._attr_native_max = last_text_data.native_max
self._attr_native_min = last_text_data.native_min
self._attr_native_value = last_text_data.native_value

View File

@@ -0,0 +1,280 @@
"""The tests for Text device actions."""
import pytest
from pytest_unordered import unordered
import voluptuous_serialize
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.text import DOMAIN, device_action
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
from tests.common import (
MockConfigEntry,
async_get_device_automations,
async_mock_service,
)
@pytest.fixture(autouse=True, name="stub_blueprint_populate")
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
"""Stub copying the blueprints to the config folder."""
async def test_get_actions(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected actions for an 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
)
hass.states.async_set("text.test_5678", 0.5, {"min_value": 0.0, "max_value": 1.0})
expected_actions = [
{
"domain": DOMAIN,
"type": "set_value",
"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"),
[
(RegistryEntryHider.INTEGRATION, None),
(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,
entity_category,
) -> 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 ("set_value",)
]
actions = await async_get_device_automations(
hass, DeviceAutomationType.ACTION, device_entry.id
)
assert actions == unordered(expected_actions)
async def test_get_action_no_state(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected actions for an 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
)
expected_actions = [
{
"domain": DOMAIN,
"type": "set_value",
"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)
async def test_action(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for actions."""
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, 0.5, {"min_value": 0.0, "max_value": 1.0})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "event",
"event_type": "test_event_set_value",
},
"action": {
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "set_value",
"value": 0.3,
},
},
]
},
)
calls = async_mock_service(hass, DOMAIN, "set_value")
assert len(calls) == 0
hass.bus.async_fire("test_event_set_value")
await hass.async_block_till_done()
assert len(calls) == 1
async def test_action_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for actions."""
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, 0.5, {"min_value": 0.0, "max_value": 1.0})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "event",
"event_type": "test_event_set_value",
},
"action": {
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.entity_id,
"type": "set_value",
"value": 0.3,
},
},
]
},
)
calls = async_mock_service(hass, DOMAIN, "set_value")
assert len(calls) == 0
hass.bus.async_fire("test_event_set_value")
await hass.async_block_till_done()
assert len(calls) == 1
async def test_capabilities(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test getting capabilities."""
entry = entity_registry.async_get_or_create(DOMAIN, "test", "5678")
capabilities = await device_action.async_get_action_capabilities(
hass,
{
"domain": DOMAIN,
"device_id": "abcdefgh",
"entity_id": entry.id,
"type": "set_value",
},
)
assert capabilities and "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [{"name": "value", "required": True, "type": "string"}]
async def test_capabilities_legacy(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test getting capabilities."""
entry = entity_registry.async_get_or_create(DOMAIN, "test", "5678")
capabilities = await device_action.async_get_action_capabilities(
hass,
{
"domain": DOMAIN,
"device_id": "abcdefgh",
"entity_id": entry.entity_id,
"type": "set_value",
},
)
assert capabilities and "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [{"name": "value", "required": True, "type": "string"}]

View File

@@ -0,0 +1,176 @@
"""The tests for the text component."""
from typing import Any
import pytest
from homeassistant.components.text import (
ATTR_MAX,
ATTR_MIN,
ATTR_MODE,
ATTR_PATTERN,
ATTR_VALUE,
DOMAIN,
SERVICE_SET_VALUE,
TextMode,
_async_set_value,
)
from homeassistant.const import MAX_LENGTH_STATE_STATE
from homeassistant.core import HomeAssistant, ServiceCall, State
from homeassistant.helpers.restore_state import STORAGE_KEY as RESTORE_STATE_KEY
from homeassistant.setup import async_setup_component
from .common import MockRestoreText, MockTextEntity
from tests.common import (
async_mock_restore_state_shutdown_restart,
mock_restore_cache_with_extra_data,
setup_test_component_platform,
)
async def test_text_default(hass: HomeAssistant) -> None:
"""Test text entity with defaults."""
text = MockTextEntity()
text.hass = hass
assert text.capability_attributes == {
ATTR_MIN: 0,
ATTR_MAX: MAX_LENGTH_STATE_STATE,
ATTR_MODE: TextMode.TEXT,
ATTR_PATTERN: None,
}
assert text.pattern is None
assert text.state == "test"
async def test_text_new_min_max_pattern(hass: HomeAssistant) -> None:
"""Test text entity with new min, max, and pattern."""
text = MockTextEntity(native_min=-1, native_max=500, pattern=r"[a-z]")
text.hass = hass
assert text.capability_attributes == {
ATTR_MIN: 0,
ATTR_MAX: MAX_LENGTH_STATE_STATE,
ATTR_MODE: TextMode.TEXT,
ATTR_PATTERN: r"[a-z]",
}
async def test_text_set_value(hass: HomeAssistant) -> None:
"""Test text entity with set_value service."""
text = MockTextEntity(native_min=1, native_max=5, pattern=r"[a-z]")
text.hass = hass
with pytest.raises(ValueError):
await _async_set_value(
text, ServiceCall(hass, DOMAIN, SERVICE_SET_VALUE, {ATTR_VALUE: ""})
)
with pytest.raises(ValueError):
await _async_set_value(
text,
ServiceCall(hass, DOMAIN, SERVICE_SET_VALUE, {ATTR_VALUE: "hello world!"}),
)
with pytest.raises(ValueError):
await _async_set_value(
text, ServiceCall(hass, DOMAIN, SERVICE_SET_VALUE, {ATTR_VALUE: "HELLO"})
)
await _async_set_value(
text, ServiceCall(hass, DOMAIN, SERVICE_SET_VALUE, {ATTR_VALUE: "test2"})
)
assert text.state == "test2"
async def test_text_value_outside_bounds(hass: HomeAssistant) -> None:
"""Test text entity with value that is outside min and max."""
with pytest.raises(ValueError):
_ = MockTextEntity(
"hello world", native_min=2, native_max=5, pattern=r"[a-z]"
).state
with pytest.raises(ValueError):
_ = MockTextEntity(
"hello world", native_min=15, native_max=20, pattern=r"[a-z]"
).state
RESTORE_DATA = {
"native_max": 5,
"native_min": 1,
# "mode": TextMode.TEXT,
# "pattern": r"[A-Za-z0-9]",
"native_value": "Hello",
}
async def test_restore_number_save_state(
hass: HomeAssistant,
hass_storage: dict[str, Any],
) -> None:
"""Test RestoreNumber."""
entity0 = MockRestoreText(
name="Test",
native_max=5,
native_min=1,
native_value="Hello",
)
setup_test_component_platform(hass, DOMAIN, [entity0])
assert await async_setup_component(hass, "text", {"text": {"platform": "test"}})
await hass.async_block_till_done()
# Trigger saving state
await async_mock_restore_state_shutdown_restart(hass)
assert len(hass_storage[RESTORE_STATE_KEY]["data"]) == 1
state = hass_storage[RESTORE_STATE_KEY]["data"][0]["state"]
assert state["entity_id"] == entity0.entity_id
extra_data = hass_storage[RESTORE_STATE_KEY]["data"][0]["extra_data"]
assert extra_data == RESTORE_DATA
assert isinstance(extra_data["native_value"], str)
@pytest.mark.parametrize(
("native_max", "native_min", "native_value", "native_value_type", "extra_data"),
[
(5, 1, "Hello", str, RESTORE_DATA),
(255, 1, None, type(None), None),
(255, 1, None, type(None), {}),
(255, 1, None, type(None), {"beer": 123}),
(255, 1, None, type(None), {"native_value": {}}),
],
)
async def test_restore_number_restore_state(
hass: HomeAssistant,
hass_storage: dict[str, Any],
native_max,
native_min,
native_value,
native_value_type,
extra_data,
) -> None:
"""Test RestoreNumber."""
mock_restore_cache_with_extra_data(hass, ((State("text.test", ""), extra_data),))
entity0 = MockRestoreText(
native_max=native_max,
native_min=native_min,
name="Test",
native_value=None,
)
setup_test_component_platform(hass, DOMAIN, [entity0])
assert await async_setup_component(hass, "text", {"text": {"platform": "test"}})
await hass.async_block_till_done()
assert hass.states.get(entity0.entity_id)
assert entity0.native_max == native_max
assert entity0.native_min == native_min
assert entity0.mode == TextMode.TEXT
assert entity0.pattern is None
assert entity0.native_value == native_value
assert isinstance(entity0.native_value, native_value_type)

View File

@@ -0,0 +1,51 @@
"""The tests for text recorder."""
from __future__ import annotations
from datetime import timedelta
from unittest.mock import patch
import pytest
from homeassistant.components import text
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.history import get_significant_states
from homeassistant.components.text import ATTR_MAX, ATTR_MIN, ATTR_MODE, ATTR_PATTERN
from homeassistant.const import ATTR_FRIENDLY_NAME, Platform
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.common import async_fire_time_changed
from tests.components.recorder.common import async_wait_recording_done
@pytest.fixture(autouse=True)
async def text_only() -> None:
"""Enable only the text platform."""
with patch(
"homeassistant.components.demo.COMPONENTS_WITH_CONFIG_ENTRY_DEMO_PLATFORM",
[Platform.TEXT],
):
yield
async def test_exclude_attributes(recorder_mock: Recorder, hass: HomeAssistant) -> None:
"""Test siren registered attributes to be excluded."""
now = dt_util.utcnow()
assert await async_setup_component(hass, "homeassistant", {})
await async_setup_component(hass, text.DOMAIN, {text.DOMAIN: {"platform": "demo"}})
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=5))
await hass.async_block_till_done()
await async_wait_recording_done(hass)
states = await hass.async_add_executor_job(
get_significant_states, hass, now, None, hass.states.async_entity_ids()
)
assert len(states) >= 1
for entity_states in states.values():
for state in entity_states:
for attr in (ATTR_MAX, ATTR_MIN, ATTR_MODE, ATTR_PATTERN):
assert attr not in state.attributes
assert ATTR_FRIENDLY_NAME in state.attributes

View File

@@ -0,0 +1,58 @@
"""Test reproduce state for Text entities."""
import pytest
from homeassistant.components.text.const import (
ATTR_MAX,
ATTR_MIN,
ATTR_MODE,
ATTR_PATTERN,
DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers.state import async_reproduce_state
from tests.common import async_mock_service
VALID_TEXT1 = "Hello"
VALID_TEXT2 = "World"
async def test_reproducing_states(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test reproducing Text states."""
hass.states.async_set(
"text.test_text",
VALID_TEXT1,
{ATTR_MIN: 1, ATTR_MAX: 5, ATTR_MODE: "text", ATTR_PATTERN: None},
)
# These calls should do nothing as entities already in desired state
await async_reproduce_state(
hass,
[
State("text.test_text", VALID_TEXT1),
# Should not raise
State("text.non_existing", "234"),
],
)
assert hass.states.get("text.test_text").state == VALID_TEXT1
# Test reproducing with different state
calls = async_mock_service(hass, DOMAIN, SERVICE_SET_VALUE)
await async_reproduce_state(
hass,
[
State("text.test_text", VALID_TEXT2),
# Should not raise
State("text.non_existing", "234"),
],
)
assert len(calls) == 1
assert calls[0].domain == DOMAIN
assert calls[0].data == {"entity_id": "text.test_text", "value": VALID_TEXT2}