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 template component."""

View File

@@ -0,0 +1,43 @@
"""template conftest."""
import pytest
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers.typing import ConfigType
from homeassistant.setup import async_setup_component
from tests.common import assert_setup_component, async_mock_service
@pytest.fixture
def calls(hass: HomeAssistant) -> list[ServiceCall]:
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
@pytest.fixture
async def start_ha(
hass: HomeAssistant, count: int, domain: str, config: ConfigType
) -> None:
"""Do setup of integration."""
with assert_setup_component(count, domain):
assert await async_setup_component(
hass,
domain,
config,
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
@pytest.fixture
async def caplog_setup_text(caplog: pytest.LogCaptureFixture) -> str:
"""Return setup log of integration."""
return caplog.text
@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."""

View File

@@ -0,0 +1,17 @@
sensor:
- platform: template
broken:
- platform: template
sensors:
combined_sensor_energy_usage:
friendly_name: Combined Sense Energy Usage
unit_of_measurement: kW
value_template:
"{{ ((states('sensor.energy_usage') | float(default=0)) + (states('sensor.energy_usage_2')
| float(default=0))) / 1000 }}"
watching_tv_in_master_bedroom:
friendly_name: Watching TV in Master Bedroom
value_template:
'{% if state_attr("remote.alexander_master_bedroom","current_activity")
== "Watch TV" or state_attr("remote.alexander_master_bedroom","current_activity")
== "Watch Apple TV" %}on{% else %}off{% endif %}'

View File

@@ -0,0 +1,9 @@
sensor:
- platform: template
sensors:
test1:
value_template: "{{ (states.sensor.test2.state |int) + (states.sensor.test3.state |int)}}"
test2:
value_template: "{{ 1 }}"
test3:
value_template: "{{ 2 }}"

View File

@@ -0,0 +1,32 @@
sensor:
- platform: snmp
name: UPS kW
unit_of_measurement: kW
baseoid: 1.3.6.1.4.1.3808.1.1.1.4.2.5.0
host: 192.168.210.25
community: public
accept_errors: true
value_template: "{{ ((value | int) / 1000) | float | round(3) }}"
scan_interval: 900
- platform: template
sensors:
combined_sensor_energy_usage:
friendly_name: Combined Sense Energy Usage
unit_of_measurement: kW
value_template:
"{{ ((states('sensor.energy_usage') | float(default=0)) + (states('sensor.energy_usage_2')
| float(default=0))) / 1000 }}"
watching_tv_in_master_bedroom:
friendly_name: Watching TV in Master Bedroom
value_template:
'{% if state_attr("remote.alexander_master_bedroom","current_activity")
== "Watch TV" or state_attr("remote.alexander_master_bedroom","current_activity")
== "Watch Apple TV" %}on{% else %}off{% endif %}'
template:
trigger:
platform: event
event_type: event_2
sensor:
name: top level 2
state: "{{ trigger.event.data.source }}"

View File

@@ -0,0 +1,18 @@
# serializer version: 1
# name: test_setup_config_entry
StateSnapshot({
'attributes': ReadOnlyDict({
'changed_by': None,
'code_arm_required': True,
'code_format': <CodeFormat.NUMBER: 'number'>,
'friendly_name': 'My template',
'supported_features': <AlarmControlPanelEntityFeature: 0>,
}),
'context': <ANY>,
'entity_id': 'alarm_control_panel.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'armed_away',
})
# ---

View File

@@ -0,0 +1,28 @@
# serializer version: 1
# name: test_setup_config_entry[config_entry_extra_options0]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'My template',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_setup_config_entry[config_entry_extra_options1]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'battery',
'friendly_name': 'My template',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---

View File

@@ -0,0 +1,28 @@
# serializer version: 1
# name: test_setup_config_entry[config_entry_extra_options0]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'My template',
}),
'context': <ANY>,
'entity_id': 'button.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_setup_config_entry[config_entry_extra_options1]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'update',
'friendly_name': 'My template',
}),
'context': <ANY>,
'entity_id': 'button.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---

View File

@@ -0,0 +1,18 @@
# serializer version: 1
# name: test_setup_config_entry
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'My template',
'max': 100.0,
'min': 0.0,
'mode': <NumberMode.AUTO: 'auto'>,
'step': 0.1,
}),
'context': <ANY>,
'entity_id': 'number.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '10.0',
})
# ---

View File

@@ -0,0 +1,19 @@
# serializer version: 1
# name: test_setup_config_entry
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'My template',
'options': Wrapper([
'off',
'on',
'auto',
]),
}),
'context': <ANY>,
'entity_id': 'select.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---

View File

@@ -0,0 +1,30 @@
# serializer version: 1
# name: test_setup_config_entry[config_entry_extra_options0]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'My template',
}),
'context': <ANY>,
'entity_id': 'sensor.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '30.0',
})
# ---
# name: test_setup_config_entry[config_entry_extra_options1]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'battery',
'friendly_name': 'My template',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': '%',
}),
'context': <ANY>,
'entity_id': 'sensor.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '30.0',
})
# ---

View File

@@ -0,0 +1,14 @@
# serializer version: 1
# name: test_setup_config_entry
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'My template',
}),
'context': <ANY>,
'entity_id': 'switch.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---

View File

@@ -0,0 +1,100 @@
# serializer version: 1
# name: test_forecasts[config0-1-weather-get_forecasts]
dict({
'weather.forecast': dict({
'forecast': list([
]),
}),
})
# ---
# name: test_forecasts[config0-1-weather-get_forecasts].1
dict({
'weather.forecast': dict({
'forecast': list([
]),
}),
})
# ---
# name: test_forecasts[config0-1-weather-get_forecasts].2
dict({
'weather.forecast': dict({
'forecast': list([
dict({
'condition': 'fog',
'datetime': '2023-02-17T14:00:00+00:00',
'is_daytime': True,
'temperature': 14.2,
}),
]),
}),
})
# ---
# name: test_forecasts[config0-1-weather-get_forecasts].3
dict({
'weather.forecast': dict({
'forecast': list([
]),
}),
})
# ---
# name: test_restore_weather_save_state
dict({
'last_apparent_temperature': None,
'last_cloud_coverage': None,
'last_dew_point': None,
'last_humidity': '25.0',
'last_ozone': None,
'last_pressure': None,
'last_temperature': '15.0',
'last_visibility': None,
'last_wind_bearing': None,
'last_wind_gust_speed': None,
'last_wind_speed': None,
})
# ---
# name: test_trigger_weather_services[config0-1-template-get_forecasts]
dict({
'weather.test': dict({
'forecast': list([
dict({
'condition': 'sunny',
'datetime': '2023-10-19T06:50:05-07:00',
'precipitation': 20.0,
'temperature': 20.0,
'templow': 15.0,
}),
]),
}),
})
# ---
# name: test_trigger_weather_services[config0-1-template-get_forecasts].1
dict({
'weather.test': dict({
'forecast': list([
dict({
'condition': 'sunny',
'datetime': '2023-10-19T06:50:05-07:00',
'precipitation': 20.0,
'temperature': 20.0,
'templow': 15.0,
}),
]),
}),
})
# ---
# name: test_trigger_weather_services[config0-1-template-get_forecasts].2
dict({
'weather.test': dict({
'forecast': list([
dict({
'condition': 'sunny',
'datetime': '2023-10-19T06:50:05-07:00',
'is_daytime': True,
'precipitation': 20.0,
'temperature': 20.0,
'templow': 15.0,
}),
]),
}),
})
# ---

View File

@@ -0,0 +1,565 @@
"""The tests for the Template alarm control panel platform."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components import template
from homeassistant.components.alarm_control_panel import (
DOMAIN as ALARM_DOMAIN,
AlarmControlPanelState,
)
from homeassistant.const import (
ATTR_DOMAIN,
ATTR_ENTITY_ID,
ATTR_SERVICE_DATA,
EVENT_CALL_SERVICE,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import Event, HomeAssistant, State, callback
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, assert_setup_component, mock_restore_cache
TEMPLATE_NAME = "alarm_control_panel.test_template_panel"
PANEL_NAME = "alarm_control_panel.test"
@pytest.fixture
def call_service_events(hass: HomeAssistant) -> list[Event]:
"""Track service call events for alarm_control_panel.test."""
events: list[Event] = []
entity_id = "alarm_control_panel.test"
@callback
def capture_events(event: Event) -> None:
if event.data[ATTR_DOMAIN] != ALARM_DOMAIN:
return
if event.data[ATTR_SERVICE_DATA][ATTR_ENTITY_ID] != [entity_id]:
return
events.append(event)
hass.bus.async_listen(EVENT_CALL_SERVICE, capture_events)
return events
OPTIMISTIC_TEMPLATE_ALARM_CONFIG = {
"arm_away": {
"service": "alarm_control_panel.alarm_arm_away",
"entity_id": "alarm_control_panel.test",
"data": {"code": "{{ this.entity_id }}"},
},
"arm_home": {
"service": "alarm_control_panel.alarm_arm_home",
"entity_id": "alarm_control_panel.test",
"data": {"code": "{{ this.entity_id }}"},
},
"arm_night": {
"service": "alarm_control_panel.alarm_arm_night",
"entity_id": "alarm_control_panel.test",
"data": {"code": "{{ this.entity_id }}"},
},
"arm_vacation": {
"service": "alarm_control_panel.alarm_arm_vacation",
"entity_id": "alarm_control_panel.test",
"data": {"code": "{{ this.entity_id }}"},
},
"arm_custom_bypass": {
"service": "alarm_control_panel.alarm_arm_custom_bypass",
"entity_id": "alarm_control_panel.test",
"data": {"code": "{{ this.entity_id }}"},
},
"disarm": {
"service": "alarm_control_panel.alarm_disarm",
"entity_id": "alarm_control_panel.test",
"data": {"code": "{{ this.entity_id }}"},
},
"trigger": {
"service": "alarm_control_panel.alarm_trigger",
"entity_id": "alarm_control_panel.test",
"data": {"code": "{{ this.entity_id }}"},
},
}
TEMPLATE_ALARM_CONFIG = {
"value_template": "{{ states('alarm_control_panel.test') }}",
**OPTIMISTIC_TEMPLATE_ALARM_CONFIG,
}
@pytest.mark.parametrize(("count", "domain"), [(1, "alarm_control_panel")])
@pytest.mark.parametrize(
"config",
[
{
"alarm_control_panel": {
"platform": "template",
"panels": {"test_template_panel": TEMPLATE_ALARM_CONFIG},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_template_state_text(hass: HomeAssistant) -> None:
"""Test the state text of a template."""
for set_state in (
AlarmControlPanelState.ARMED_HOME,
AlarmControlPanelState.ARMED_AWAY,
AlarmControlPanelState.ARMED_NIGHT,
AlarmControlPanelState.ARMED_VACATION,
AlarmControlPanelState.ARMED_CUSTOM_BYPASS,
AlarmControlPanelState.ARMING,
AlarmControlPanelState.DISARMED,
AlarmControlPanelState.PENDING,
AlarmControlPanelState.TRIGGERED,
):
hass.states.async_set(PANEL_NAME, set_state)
await hass.async_block_till_done()
state = hass.states.get(TEMPLATE_NAME)
assert state.state == set_state
hass.states.async_set(PANEL_NAME, "invalid_state")
await hass.async_block_till_done()
state = hass.states.get(TEMPLATE_NAME)
assert state.state == "unknown"
async def test_setup_config_entry(
hass: HomeAssistant, snapshot: SnapshotAssertion
) -> None:
"""Test the config flow."""
value_template = "{{ states('alarm_control_panel.one') }}"
hass.states.async_set("alarm_control_panel.one", "armed_away", {})
template_config_entry = MockConfigEntry(
data={},
domain=template.DOMAIN,
options={
"name": "My template",
"value_template": value_template,
"template_type": "alarm_control_panel",
"code_arm_required": True,
"code_format": "number",
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("alarm_control_panel.my_template")
assert state is not None
assert state == snapshot
hass.states.async_set("alarm_control_panel.one", "disarmed", {})
await hass.async_block_till_done()
state = hass.states.get("alarm_control_panel.my_template")
assert state.state == AlarmControlPanelState.DISARMED
@pytest.mark.parametrize(("count", "domain"), [(1, "alarm_control_panel")])
@pytest.mark.parametrize(
"config",
[
{
"alarm_control_panel": {
"platform": "template",
"panels": {"test_template_panel": OPTIMISTIC_TEMPLATE_ALARM_CONFIG},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_optimistic_states(hass: HomeAssistant) -> None:
"""Test the optimistic state."""
state = hass.states.get(TEMPLATE_NAME)
await hass.async_block_till_done()
assert state.state == "unknown"
for service, set_state in (
("alarm_arm_away", AlarmControlPanelState.ARMED_AWAY),
("alarm_arm_home", AlarmControlPanelState.ARMED_HOME),
("alarm_arm_night", AlarmControlPanelState.ARMED_NIGHT),
("alarm_arm_vacation", AlarmControlPanelState.ARMED_VACATION),
("alarm_arm_custom_bypass", AlarmControlPanelState.ARMED_CUSTOM_BYPASS),
("alarm_disarm", AlarmControlPanelState.DISARMED),
("alarm_trigger", AlarmControlPanelState.TRIGGERED),
):
await hass.services.async_call(
ALARM_DOMAIN,
service,
{"entity_id": TEMPLATE_NAME, "code": "1234"},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get(TEMPLATE_NAME).state == set_state
@pytest.mark.parametrize(("count", "domain"), [(0, "alarm_control_panel")])
@pytest.mark.parametrize(
("config", "msg"),
[
(
{
"alarm_control_panel": {
"platform": "template",
"panels": {
"test_template_panel": {
"value_template": "{% if blah %}",
**OPTIMISTIC_TEMPLATE_ALARM_CONFIG,
}
},
}
},
"invalid template",
),
(
{
"alarm_control_panel": {
"platform": "template",
"panels": {
"bad name here": {
"value_template": "disarmed",
**OPTIMISTIC_TEMPLATE_ALARM_CONFIG,
}
},
}
},
"invalid slug bad name",
),
(
{
"alarm_control_panel": {
"platform": "template",
"wibble": {"test_panel": "Invalid"},
}
},
"'wibble' is an invalid option",
),
(
{
"alarm_control_panel": {"platform": "template"},
},
"required key 'panels' not provided",
),
(
{
"alarm_control_panel": {
"platform": "template",
"panels": {
"test_template_panel": {
"value_template": "disarmed",
**OPTIMISTIC_TEMPLATE_ALARM_CONFIG,
"code_format": "bad_format",
}
},
}
},
"value must be one of ['no_code', 'number', 'text']",
),
],
)
@pytest.mark.usefixtures("start_ha")
async def test_template_syntax_error(
hass: HomeAssistant, msg, caplog_setup_text
) -> None:
"""Test templating syntax error."""
assert len(hass.states.async_all("alarm_control_panel")) == 0
assert (msg) in caplog_setup_text
@pytest.mark.parametrize(("count", "domain"), [(1, "alarm_control_panel")])
@pytest.mark.parametrize(
"config",
[
{
"alarm_control_panel": {
"platform": "template",
"panels": {
"test_template_panel": {
"name": '{{ "Template Alarm Panel" }}',
"value_template": "disarmed",
**OPTIMISTIC_TEMPLATE_ALARM_CONFIG,
}
},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_name(hass: HomeAssistant) -> None:
"""Test the accessibility of the name attribute."""
state = hass.states.get(TEMPLATE_NAME)
assert state is not None
assert state.attributes.get("friendly_name") == "Template Alarm Panel"
@pytest.mark.parametrize(("count", "domain"), [(1, "alarm_control_panel")])
@pytest.mark.parametrize(
"config",
[
{
"alarm_control_panel": {
"platform": "template",
"panels": {"test_template_panel": TEMPLATE_ALARM_CONFIG},
}
},
],
)
@pytest.mark.parametrize(
"service",
[
"alarm_arm_home",
"alarm_arm_away",
"alarm_arm_night",
"alarm_arm_vacation",
"alarm_arm_custom_bypass",
"alarm_disarm",
"alarm_trigger",
],
)
@pytest.mark.usefixtures("start_ha")
async def test_actions(
hass: HomeAssistant, service, call_service_events: list[Event]
) -> None:
"""Test alarm actions."""
await hass.services.async_call(
ALARM_DOMAIN,
service,
{"entity_id": TEMPLATE_NAME, "code": "1234"},
blocking=True,
)
await hass.async_block_till_done()
assert len(call_service_events) == 1
assert call_service_events[0].data["service"] == service
assert call_service_events[0].data["service_data"]["code"] == TEMPLATE_NAME
@pytest.mark.parametrize(("count", "domain"), [(1, "alarm_control_panel")])
@pytest.mark.parametrize(
"config",
[
{
"alarm_control_panel": {
"platform": "template",
"panels": {
"test_template_alarm_control_panel_01": {
"unique_id": "not-so-unique-anymore",
"value_template": "{{ true }}",
},
"test_template_alarm_control_panel_02": {
"unique_id": "not-so-unique-anymore",
"value_template": "{{ false }}",
},
},
},
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_unique_id(hass: HomeAssistant) -> None:
"""Test unique_id option only creates one alarm control panel per id."""
assert len(hass.states.async_all()) == 1
@pytest.mark.parametrize(("count", "domain"), [(1, "alarm_control_panel")])
@pytest.mark.parametrize(
("config", "code_format", "code_arm_required"),
[
(
{
"alarm_control_panel": {
"platform": "template",
"panels": {
"test_template_panel": {
"value_template": "disarmed",
}
},
}
},
"number",
True,
),
(
{
"alarm_control_panel": {
"platform": "template",
"panels": {
"test_template_panel": {
"value_template": "disarmed",
"code_format": "text",
}
},
}
},
"text",
True,
),
(
{
"alarm_control_panel": {
"platform": "template",
"panels": {
"test_template_panel": {
"value_template": "disarmed",
"code_format": "no_code",
"code_arm_required": False,
}
},
}
},
None,
False,
),
(
{
"alarm_control_panel": {
"platform": "template",
"panels": {
"test_template_panel": {
"value_template": "disarmed",
"code_format": "text",
"code_arm_required": False,
}
},
}
},
"text",
False,
),
],
)
@pytest.mark.usefixtures("start_ha")
async def test_code_config(hass: HomeAssistant, code_format, code_arm_required) -> None:
"""Test configuration options related to alarm code."""
state = hass.states.get(TEMPLATE_NAME)
assert state.attributes.get("code_format") == code_format
assert state.attributes.get("code_arm_required") == code_arm_required
@pytest.mark.parametrize(("count", "domain"), [(1, "alarm_control_panel")])
@pytest.mark.parametrize(
"config",
[
{
"alarm_control_panel": {
"platform": "template",
"panels": {"test_template_panel": TEMPLATE_ALARM_CONFIG},
}
},
],
)
@pytest.mark.parametrize(
("restored_state", "initial_state"),
[
(
AlarmControlPanelState.ARMED_AWAY,
AlarmControlPanelState.ARMED_AWAY,
),
(
AlarmControlPanelState.ARMED_CUSTOM_BYPASS,
AlarmControlPanelState.ARMED_CUSTOM_BYPASS,
),
(
AlarmControlPanelState.ARMED_HOME,
AlarmControlPanelState.ARMED_HOME,
),
(
AlarmControlPanelState.ARMED_NIGHT,
AlarmControlPanelState.ARMED_NIGHT,
),
(
AlarmControlPanelState.ARMED_VACATION,
AlarmControlPanelState.ARMED_VACATION,
),
(AlarmControlPanelState.ARMING, AlarmControlPanelState.ARMING),
(AlarmControlPanelState.DISARMED, AlarmControlPanelState.DISARMED),
(AlarmControlPanelState.PENDING, AlarmControlPanelState.PENDING),
(
AlarmControlPanelState.TRIGGERED,
AlarmControlPanelState.TRIGGERED,
),
(STATE_UNAVAILABLE, STATE_UNKNOWN),
(STATE_UNKNOWN, STATE_UNKNOWN),
("faulty_state", STATE_UNKNOWN),
],
)
async def test_restore_state(
hass: HomeAssistant,
count,
domain,
config,
restored_state,
initial_state,
) -> None:
"""Test restoring template alarm control panel."""
fake_state = State(
"alarm_control_panel.test_template_panel",
restored_state,
{},
)
mock_restore_cache(hass, (fake_state,))
with assert_setup_component(count, domain):
assert await async_setup_component(
hass,
domain,
config,
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("alarm_control_panel.test_template_panel")
assert state.state == initial_state
async def test_device_id(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for device for button template."""
device_config_entry = MockConfigEntry()
device_config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=device_config_entry.entry_id,
identifiers={("test", "identifier_test")},
connections={("mac", "30:31:32:33:34:35")},
)
await hass.async_block_till_done()
assert device_entry is not None
assert device_entry.id is not None
template_config_entry = MockConfigEntry(
data={},
domain=template.DOMAIN,
options={
"name": "My template",
"value_template": "disarmed",
"template_type": "alarm_control_panel",
"code_arm_required": True,
"code_format": "number",
"device_id": device_entry.id,
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
template_entity = entity_registry.async_get("alarm_control_panel.my_template")
assert template_entity is not None
assert template_entity.device_id == device_entry.id

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,242 @@
"""Test blueprints."""
from collections.abc import Iterator
import contextlib
from os import PathLike
import pathlib
from unittest.mock import MagicMock, patch
import pytest
from homeassistant.components import template
from homeassistant.components.blueprint import (
BLUEPRINT_SCHEMA,
Blueprint,
BlueprintInUse,
DomainBlueprints,
)
from homeassistant.components.template import DOMAIN, SERVICE_RELOAD
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component
from homeassistant.util import yaml
from tests.common import async_mock_service
BUILTIN_BLUEPRINT_FOLDER = pathlib.Path(template.__file__).parent / "blueprints"
@contextlib.contextmanager
def patch_blueprint(
blueprint_path: str, data_path: str | PathLike[str]
) -> Iterator[None]:
"""Patch blueprint loading from a different source."""
orig_load = DomainBlueprints._load_blueprint
@callback
def mock_load_blueprint(self, path):
if path != blueprint_path:
pytest.fail(f"Unexpected blueprint {path}")
return orig_load(self, path)
return Blueprint(
yaml.load_yaml(data_path),
expected_domain=self.domain,
path=path,
schema=BLUEPRINT_SCHEMA,
)
with patch(
"homeassistant.components.blueprint.models.DomainBlueprints._load_blueprint",
mock_load_blueprint,
):
yield
@contextlib.contextmanager
def patch_invalid_blueprint() -> Iterator[None]:
"""Patch blueprint returning an invalid one."""
@callback
def mock_load_blueprint(self, path):
return Blueprint(
{
"blueprint": {
"domain": "template",
"name": "Invalid template blueprint",
},
"binary_sensor": {},
"sensor": {},
},
expected_domain=self.domain,
path=path,
schema=BLUEPRINT_SCHEMA,
)
with patch(
"homeassistant.components.blueprint.models.DomainBlueprints._load_blueprint",
mock_load_blueprint,
):
yield
async def test_inverted_binary_sensor(
hass: HomeAssistant, device_registry: dr.DeviceRegistry
) -> None:
"""Test inverted binary sensor blueprint."""
hass.states.async_set("binary_sensor.foo", "on", {"friendly_name": "Foo"})
hass.states.async_set("binary_sensor.bar", "off", {"friendly_name": "Bar"})
with patch_blueprint(
"inverted_binary_sensor.yaml",
BUILTIN_BLUEPRINT_FOLDER / "inverted_binary_sensor.yaml",
):
assert await async_setup_component(
hass,
"template",
{
"template": [
{
"use_blueprint": {
"path": "inverted_binary_sensor.yaml",
"input": {"reference_entity": "binary_sensor.foo"},
},
"name": "Inverted foo",
},
{
"use_blueprint": {
"path": "inverted_binary_sensor.yaml",
"input": {"reference_entity": "binary_sensor.bar"},
},
"name": "Inverted bar",
},
]
},
)
hass.states.async_set("binary_sensor.foo", "off", {"friendly_name": "Foo"})
hass.states.async_set("binary_sensor.bar", "on", {"friendly_name": "Bar"})
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.foo").state == "off"
assert hass.states.get("binary_sensor.bar").state == "on"
inverted_foo = hass.states.get("binary_sensor.inverted_foo")
assert inverted_foo
assert inverted_foo.state == "on"
inverted_bar = hass.states.get("binary_sensor.inverted_bar")
assert inverted_bar
assert inverted_bar.state == "off"
foo_template = template.helpers.blueprint_in_template(hass, "binary_sensor.foo")
inverted_foo_template = template.helpers.blueprint_in_template(
hass, "binary_sensor.inverted_foo"
)
assert foo_template is None
assert inverted_foo_template == "inverted_binary_sensor.yaml"
inverted_binary_sensor_blueprint_entity_ids = (
template.helpers.templates_with_blueprint(hass, "inverted_binary_sensor.yaml")
)
assert len(inverted_binary_sensor_blueprint_entity_ids) == 2
assert len(template.helpers.templates_with_blueprint(hass, "dummy.yaml")) == 0
with pytest.raises(BlueprintInUse):
await template.async_get_blueprints(hass).async_remove_blueprint(
"inverted_binary_sensor.yaml"
)
async def test_domain_blueprint(hass: HomeAssistant) -> None:
"""Test DomainBlueprint services."""
reload_handler_calls = async_mock_service(hass, DOMAIN, SERVICE_RELOAD)
mock_create_file = MagicMock()
mock_create_file.return_value = True
with patch(
"homeassistant.components.blueprint.models.DomainBlueprints._create_file",
mock_create_file,
):
await template.async_get_blueprints(hass).async_add_blueprint(
Blueprint(
{
"blueprint": {
"domain": DOMAIN,
"name": "Test",
},
},
expected_domain="template",
path="xxx",
schema=BLUEPRINT_SCHEMA,
),
"xxx",
True,
)
assert len(reload_handler_calls) == 1
async def test_invalid_blueprint(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test an invalid blueprint definition."""
with patch_invalid_blueprint():
assert await async_setup_component(
hass,
"template",
{
"template": [
{
"use_blueprint": {
"path": "invalid.yaml",
},
"name": "Invalid blueprint instance",
},
]
},
)
assert "more than one platform defined per blueprint" in caplog.text
assert await template.async_get_blueprints(hass).async_get_blueprints() == {}
async def test_no_blueprint(hass: HomeAssistant) -> None:
"""Test templates without blueprints."""
with patch_blueprint(
"inverted_binary_sensor.yaml",
BUILTIN_BLUEPRINT_FOLDER / "inverted_binary_sensor.yaml",
):
assert await async_setup_component(
hass,
"template",
{
"template": [
{"binary_sensor": {"name": "test entity", "state": "off"}},
{
"use_blueprint": {
"path": "inverted_binary_sensor.yaml",
"input": {"reference_entity": "binary_sensor.foo"},
},
"name": "inverted entity",
},
]
},
)
hass.states.async_set("binary_sensor.foo", "off", {"friendly_name": "Foo"})
await hass.async_block_till_done()
assert (
len(
template.helpers.templates_with_blueprint(
hass, "inverted_binary_sensor.yaml"
)
)
== 1
)
assert (
template.helpers.blueprint_in_template(hass, "binary_sensor.test_entity")
is None
)

View File

@@ -0,0 +1,293 @@
"""The tests for the Template button platform."""
import datetime as dt
from typing import Any
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant import setup
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.components.template import DOMAIN
from homeassistant.components.template.button import DEFAULT_NAME
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_ENTITY_ID,
CONF_FRIENDLY_NAME,
CONF_ICON,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import MockConfigEntry, assert_setup_component
_TEST_BUTTON = "button.template_button"
_TEST_OPTIONS_BUTTON = "button.test"
@pytest.mark.parametrize(
"config_entry_extra_options",
[
{},
{
"device_class": "update",
},
],
)
async def test_setup_config_entry(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
config_entry_extra_options: dict[str, str],
) -> None:
"""Test the config flow."""
template_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"name": "My template",
"template_type": "button",
"press": [
{
"service": "input_boolean.toggle",
"metadata": {},
"data": {},
"target": {"entity_id": "input_boolean.test"},
}
],
}
| config_entry_extra_options,
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("button.my_template")
assert state is not None
assert state == snapshot
async def test_missing_optional_config(hass: HomeAssistant) -> None:
"""Test: missing optional template is ok."""
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"button": {
"press": {"service": "script.press"},
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
_verify(hass, STATE_UNKNOWN)
async def test_missing_required_keys(hass: HomeAssistant) -> None:
"""Test: missing required fields will fail."""
with assert_setup_component(0, "template"):
assert await setup.async_setup_component(
hass,
"template",
{"template": {"button": {}}},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all("button") == []
async def test_all_optional_config(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
freezer: FrozenDateTimeFactory,
calls: list[ServiceCall],
) -> None:
"""Test: including all optional templates is ok."""
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"unique_id": "test",
"button": {
"press": {
"service": "test.automation",
"data_template": {"caller": "{{ this.entity_id }}"},
},
"device_class": "restart",
"unique_id": "test",
"name": "test",
"icon": "mdi:test",
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
_verify(
hass,
STATE_UNKNOWN,
{
CONF_DEVICE_CLASS: "restart",
CONF_FRIENDLY_NAME: "test",
CONF_ICON: "mdi:test",
},
_TEST_OPTIONS_BUTTON,
)
now = dt.datetime.now(dt.UTC)
freezer.move_to(now)
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{CONF_ENTITY_ID: _TEST_OPTIONS_BUTTON},
blocking=True,
)
assert len(calls) == 1
assert calls[0].data["caller"] == _TEST_OPTIONS_BUTTON
_verify(
hass,
now.isoformat(),
{
CONF_DEVICE_CLASS: "restart",
CONF_FRIENDLY_NAME: "test",
CONF_ICON: "mdi:test",
},
_TEST_OPTIONS_BUTTON,
)
assert entity_registry.async_get_entity_id("button", "template", "test-test")
async def test_name_template(hass: HomeAssistant) -> None:
"""Test: name template."""
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"button": {
"press": {"service": "script.press"},
"name": "Button {{ 1 + 1 }}",
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
_verify(
hass,
STATE_UNKNOWN,
{
CONF_FRIENDLY_NAME: "Button 2",
},
"button.button_2",
)
async def test_unique_id(hass: HomeAssistant) -> None:
"""Test: unique id is ok."""
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"unique_id": "test",
"button": {
"press": {"service": "script.press"},
"unique_id": "test",
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
_verify(hass, STATE_UNKNOWN)
def _verify(
hass: HomeAssistant,
expected_value: str,
attributes: dict[str, Any] | None = None,
entity_id: str = _TEST_BUTTON,
) -> None:
"""Verify button's state."""
attributes = attributes or {}
if CONF_FRIENDLY_NAME not in attributes:
attributes[CONF_FRIENDLY_NAME] = DEFAULT_NAME
state = hass.states.get(entity_id)
assert state.state == expected_value
assert state.attributes == attributes
async def test_device_id(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for device for button template."""
device_config_entry = MockConfigEntry()
device_config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=device_config_entry.entry_id,
identifiers={("test", "identifier_test")},
connections={("mac", "30:31:32:33:34:35")},
)
await hass.async_block_till_done()
assert device_entry is not None
assert device_entry.id is not None
template_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"name": "My template",
"template_type": "button",
"device_id": device_entry.id,
"press": [
{
"service": "input_boolean.toggle",
"metadata": {},
"data": {},
"target": {"entity_id": "input_boolean.test"},
}
],
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
template_entity = entity_registry.async_get("button.my_template")
assert template_entity is not None
assert template_entity.device_id == device_entry.id

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,584 @@
"""The tests for the Template image platform."""
from http import HTTPStatus
from io import BytesIO
from typing import Any
import httpx
from PIL import Image
import pytest
import respx
from syrupy.assertion import SnapshotAssertion
from homeassistant import setup
from homeassistant.components.input_text import (
ATTR_VALUE as INPUT_TEXT_ATTR_VALUE,
DOMAIN as INPUT_TEXT_DOMAIN,
SERVICE_SET_VALUE as INPUT_TEXT_SERVICE_SET_VALUE,
)
from homeassistant.components.template import DOMAIN
from homeassistant.const import ATTR_ENTITY_PICTURE, CONF_ENTITY_ID, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util import dt as dt_util
from tests.common import MockConfigEntry, assert_setup_component
from tests.typing import ClientSessionGenerator
_DEFAULT = object()
_TEST_IMAGE = "image.template_image"
_URL_INPUT_TEXT = "input_text.url"
@pytest.fixture
def imgbytes_jpg():
"""Image in RAM for testing."""
buf = BytesIO() # fake image in ram for testing.
Image.new("RGB", (1, 1)).save(buf, format="jpeg")
return bytes(buf.getbuffer())
@pytest.fixture
def imgbytes2_jpg():
"""Image in RAM for testing."""
buf = BytesIO() # fake image in ram for testing.
Image.new("RGB", (1, 1), 100).save(buf, format="jpeg")
return bytes(buf.getbuffer())
async def _assert_state(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
expected_state: str,
expected_image: bytes | None,
entity_id: str = _TEST_IMAGE,
expected_content_type: str = "image/jpeg",
expected_entity_picture: Any = _DEFAULT,
expected_status: HTTPStatus = HTTPStatus.OK,
):
"""Verify image's state."""
state = hass.states.get(entity_id)
attributes = state.attributes
assert state.state == expected_state
if expected_entity_picture is _DEFAULT:
expected_entity_picture = (
f"/api/image_proxy/{entity_id}?token={attributes['access_token']}"
)
assert attributes.get(ATTR_ENTITY_PICTURE) == expected_entity_picture
client = await hass_client()
resp = await client.get(f"/api/image_proxy/{entity_id}")
assert resp.content_type == expected_content_type
assert resp.status == expected_status
body = await resp.read()
assert body == expected_image
@respx.mock
@pytest.mark.freeze_time("2024-07-09 00:00:00+00:00")
async def test_setup_config_entry(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
imgbytes_jpg,
) -> None:
"""Test the config flow."""
respx.get("http://example.com").respond(
stream=imgbytes_jpg, content_type="image/jpeg"
)
template_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"name": "My template",
"template_type": "image",
"url": "http://example.com",
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("image.my_template")
assert state is not None
assert state.state == "2024-07-09T00:00:00+00:00"
@respx.mock
@pytest.mark.freeze_time("2023-04-01 00:00:00+00:00")
async def test_platform_config(
hass: HomeAssistant, hass_client: ClientSessionGenerator, imgbytes_jpg
) -> None:
"""Test configuring under the platform key does not work."""
respx.get("http://example.com").respond(
stream=imgbytes_jpg, content_type="image/jpeg"
)
with assert_setup_component(1, "image"):
assert await setup.async_setup_component(
hass,
"image",
{
"image": {
"platform": "template",
"url": "{{ 'http://example.com' }}",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 0
@respx.mock
@pytest.mark.freeze_time("2023-04-01 00:00:00+00:00")
async def test_missing_optional_config(
hass: HomeAssistant, hass_client: ClientSessionGenerator, imgbytes_jpg
) -> None:
"""Test: missing optional template is ok."""
respx.get("http://example.com").respond(
stream=imgbytes_jpg, content_type="image/jpeg"
)
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"image": {
"url": "{{ 'http://example.com' }}",
}
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
expected_state = dt_util.utcnow().isoformat()
await _assert_state(hass, hass_client, expected_state, imgbytes_jpg)
assert respx.get("http://example.com").call_count == 1
# Check the image is not refetched
await _assert_state(hass, hass_client, expected_state, imgbytes_jpg)
assert respx.get("http://example.com").call_count == 1
@respx.mock
@pytest.mark.freeze_time("2023-04-01 00:00:00+00:00")
async def test_multiple_configs(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
imgbytes_jpg,
imgbytes2_jpg,
) -> None:
"""Test: multiple image entities get created."""
respx.get("http://example.com").respond(
stream=imgbytes_jpg, content_type="image/jpeg"
)
respx.get("http://example2.com").respond(
stream=imgbytes2_jpg, content_type="image/png"
)
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"image": [
{
"url": "{{ 'http://example.com' }}",
},
{
"url": "{{ 'http://example2.com' }}",
},
]
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
expected_state = dt_util.utcnow().isoformat()
await _assert_state(hass, hass_client, expected_state, imgbytes_jpg)
await _assert_state(
hass,
hass_client,
expected_state,
imgbytes2_jpg,
f"{_TEST_IMAGE}_2",
expected_content_type="image/png",
)
async def test_missing_required_keys(hass: HomeAssistant) -> None:
"""Test: missing required fields will fail."""
with assert_setup_component(0, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"image": {
"name": "a name",
}
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all("image") == []
async def test_unique_id(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test unique_id configuration."""
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"unique_id": "b",
"image": {
"url": "http://example.com",
"unique_id": "a",
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
entry = entity_registry.async_get(_TEST_IMAGE)
assert entry
assert entry.unique_id == "b-a"
@respx.mock
@pytest.mark.freeze_time("2023-04-01 00:00:00+00:00")
async def test_custom_entity_picture(
hass: HomeAssistant, hass_client: ClientSessionGenerator, imgbytes_jpg
) -> None:
"""Test custom entity picture."""
respx.get("http://example.com").respond(
stream=imgbytes_jpg, content_type="image/jpeg"
)
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"image": {
"url": "http://example.com",
"picture": "http://example2.com",
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
expected_state = dt_util.utcnow().isoformat()
await _assert_state(
hass,
hass_client,
expected_state,
imgbytes_jpg,
expected_entity_picture="http://example2.com",
)
@respx.mock
async def test_template_error(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> None:
"""Test handling template error."""
respx.get("http://example.com").side_effect = httpx.TimeoutException
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"image": {
"url": "{{ no_such_variable.url }}",
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
await _assert_state(
hass,
hass_client,
STATE_UNKNOWN,
b"500: Internal Server Error",
expected_status=HTTPStatus.INTERNAL_SERVER_ERROR,
expected_content_type="text/plain",
)
@respx.mock
@pytest.mark.freeze_time("2023-04-01 00:00:00+00:00")
async def test_templates_with_entities(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
imgbytes_jpg,
imgbytes2_jpg,
) -> None:
"""Test templates with values from other entities."""
respx.get("http://example.com").respond(
stream=imgbytes_jpg, content_type="image/jpeg"
)
respx.get("http://example2.com").respond(
stream=imgbytes2_jpg, content_type="image/png"
)
with assert_setup_component(1, "input_text"):
assert await setup.async_setup_component(
hass,
"input_text",
{
"input_text": {
"url": {
"initial": "http://example.com",
"name": "url",
},
}
},
)
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"image": {
"url": f"{{{{ states('{_URL_INPUT_TEXT}') }}}}",
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
expected_state = dt_util.utcnow().isoformat()
await _assert_state(hass, hass_client, expected_state, imgbytes_jpg)
assert respx.get("http://example.com").call_count == 1
# Check the image is not refetched
await _assert_state(hass, hass_client, expected_state, imgbytes_jpg)
assert respx.get("http://example.com").call_count == 1
await hass.services.async_call(
INPUT_TEXT_DOMAIN,
INPUT_TEXT_SERVICE_SET_VALUE,
{CONF_ENTITY_ID: _URL_INPUT_TEXT, INPUT_TEXT_ATTR_VALUE: "http://example2.com"},
blocking=True,
)
await hass.async_block_till_done()
await _assert_state(
hass,
hass_client,
expected_state,
imgbytes2_jpg,
expected_content_type="image/png",
)
@respx.mock
@pytest.mark.freeze_time("2023-04-01 00:00:00+00:00")
async def test_trigger_image(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
imgbytes_jpg,
imgbytes2_jpg,
) -> None:
"""Test trigger based template image."""
respx.get("http://example.com").respond(
stream=imgbytes_jpg, content_type="image/jpeg"
)
respx.get("http://example2.com").respond(
stream=imgbytes2_jpg, content_type="image/png"
)
assert await setup.async_setup_component(
hass,
"template",
{
"template": [
{
"trigger": {"platform": "event", "event_type": "test_event"},
"image": [
{
"url": "{{ trigger.event.data.url }}",
},
],
},
],
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
# No image is loaded, expect error
await _assert_state(
hass,
hass_client,
"unknown",
b"500: Internal Server Error",
expected_status=HTTPStatus.INTERNAL_SERVER_ERROR,
expected_content_type="text/plain",
)
hass.bus.async_fire("test_event", {"url": "http://example.com"})
await hass.async_block_till_done()
expected_state = dt_util.utcnow().isoformat()
await _assert_state(hass, hass_client, expected_state, imgbytes_jpg)
assert respx.get("http://example.com").call_count == 1
# Check the image is not refetched
await _assert_state(hass, hass_client, expected_state, imgbytes_jpg)
assert respx.get("http://example.com").call_count == 1
hass.bus.async_fire("test_event", {"url": "http://example2.com"})
await hass.async_block_till_done()
await _assert_state(
hass,
hass_client,
expected_state,
imgbytes2_jpg,
expected_content_type="image/png",
)
@respx.mock
@pytest.mark.freeze_time("2023-04-01 00:00:00+00:00")
async def test_trigger_image_custom_entity_picture(
hass: HomeAssistant, hass_client: ClientSessionGenerator, imgbytes_jpg
) -> None:
"""Test trigger based template image with custom entity picture."""
respx.get("http://example.com").respond(
stream=imgbytes_jpg, content_type="image/jpeg"
)
assert await setup.async_setup_component(
hass,
"template",
{
"template": [
{
"trigger": {"platform": "event", "event_type": "test_event"},
"image": [
{
"url": "{{ trigger.event.data.url }}",
"picture": "http://example2.com",
},
],
},
],
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
# No image is loaded, expect error
await _assert_state(
hass,
hass_client,
"unknown",
b"500: Internal Server Error",
expected_status=HTTPStatus.INTERNAL_SERVER_ERROR,
expected_entity_picture="http://example2.com",
expected_content_type="text/plain",
)
hass.bus.async_fire("test_event", {"url": "http://example.com"})
await hass.async_block_till_done()
expected_state = dt_util.utcnow().isoformat()
await _assert_state(
hass,
hass_client,
expected_state,
imgbytes_jpg,
expected_entity_picture="http://example2.com",
)
@respx.mock
async def test_device_id(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for device for image template."""
device_config_entry = MockConfigEntry()
device_config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=device_config_entry.entry_id,
identifiers={("test", "identifier_test")},
connections={("mac", "30:31:32:33:34:35")},
)
await hass.async_block_till_done()
assert device_entry is not None
assert device_entry.id is not None
respx.get("http://example.com").respond(
stream=imgbytes_jpg, content_type="image/jpeg"
)
template_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"name": "My template",
"template_type": "image",
"url": "http://example.com",
"device_id": device_entry.id,
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
template_entity = entity_registry.async_get("image.my_template")
assert template_entity is not None
assert template_entity.device_id == device_entry.id

View File

@@ -0,0 +1,495 @@
"""Test for Template helper."""
from datetime import timedelta
from unittest.mock import patch
import pytest
from homeassistant import config
from homeassistant.components.template import DOMAIN
from homeassistant.const import SERVICE_RELOAD
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.common import MockConfigEntry, async_fire_time_changed, get_fixture_path
@pytest.mark.parametrize(("count", "domain"), [(1, "sensor")])
@pytest.mark.parametrize(
"config",
[
{
"sensor": {
"platform": DOMAIN,
"sensors": {
"state": {
"value_template": "{{ states.sensor.test_sensor.state }}"
},
},
},
"template": [
{
"trigger": {"platform": "event", "event_type": "event_1"},
"sensor": {
"name": "top level",
"state": "{{ trigger.event.data.source }}",
},
},
{
"sensor": {
"name": "top level state",
"state": "{{ states.sensor.top_level.state }} + 2",
},
"binary_sensor": {
"name": "top level state",
"state": "{{ states.sensor.top_level.state == 'init' }}",
},
},
],
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_reloadable(hass: HomeAssistant) -> None:
"""Test that we can reload."""
hass.states.async_set("sensor.test_sensor", "mytest")
await hass.async_block_till_done()
assert hass.states.get("sensor.top_level_state").state == "unknown + 2"
assert hass.states.get("binary_sensor.top_level_state").state == "off"
hass.bus.async_fire("event_1", {"source": "init"})
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 5
assert hass.states.get("sensor.state").state == "mytest"
assert hass.states.get("sensor.top_level").state == "init"
await hass.async_block_till_done()
assert hass.states.get("sensor.top_level_state").state == "init + 2"
assert hass.states.get("binary_sensor.top_level_state").state == "on"
await async_yaml_patch_helper(hass, "sensor_configuration.yaml")
assert len(hass.states.async_all()) == 4
hass.bus.async_fire("event_2", {"source": "reload"})
await hass.async_block_till_done()
assert hass.states.get("sensor.state") is None
assert hass.states.get("sensor.top_level") is None
assert hass.states.get("sensor.watching_tv_in_master_bedroom").state == "off"
assert float(hass.states.get("sensor.combined_sensor_energy_usage").state) == 0
assert hass.states.get("sensor.top_level_2").state == "reload"
@pytest.mark.parametrize(("count", "domain"), [(1, "sensor")])
@pytest.mark.parametrize(
"config",
[
{
"sensor": {
"platform": DOMAIN,
"sensors": {
"state": {
"value_template": "{{ states.sensor.test_sensor.state }}"
},
},
},
"template": {
"trigger": {"platform": "event", "event_type": "event_1"},
"sensor": {
"name": "top level",
"state": "{{ trigger.event.data.source }}",
},
},
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_reloadable_can_remove(hass: HomeAssistant) -> None:
"""Test that we can reload and remove all template sensors."""
hass.states.async_set("sensor.test_sensor", "mytest")
await hass.async_block_till_done()
hass.bus.async_fire("event_1", {"source": "init"})
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 3
assert hass.states.get("sensor.state").state == "mytest"
assert hass.states.get("sensor.top_level").state == "init"
await async_yaml_patch_helper(hass, "empty_configuration.yaml")
assert len(hass.states.async_all()) == 1
@pytest.mark.parametrize(("count", "domain"), [(1, "sensor")])
@pytest.mark.parametrize(
"config",
[
{
"sensor": {
"platform": DOMAIN,
"sensors": {
"state": {
"value_template": "{{ states.sensor.test_sensor.state }}"
},
},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_reloadable_stops_on_invalid_config(hass: HomeAssistant) -> None:
"""Test we stop the reload if configuration.yaml is completely broken."""
hass.states.async_set("sensor.test_sensor", "mytest")
await hass.async_block_till_done()
assert hass.states.get("sensor.state").state == "mytest"
assert len(hass.states.async_all()) == 2
await async_yaml_patch_helper(hass, "configuration.yaml.corrupt")
assert hass.states.get("sensor.state").state == "mytest"
assert len(hass.states.async_all()) == 2
@pytest.mark.parametrize(("count", "domain"), [(1, "sensor")])
@pytest.mark.parametrize(
"config",
[
{
"sensor": {
"platform": DOMAIN,
"sensors": {
"state": {
"value_template": "{{ states.sensor.test_sensor.state }}"
},
},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_reloadable_handles_partial_valid_config(hass: HomeAssistant) -> None:
"""Test we can still setup valid sensors when configuration.yaml has a broken entry."""
hass.states.async_set("sensor.test_sensor", "mytest")
await hass.async_block_till_done()
assert hass.states.get("sensor.state").state == "mytest"
assert len(hass.states.async_all("sensor")) == 2
await async_yaml_patch_helper(hass, "broken_configuration.yaml")
assert len(hass.states.async_all("sensor")) == 3
assert hass.states.get("sensor.state") is None
assert hass.states.get("sensor.watching_tv_in_master_bedroom").state == "off"
assert float(hass.states.get("sensor.combined_sensor_energy_usage").state) == 0
@pytest.mark.parametrize(("count", "domain"), [(1, "sensor")])
@pytest.mark.parametrize(
"config",
[
{
"sensor": {
"platform": DOMAIN,
"sensors": {
"state": {
"value_template": "{{ states.sensor.test_sensor.state }}"
},
},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_reloadable_multiple_platforms(hass: HomeAssistant) -> None:
"""Test that we can reload."""
hass.states.async_set("sensor.test_sensor", "mytest")
await async_setup_component(
hass,
"binary_sensor",
{
"binary_sensor": {
"platform": DOMAIN,
"sensors": {
"state": {
"value_template": "{{ states.sensor.test_sensor.state }}"
},
},
}
},
)
await hass.async_block_till_done()
assert hass.states.get("sensor.state").state == "mytest"
assert hass.states.get("binary_sensor.state").state == "off"
assert len(hass.states.async_all()) == 3
await async_yaml_patch_helper(hass, "sensor_configuration.yaml")
assert len(hass.states.async_all()) == 4
assert hass.states.get("sensor.state") is None
assert hass.states.get("sensor.watching_tv_in_master_bedroom").state == "off"
assert float(hass.states.get("sensor.combined_sensor_energy_usage").state) == 0
assert hass.states.get("sensor.top_level_2") is not None
@pytest.mark.parametrize(("count", "domain"), [(1, "sensor")])
@pytest.mark.parametrize(
"config",
[
{
"sensor": {
"platform": DOMAIN,
"sensors": {
"state": {"value_template": "{{ 1 }}"},
},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_reload_sensors_that_reference_other_template_sensors(
hass: HomeAssistant,
) -> None:
"""Test that we can reload sensor that reference other template sensors."""
await async_yaml_patch_helper(hass, "ref_configuration.yaml")
assert len(hass.states.async_all()) == 3
await hass.async_block_till_done()
next_time = dt_util.utcnow() + timedelta(seconds=1.2)
with patch(
"homeassistant.helpers.ratelimit.time.time", return_value=next_time.timestamp()
):
async_fire_time_changed(hass, next_time)
await hass.async_block_till_done()
assert hass.states.get("sensor.test1").state == "3"
assert hass.states.get("sensor.test2").state == "1"
assert hass.states.get("sensor.test3").state == "2"
async def async_yaml_patch_helper(hass: HomeAssistant, filename: str) -> None:
"""Help update configuration.yaml."""
yaml_path = get_fixture_path(filename, "template")
with patch.object(config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
@pytest.mark.parametrize(
(
"config_entry_options",
"config_user_input",
),
[
(
{
"name": "My template",
"state": "{{10}}",
"template_type": "sensor",
},
{
"state": "{{12}}",
},
),
(
{
"template_type": "binary_sensor",
"name": "My template",
"state": "{{1 == 1}}",
},
{
"state": "{{1 == 2}}",
},
),
(
{
"template_type": "image",
"name": "My template",
"url": "http://example.com",
},
{
"url": "http://example.com",
},
),
(
{
"template_type": "button",
"name": "My template",
},
{},
),
(
{
"template_type": "number",
"name": "My template",
"state": "{{ 10 }}",
"min": 0,
"max": 100,
"step": 0.1,
"set_value": {
"action": "input_number.set_value",
"target": {"entity_id": "input_number.test"},
"data": {"value": "{{ value }}"},
},
},
{
"state": "{{ 11 }}",
"min": 0,
"max": 100,
"step": 0.1,
"set_value": {
"action": "input_number.set_value",
"target": {"entity_id": "input_number.test"},
"data": {"value": "{{ value }}"},
},
},
),
(
{
"template_type": "select",
"name": "My template",
"state": "{{ 'on' }}",
"options": "{{ ['off', 'on', 'auto'] }}",
},
{
"state": "{{ 'on' }}",
"options": "{{ ['off', 'on', 'auto'] }}",
},
),
(
{
"template_type": "switch",
"name": "My template",
"value_template": "{{ true }}",
},
{
"value_template": "{{ true }}",
},
),
],
)
async def test_change_device(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
config_entry_options: dict[str, str],
config_user_input: dict[str, str],
) -> None:
"""Test the link between the device and the config entry.
Test, for each platform, that the device was linked to the
config entry and the link was removed when the device is
changed in the integration options.
"""
# Configure devices registry
entry_device1 = MockConfigEntry()
entry_device1.add_to_hass(hass)
device1 = device_registry.async_get_or_create(
config_entry_id=entry_device1.entry_id,
identifiers={("test", "identifier_test1")},
connections={("mac", "20:31:32:33:34:01")},
)
entry_device2 = MockConfigEntry()
entry_device2.add_to_hass(hass)
device2 = device_registry.async_get_or_create(
config_entry_id=entry_device1.entry_id,
identifiers={("test", "identifier_test2")},
connections={("mac", "20:31:32:33:34:02")},
)
await hass.async_block_till_done()
device_id1 = device1.id
assert device_id1 is not None
device_id2 = device2.id
assert device_id2 is not None
# Setup the config entry
template_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options=config_entry_options | {"device_id": device_id1},
title="Template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
# Confirm that the config entry has been added to the device 1 registry (current)
current_device = device_registry.async_get(device_id=device_id1)
assert template_config_entry.entry_id in current_device.config_entries
# Change config options to use device 2 and reload the integration
result = await hass.config_entries.options.async_init(
template_config_entry.entry_id
)
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input=config_user_input | {"device_id": device_id2},
)
await hass.async_block_till_done()
# Confirm that the config entry has been removed from the device 1 registry
previous_device = device_registry.async_get(device_id=device_id1)
assert template_config_entry.entry_id not in previous_device.config_entries
# Confirm that the config entry has been added to the device 2 registry (current)
current_device = device_registry.async_get(device_id=device_id2)
assert template_config_entry.entry_id in current_device.config_entries
# Change the config options to remove the device and reload the integration
result = await hass.config_entries.options.async_init(
template_config_entry.entry_id
)
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input=config_user_input,
)
await hass.async_block_till_done()
# Confirm that the config entry has been removed from the device 2 registry
previous_device = device_registry.async_get(device_id=device_id2)
assert template_config_entry.entry_id not in previous_device.config_entries
# Confirm that there is no device with the helper config entry
assert (
dr.async_entries_for_config_entry(
device_registry, template_config_entry.entry_id
)
== []
)
async def test_fail_non_numerical_number_settings(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that non numerical number options causes config entry setup to fail.
Support for non numerical max, min and step was added in HA Core 2024.9.0 and
removed in HA Core 2024.9.1.
"""
options = {
"template_type": "number",
"name": "My template",
"state": "{{ 10 }}",
"min": "{{ 0 }}",
"max": "{{ 100 }}",
"step": "{{ 0.1 }}",
"set_value": {
"action": "input_number.set_value",
"target": {"entity_id": "input_number.test"},
"data": {"value": "{{ value }}"},
},
}
# Setup the config entry
template_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options=options,
title="Template",
)
template_config_entry.add_to_hass(hass)
assert not await hass.config_entries.async_setup(template_config_entry.entry_id)
assert (
"The 'My template' number template needs to be reconfigured, "
"max must be a number, got '{{ 100 }}'" in caplog.text
)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,720 @@
"""The tests for the Template lock platform."""
import pytest
from homeassistant import setup
from homeassistant.components import lock
from homeassistant.components.lock import LockState
from homeassistant.const import (
ATTR_CODE,
ATTR_ENTITY_ID,
STATE_OFF,
STATE_ON,
STATE_OPEN,
STATE_UNAVAILABLE,
)
from homeassistant.core import HomeAssistant, ServiceCall
OPTIMISTIC_LOCK_CONFIG = {
"platform": "template",
"lock": {
"service": "test.automation",
"data_template": {
"action": "lock",
"caller": "{{ this.entity_id }}",
},
},
"unlock": {
"service": "test.automation",
"data_template": {
"action": "unlock",
"caller": "{{ this.entity_id }}",
},
},
"open": {
"service": "test.automation",
"data_template": {
"action": "open",
"caller": "{{ this.entity_id }}",
},
},
}
OPTIMISTIC_CODED_LOCK_CONFIG = {
"platform": "template",
"lock": {
"service": "test.automation",
"data_template": {
"action": "lock",
"caller": "{{ this.entity_id }}",
"code": "{{ code }}",
},
},
"unlock": {
"service": "test.automation",
"data_template": {
"action": "unlock",
"caller": "{{ this.entity_id }}",
"code": "{{ code }}",
},
},
}
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"name": "Test template lock",
"value_template": "{{ states.switch.test_state.state }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_template_state(hass: HomeAssistant) -> None:
"""Test template."""
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("lock.test_template_lock")
assert state.state == LockState.LOCKED
hass.states.async_set("switch.test_state", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("lock.test_template_lock")
assert state.state == LockState.UNLOCKED
hass.states.async_set("switch.test_state", STATE_OPEN)
await hass.async_block_till_done()
state = hass.states.get("lock.test_template_lock")
assert state.state == LockState.OPEN
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"name": "Test lock",
"optimistic": True,
"value_template": "{{ states.switch.test_state.state }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_open_lock_optimistic(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test optimistic open."""
await setup.async_setup_component(hass, "switch", {})
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("lock.test_lock")
assert state.state == LockState.LOCKED
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_OPEN,
{ATTR_ENTITY_ID: "lock.test_lock"},
)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["action"] == "open"
assert calls[0].data["caller"] == "lock.test_lock"
state = hass.states.get("lock.test_lock")
assert state.state == LockState.OPEN
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ 1 == 1 }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_template_state_boolean_on(hass: HomeAssistant) -> None:
"""Test the setting of the state with boolean on."""
state = hass.states.get("lock.template_lock")
assert state.state == LockState.LOCKED
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ 1 == 2 }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_template_state_boolean_off(hass: HomeAssistant) -> None:
"""Test the setting of the state with off."""
state = hass.states.get("lock.template_lock")
assert state.state == LockState.UNLOCKED
@pytest.mark.parametrize(("count", "domain"), [(0, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
"platform": "template",
"value_template": "{% if rubbish %}",
"lock": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"unlock": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
{
"switch": {
"platform": "lock",
"name": "{{%}",
"value_template": "{{ rubbish }",
"lock": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"unlock": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
},
},
{lock.DOMAIN: {"platform": "template", "value_template": "Invalid"}},
{
lock.DOMAIN: {
"platform": "template",
"not_value_template": "{{ states.switch.test_state.state }}",
"lock": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"unlock": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ 1 == 1 }}",
"code_format_template": "{{ rubbish }",
}
},
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ 1 == 1 }}",
"code_format_template": "{% if rubbish %}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_template_syntax_error(hass: HomeAssistant) -> None:
"""Test templating syntax errors don't create entities."""
assert hass.states.async_all("lock") == []
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ 1 + 1 }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_template_static(hass: HomeAssistant) -> None:
"""Test that we allow static templates."""
state = hass.states.get("lock.template_lock")
assert state.state == LockState.UNLOCKED
hass.states.async_set("lock.template_lock", LockState.LOCKED)
await hass.async_block_till_done()
state = hass.states.get("lock.template_lock")
assert state.state == LockState.LOCKED
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_lock_action(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Test lock action."""
await setup.async_setup_component(hass, "switch", {})
hass.states.async_set("switch.test_state", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("lock.template_lock")
assert state.state == LockState.UNLOCKED
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_LOCK,
{ATTR_ENTITY_ID: "lock.template_lock"},
)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["action"] == "lock"
assert calls[0].data["caller"] == "lock.template_lock"
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_unlock_action(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Test unlock action."""
await setup.async_setup_component(hass, "switch", {})
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("lock.template_lock")
assert state.state == LockState.LOCKED
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_UNLOCK,
{ATTR_ENTITY_ID: "lock.template_lock"},
)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["action"] == "unlock"
assert calls[0].data["caller"] == "lock.template_lock"
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_open_action(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Test open action."""
await setup.async_setup_component(hass, "switch", {})
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("lock.template_lock")
assert state.state == LockState.LOCKED
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_OPEN,
{ATTR_ENTITY_ID: "lock.template_lock"},
)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["action"] == "open"
assert calls[0].data["caller"] == "lock.template_lock"
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_CODED_LOCK_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
"code_format_template": "{{ '.+' }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_lock_action_with_code(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test lock action with defined code format and supplied lock code."""
await setup.async_setup_component(hass, "switch", {})
hass.states.async_set("switch.test_state", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("lock.template_lock")
assert state.state == LockState.UNLOCKED
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_LOCK,
{ATTR_ENTITY_ID: "lock.template_lock", ATTR_CODE: "LOCK_CODE"},
)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["action"] == "lock"
assert calls[0].data["caller"] == "lock.template_lock"
assert calls[0].data["code"] == "LOCK_CODE"
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_CODED_LOCK_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
"code_format_template": "{{ '.+' }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_unlock_action_with_code(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test unlock action with code format and supplied unlock code."""
await setup.async_setup_component(hass, "switch", {})
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("lock.template_lock")
assert state.state == LockState.LOCKED
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_UNLOCK,
{ATTR_ENTITY_ID: "lock.template_lock", ATTR_CODE: "UNLOCK_CODE"},
)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["action"] == "unlock"
assert calls[0].data["caller"] == "lock.template_lock"
assert calls[0].data["code"] == "UNLOCK_CODE"
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ 1 == 1 }}",
"code_format_template": "{{ '\\\\d+' }}",
}
},
],
)
@pytest.mark.parametrize(
"test_action",
[
lock.SERVICE_LOCK,
lock.SERVICE_UNLOCK,
],
)
@pytest.mark.usefixtures("start_ha")
async def test_lock_actions_fail_with_invalid_code(
hass: HomeAssistant, calls: list[ServiceCall], test_action
) -> None:
"""Test invalid lock codes."""
await hass.services.async_call(
lock.DOMAIN,
test_action,
{ATTR_ENTITY_ID: "lock.template_lock", ATTR_CODE: "non-number-value"},
)
await hass.services.async_call(
lock.DOMAIN,
test_action,
{ATTR_ENTITY_ID: "lock.template_lock"},
)
await hass.async_block_till_done()
assert len(calls) == 0
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ 1 == 1 }}",
"code_format_template": "{{ 1/0 }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_lock_actions_dont_execute_with_code_template_rendering_error(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test lock code format rendering fails block lock/unlock actions."""
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_LOCK,
{ATTR_ENTITY_ID: "lock.template_lock"},
)
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_UNLOCK,
{ATTR_ENTITY_ID: "lock.template_lock", ATTR_CODE: "any-value"},
)
await hass.async_block_till_done()
assert len(calls) == 0
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize("action", [lock.SERVICE_LOCK, lock.SERVICE_UNLOCK])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_CODED_LOCK_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
"code_format_template": "{{ None }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_actions_with_none_as_codeformat_ignores_code(
hass: HomeAssistant, action, calls: list[ServiceCall]
) -> None:
"""Test lock actions with supplied lock code."""
await setup.async_setup_component(hass, "switch", {})
hass.states.async_set("switch.test_state", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("lock.template_lock")
assert state.state == LockState.UNLOCKED
await hass.services.async_call(
lock.DOMAIN,
action,
{ATTR_ENTITY_ID: "lock.template_lock", ATTR_CODE: "any code"},
)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["action"] == action
assert calls[0].data["caller"] == "lock.template_lock"
assert calls[0].data["code"] == "any code"
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize("action", [lock.SERVICE_LOCK, lock.SERVICE_UNLOCK])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
"code_format_template": "[12]{1",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_actions_with_invalid_regexp_as_codeformat_never_execute(
hass: HomeAssistant, action, calls: list[ServiceCall]
) -> None:
"""Test lock actions don't execute with invalid regexp."""
await setup.async_setup_component(hass, "switch", {})
hass.states.async_set("switch.test_state", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("lock.template_lock")
assert state.state == LockState.UNLOCKED
await hass.services.async_call(
lock.DOMAIN,
action,
{ATTR_ENTITY_ID: "lock.template_lock", ATTR_CODE: "1"},
)
await hass.services.async_call(
lock.DOMAIN,
action,
{ATTR_ENTITY_ID: "lock.template_lock", ATTR_CODE: "x"},
)
await hass.services.async_call(
lock.DOMAIN,
action,
{ATTR_ENTITY_ID: "lock.template_lock"},
)
await hass.async_block_till_done()
assert len(calls) == 0
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ states.input_select.test_state.state }}",
}
},
],
)
@pytest.mark.parametrize(
"test_state", [LockState.UNLOCKING, LockState.LOCKING, LockState.JAMMED]
)
@pytest.mark.usefixtures("start_ha")
async def test_lock_state(hass: HomeAssistant, test_state) -> None:
"""Test value template."""
hass.states.async_set("input_select.test_state", test_state)
await hass.async_block_till_done()
state = hass.states.get("lock.template_lock")
assert state.state == test_state
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ states('switch.test_state') }}",
"availability_template": "{{ is_state('availability_state.state', 'on') }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_available_template_with_entities(hass: HomeAssistant) -> None:
"""Test availability templates with values from other entities."""
# When template returns true..
hass.states.async_set("availability_state.state", STATE_ON)
await hass.async_block_till_done()
# Device State should not be unavailable
assert hass.states.get("lock.template_lock").state != STATE_UNAVAILABLE
# When Availability template returns false
hass.states.async_set("availability_state.state", STATE_OFF)
await hass.async_block_till_done()
# device state should be unavailable
assert hass.states.get("lock.template_lock").state == STATE_UNAVAILABLE
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"value_template": "{{ 1 + 1 }}",
"availability_template": "{{ x - 12 }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_invalid_availability_template_keeps_component_available(
hass: HomeAssistant, caplog_setup_text
) -> None:
"""Test that an invalid availability keeps the device available."""
assert hass.states.get("lock.template_lock").state != STATE_UNAVAILABLE
assert ("UndefinedError: 'x' is undefined") in caplog_setup_text
@pytest.mark.parametrize(("count", "domain"), [(1, lock.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
lock.DOMAIN: {
**OPTIMISTIC_LOCK_CONFIG,
"name": "test_template_lock_01",
"unique_id": "not-so-unique-anymore",
"value_template": "{{ true }}",
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_unique_id(hass: HomeAssistant) -> None:
"""Test unique_id option only creates one lock per id."""
await setup.async_setup_component(
hass,
lock.DOMAIN,
{
"lock": {
**OPTIMISTIC_LOCK_CONFIG,
"name": "test_template_lock_02",
"unique_id": "not-so-unique-anymore",
"value_template": "{{ false }}",
},
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert len(hass.states.async_all("lock")) == 1

View File

@@ -0,0 +1,561 @@
"""The tests for the Template number platform."""
from syrupy.assertion import SnapshotAssertion
from homeassistant import setup
from homeassistant.components.input_number import (
ATTR_VALUE as INPUT_NUMBER_ATTR_VALUE,
DOMAIN as INPUT_NUMBER_DOMAIN,
SERVICE_SET_VALUE as INPUT_NUMBER_SERVICE_SET_VALUE,
)
from homeassistant.components.number import (
ATTR_MAX,
ATTR_MIN,
ATTR_STEP,
ATTR_VALUE as NUMBER_ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE as NUMBER_SERVICE_SET_VALUE,
)
from homeassistant.components.template import DOMAIN
from homeassistant.const import (
ATTR_ICON,
CONF_ENTITY_ID,
CONF_UNIT_OF_MEASUREMENT,
STATE_UNKNOWN,
)
from homeassistant.core import Context, HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import MockConfigEntry, assert_setup_component, async_capture_events
_TEST_NUMBER = "number.template_number"
# Represent for number's value
_VALUE_INPUT_NUMBER = "input_number.value"
# Represent for number's minimum
_MINIMUM_INPUT_NUMBER = "input_number.minimum"
# Represent for number's maximum
_MAXIMUM_INPUT_NUMBER = "input_number.maximum"
# Represent for number's step
_STEP_INPUT_NUMBER = "input_number.step"
# Config for `_VALUE_INPUT_NUMBER`
_VALUE_INPUT_NUMBER_CONFIG = {
"value": {
"min": 0.0,
"max": 100.0,
"name": "Value",
"step": 1.0,
"mode": "slider",
}
}
async def test_setup_config_entry(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
) -> None:
"""Test the config flow."""
template_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"name": "My template",
"template_type": "number",
"state": "{{ 10 }}",
"min": 0,
"max": 100,
"step": 0.1,
"set_value": {
"action": "input_number.set_value",
"target": {"entity_id": "input_number.test"},
"data": {"value": "{{ value }}"},
},
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("number.my_template")
assert state is not None
assert state == snapshot
async def test_missing_optional_config(hass: HomeAssistant) -> None:
"""Test: missing optional template is ok."""
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"number": {
"state": "{{ 4 }}",
"set_value": {"service": "script.set_value"},
"step": "{{ 1 }}",
}
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
_verify(hass, 4, 1, 0.0, 100.0, None)
async def test_missing_required_keys(hass: HomeAssistant) -> None:
"""Test: missing required fields will fail."""
with assert_setup_component(0, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"number": {
"set_value": {"service": "script.set_value"},
}
}
},
)
with assert_setup_component(0, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"number": {
"state": "{{ 4 }}",
}
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all("number") == []
async def test_all_optional_config(hass: HomeAssistant) -> None:
"""Test: including all optional templates is ok."""
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"number": {
"state": "{{ 4 }}",
"set_value": {"service": "script.set_value"},
"min": "{{ 3 }}",
"max": "{{ 5 }}",
"step": "{{ 1 }}",
"unit_of_measurement": "beer",
}
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
_verify(hass, 4, 1, 3, 5, "beer")
async def test_templates_with_entities(
hass: HomeAssistant, entity_registry: er.EntityRegistry, calls: list[ServiceCall]
) -> None:
"""Test templates with values from other entities."""
with assert_setup_component(4, "input_number"):
assert await setup.async_setup_component(
hass,
"input_number",
{
"input_number": {
**_VALUE_INPUT_NUMBER_CONFIG,
"step": {
"min": 0.0,
"max": 100.0,
"name": "Step",
"step": 1.0,
"mode": "slider",
},
"minimum": {
"min": 0.0,
"max": 100.0,
"name": "Minimum",
"step": 1.0,
"mode": "slider",
},
"maximum": {
"min": 0.0,
"max": 100.0,
"name": "Maximum",
"step": 1.0,
"mode": "slider",
},
}
},
)
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"unique_id": "b",
"number": {
"state": f"{{{{ states('{_VALUE_INPUT_NUMBER}') }}}}",
"step": f"{{{{ states('{_STEP_INPUT_NUMBER}') }}}}",
"min": f"{{{{ states('{_MINIMUM_INPUT_NUMBER}') }}}}",
"max": f"{{{{ states('{_MAXIMUM_INPUT_NUMBER}') }}}}",
"set_value": [
{
"service": "input_number.set_value",
"data_template": {
"entity_id": _VALUE_INPUT_NUMBER,
"value": "{{ value }}",
},
},
{
"service": "test.automation",
"data_template": {
"action": "set_value",
"caller": "{{ this.entity_id }}",
"value": "{{ value }}",
},
},
],
"optimistic": True,
"unique_id": "a",
},
}
},
)
hass.states.async_set(_VALUE_INPUT_NUMBER, 4)
hass.states.async_set(_STEP_INPUT_NUMBER, 1)
hass.states.async_set(_MINIMUM_INPUT_NUMBER, 3)
hass.states.async_set(_MAXIMUM_INPUT_NUMBER, 5)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
entry = entity_registry.async_get(_TEST_NUMBER)
assert entry
assert entry.unique_id == "b-a"
_verify(hass, 4, 1, 3, 5, None)
await hass.services.async_call(
INPUT_NUMBER_DOMAIN,
INPUT_NUMBER_SERVICE_SET_VALUE,
{CONF_ENTITY_ID: _VALUE_INPUT_NUMBER, INPUT_NUMBER_ATTR_VALUE: 5},
blocking=True,
)
await hass.async_block_till_done()
_verify(hass, 5, 1, 3, 5, None)
await hass.services.async_call(
INPUT_NUMBER_DOMAIN,
INPUT_NUMBER_SERVICE_SET_VALUE,
{CONF_ENTITY_ID: _STEP_INPUT_NUMBER, INPUT_NUMBER_ATTR_VALUE: 2},
blocking=True,
)
await hass.async_block_till_done()
_verify(hass, 5, 2, 3, 5, None)
await hass.services.async_call(
INPUT_NUMBER_DOMAIN,
INPUT_NUMBER_SERVICE_SET_VALUE,
{CONF_ENTITY_ID: _MINIMUM_INPUT_NUMBER, INPUT_NUMBER_ATTR_VALUE: 2},
blocking=True,
)
await hass.async_block_till_done()
_verify(hass, 5, 2, 2, 5, None)
await hass.services.async_call(
INPUT_NUMBER_DOMAIN,
INPUT_NUMBER_SERVICE_SET_VALUE,
{CONF_ENTITY_ID: _MAXIMUM_INPUT_NUMBER, INPUT_NUMBER_ATTR_VALUE: 6},
blocking=True,
)
await hass.async_block_till_done()
_verify(hass, 5, 2, 2, 6, None)
await hass.services.async_call(
NUMBER_DOMAIN,
NUMBER_SERVICE_SET_VALUE,
{CONF_ENTITY_ID: _TEST_NUMBER, NUMBER_ATTR_VALUE: 2},
blocking=True,
)
_verify(hass, 2, 2, 2, 6, None)
# Check this variable can be used in set_value script
assert len(calls) == 1
assert calls[-1].data["action"] == "set_value"
assert calls[-1].data["caller"] == _TEST_NUMBER
assert calls[-1].data["value"] == 2
async def test_trigger_number(hass: HomeAssistant) -> None:
"""Test trigger based template number."""
events = async_capture_events(hass, "test_number_event")
assert await setup.async_setup_component(
hass,
"template",
{
"template": [
{"invalid": "config"},
# Config after invalid should still be set up
{
"unique_id": "listening-test-event",
"trigger": {"platform": "event", "event_type": "test_event"},
"number": [
{
"name": "Hello Name",
"unique_id": "hello_name-id",
"state": "{{ trigger.event.data.beers_drank }}",
"min": "{{ trigger.event.data.min_beers }}",
"max": "{{ trigger.event.data.max_beers }}",
"step": "{{ trigger.event.data.step }}",
"unit_of_measurement": "beer",
"set_value": {"event": "test_number_event"},
"optimistic": True,
},
],
},
],
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("number.hello_name")
assert state is not None
assert state.state == STATE_UNKNOWN
assert state.attributes["min"] == 0.0
assert state.attributes["max"] == 100.0
assert state.attributes["step"] == 1.0
assert state.attributes["unit_of_measurement"] == "beer"
context = Context()
hass.bus.async_fire(
"test_event",
{
"beers_drank": 3,
"min_beers": 1.0,
"max_beers": 5.0,
"step": 0.5,
},
context=context,
)
await hass.async_block_till_done()
state = hass.states.get("number.hello_name")
assert state is not None
assert state.state == "3.0"
assert state.attributes["min"] == 1.0
assert state.attributes["max"] == 5.0
assert state.attributes["step"] == 0.5
await hass.services.async_call(
NUMBER_DOMAIN,
NUMBER_SERVICE_SET_VALUE,
{CONF_ENTITY_ID: "number.hello_name", NUMBER_ATTR_VALUE: 2},
blocking=True,
)
assert len(events) == 1
assert events[0].event_type == "test_number_event"
def _verify(
hass: HomeAssistant,
expected_value: int,
expected_step: int,
expected_minimum: int,
expected_maximum: int,
expected_unit_of_measurement: str | None,
) -> None:
"""Verify number's state."""
state = hass.states.get(_TEST_NUMBER)
attributes = state.attributes
assert state.state == str(float(expected_value))
assert attributes.get(ATTR_STEP) == float(expected_step)
assert attributes.get(ATTR_MAX) == float(expected_maximum)
assert attributes.get(ATTR_MIN) == float(expected_minimum)
assert attributes.get(CONF_UNIT_OF_MEASUREMENT) == expected_unit_of_measurement
async def test_icon_template(hass: HomeAssistant) -> None:
"""Test template numbers with icon templates."""
with assert_setup_component(1, "input_number"):
assert await setup.async_setup_component(
hass,
"input_number",
{"input_number": _VALUE_INPUT_NUMBER_CONFIG},
)
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"unique_id": "b",
"number": {
"state": f"{{{{ states('{_VALUE_INPUT_NUMBER}') }}}}",
"step": 1,
"min": 0,
"max": 100,
"set_value": {
"service": "input_number.set_value",
"data_template": {
"entity_id": _VALUE_INPUT_NUMBER,
"value": "{{ value }}",
},
},
"icon": "{% if ((states.input_number.value.state or 0) | int) > 50 %}mdi:greater{% else %}mdi:less{% endif %}",
},
}
},
)
hass.states.async_set(_VALUE_INPUT_NUMBER, 49)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get(_TEST_NUMBER)
assert float(state.state) == 49
assert state.attributes[ATTR_ICON] == "mdi:less"
await hass.services.async_call(
INPUT_NUMBER_DOMAIN,
INPUT_NUMBER_SERVICE_SET_VALUE,
{CONF_ENTITY_ID: _VALUE_INPUT_NUMBER, INPUT_NUMBER_ATTR_VALUE: 51},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get(_TEST_NUMBER)
assert float(state.state) == 51
assert state.attributes[ATTR_ICON] == "mdi:greater"
async def test_icon_template_with_trigger(hass: HomeAssistant) -> None:
"""Test template numbers with icon templates."""
with assert_setup_component(1, "input_number"):
assert await setup.async_setup_component(
hass,
"input_number",
{"input_number": _VALUE_INPUT_NUMBER_CONFIG},
)
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"trigger": {"platform": "state", "entity_id": _VALUE_INPUT_NUMBER},
"unique_id": "b",
"number": {
"state": "{{ trigger.to_state.state }}",
"step": 1,
"min": 0,
"max": 100,
"set_value": {
"service": "input_number.set_value",
"data_template": {
"entity_id": _VALUE_INPUT_NUMBER,
"value": "{{ value }}",
},
},
"icon": "{% if ((trigger.to_state.state or 0) | int) > 50 %}mdi:greater{% else %}mdi:less{% endif %}",
},
}
},
)
hass.states.async_set(_VALUE_INPUT_NUMBER, 49)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get(_TEST_NUMBER)
assert float(state.state) == 49
assert state.attributes[ATTR_ICON] == "mdi:less"
await hass.services.async_call(
INPUT_NUMBER_DOMAIN,
INPUT_NUMBER_SERVICE_SET_VALUE,
{CONF_ENTITY_ID: _VALUE_INPUT_NUMBER, INPUT_NUMBER_ATTR_VALUE: 51},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get(_TEST_NUMBER)
assert float(state.state) == 51
assert state.attributes[ATTR_ICON] == "mdi:greater"
async def test_device_id(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for device for number template."""
device_config_entry = MockConfigEntry()
device_config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=device_config_entry.entry_id,
identifiers={("test", "identifier_test")},
connections={("mac", "30:31:32:33:34:35")},
)
await hass.async_block_till_done()
assert device_entry is not None
assert device_entry.id is not None
template_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"name": "My template",
"template_type": "number",
"state": "{{ 10 }}",
"min": 0,
"max": 100,
"step": 0.1,
"set_value": {
"action": "input_number.set_value",
"target": {"entity_id": "input_number.test"},
"data": {"value": "{{ value }}"},
},
"device_id": device_entry.id,
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
template_entity = entity_registry.async_get("number.my_template")
assert template_entity is not None
assert template_entity.device_id == device_entry.id

View File

@@ -0,0 +1,505 @@
"""The tests for the Template select platform."""
from syrupy.assertion import SnapshotAssertion
from homeassistant import setup
from homeassistant.components.input_select import (
ATTR_OPTION as INPUT_SELECT_ATTR_OPTION,
ATTR_OPTIONS as INPUT_SELECT_ATTR_OPTIONS,
DOMAIN as INPUT_SELECT_DOMAIN,
SERVICE_SELECT_OPTION as INPUT_SELECT_SERVICE_SELECT_OPTION,
SERVICE_SET_OPTIONS,
)
from homeassistant.components.select import (
ATTR_OPTION as SELECT_ATTR_OPTION,
ATTR_OPTIONS as SELECT_ATTR_OPTIONS,
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION as SELECT_SERVICE_SELECT_OPTION,
)
from homeassistant.components.template import DOMAIN
from homeassistant.const import ATTR_ICON, CONF_ENTITY_ID, STATE_UNKNOWN
from homeassistant.core import Context, HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import MockConfigEntry, assert_setup_component, async_capture_events
_TEST_SELECT = "select.template_select"
# Represent for select's current_option
_OPTION_INPUT_SELECT = "input_select.option"
async def test_setup_config_entry(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
) -> None:
"""Test the config flow."""
template_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"name": "My template",
"template_type": "select",
"state": "{{ 'on' }}",
"options": "{{ ['off', 'on', 'auto'] }}",
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("select.my_template")
assert state is not None
assert state == snapshot
async def test_missing_optional_config(hass: HomeAssistant) -> None:
"""Test: missing optional template is ok."""
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"select": {
"state": "{{ 'a' }}",
"select_option": {"service": "script.select_option"},
"options": "{{ ['a', 'b'] }}",
}
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
_verify(hass, "a", ["a", "b"])
async def test_multiple_configs(hass: HomeAssistant) -> None:
"""Test: multiple select entities get created."""
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"select": [
{
"state": "{{ 'a' }}",
"select_option": {"service": "script.select_option"},
"options": "{{ ['a', 'b'] }}",
},
{
"state": "{{ 'a' }}",
"select_option": {"service": "script.select_option"},
"options": "{{ ['a', 'b'] }}",
},
]
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
_verify(hass, "a", ["a", "b"])
_verify(hass, "a", ["a", "b"], f"{_TEST_SELECT}_2")
async def test_missing_required_keys(hass: HomeAssistant) -> None:
"""Test: missing required fields will fail."""
with assert_setup_component(0, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"select": {
"select_option": {"service": "script.select_option"},
"options": "{{ ['a', 'b'] }}",
}
}
},
)
with assert_setup_component(0, "select"):
assert await setup.async_setup_component(
hass,
"select",
{
"template": {
"select": {
"state": "{{ 'a' }}",
"select_option": {"service": "script.select_option"},
}
}
},
)
with assert_setup_component(0, "select"):
assert await setup.async_setup_component(
hass,
"select",
{
"template": {
"select": {
"state": "{{ 'a' }}",
"options": "{{ ['a', 'b'] }}",
}
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all("select") == []
async def test_templates_with_entities(
hass: HomeAssistant, entity_registry: er.EntityRegistry, calls: list[ServiceCall]
) -> None:
"""Test templates with values from other entities."""
with assert_setup_component(1, "input_select"):
assert await setup.async_setup_component(
hass,
"input_select",
{
"input_select": {
"option": {
"options": ["a", "b"],
"initial": "a",
"name": "Option",
},
}
},
)
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"unique_id": "b",
"select": {
"state": f"{{{{ states('{_OPTION_INPUT_SELECT}') }}}}",
"options": f"{{{{ state_attr('{_OPTION_INPUT_SELECT}', '{INPUT_SELECT_ATTR_OPTIONS}') }}}}",
"select_option": [
{
"service": "input_select.select_option",
"data_template": {
"entity_id": _OPTION_INPUT_SELECT,
"option": "{{ option }}",
},
},
{
"service": "test.automation",
"data_template": {
"action": "select_option",
"caller": "{{ this.entity_id }}",
"option": "{{ option }}",
},
},
],
"optimistic": True,
"unique_id": "a",
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
entry = entity_registry.async_get(_TEST_SELECT)
assert entry
assert entry.unique_id == "b-a"
_verify(hass, "a", ["a", "b"])
await hass.services.async_call(
INPUT_SELECT_DOMAIN,
INPUT_SELECT_SERVICE_SELECT_OPTION,
{CONF_ENTITY_ID: _OPTION_INPUT_SELECT, INPUT_SELECT_ATTR_OPTION: "b"},
blocking=True,
)
await hass.async_block_till_done()
_verify(hass, "b", ["a", "b"])
await hass.services.async_call(
INPUT_SELECT_DOMAIN,
SERVICE_SET_OPTIONS,
{
CONF_ENTITY_ID: _OPTION_INPUT_SELECT,
INPUT_SELECT_ATTR_OPTIONS: ["a", "b", "c"],
},
blocking=True,
)
await hass.async_block_till_done()
_verify(hass, "b", ["a", "b", "c"])
await hass.services.async_call(
SELECT_DOMAIN,
SELECT_SERVICE_SELECT_OPTION,
{CONF_ENTITY_ID: _TEST_SELECT, SELECT_ATTR_OPTION: "c"},
blocking=True,
)
_verify(hass, "c", ["a", "b", "c"])
# Check this variable can be used in set_value script
assert len(calls) == 1
assert calls[-1].data["action"] == "select_option"
assert calls[-1].data["caller"] == _TEST_SELECT
assert calls[-1].data["option"] == "c"
async def test_trigger_select(hass: HomeAssistant) -> None:
"""Test trigger based template select."""
events = async_capture_events(hass, "test_number_event")
assert await setup.async_setup_component(
hass,
"template",
{
"template": [
{"invalid": "config"},
# Config after invalid should still be set up
{
"unique_id": "listening-test-event",
"trigger": {"platform": "event", "event_type": "test_event"},
"select": [
{
"name": "Hello Name",
"unique_id": "hello_name-id",
"state": "{{ trigger.event.data.beer }}",
"options": "{{ trigger.event.data.beers }}",
"select_option": {"event": "test_number_event"},
"optimistic": True,
},
],
},
],
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("select.hello_name")
assert state is not None
assert state.state == STATE_UNKNOWN
context = Context()
hass.bus.async_fire(
"test_event", {"beer": "duff", "beers": ["duff", "alamo"]}, context=context
)
await hass.async_block_till_done()
state = hass.states.get("select.hello_name")
assert state is not None
assert state.state == "duff"
assert state.attributes["options"] == ["duff", "alamo"]
await hass.services.async_call(
SELECT_DOMAIN,
SELECT_SERVICE_SELECT_OPTION,
{CONF_ENTITY_ID: "select.hello_name", SELECT_ATTR_OPTION: "alamo"},
blocking=True,
)
assert len(events) == 1
assert events[0].event_type == "test_number_event"
def _verify(
hass: HomeAssistant,
expected_current_option: str,
expected_options: list[str],
entity_name: str = _TEST_SELECT,
) -> None:
"""Verify select's state."""
state = hass.states.get(entity_name)
attributes = state.attributes
assert state.state == str(expected_current_option)
assert attributes.get(SELECT_ATTR_OPTIONS) == expected_options
async def test_template_icon_with_entities(hass: HomeAssistant) -> None:
"""Test templates with values from other entities."""
with assert_setup_component(1, "input_select"):
assert await setup.async_setup_component(
hass,
"input_select",
{
"input_select": {
"option": {
"options": ["a", "b"],
"initial": "a",
"name": "Option",
},
}
},
)
with assert_setup_component(1, "template"):
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"unique_id": "b",
"select": {
"state": f"{{{{ states('{_OPTION_INPUT_SELECT}') }}}}",
"options": f"{{{{ state_attr('{_OPTION_INPUT_SELECT}', '{INPUT_SELECT_ATTR_OPTIONS}') }}}}",
"select_option": {
"service": "input_select.select_option",
"data": {
"entity_id": _OPTION_INPUT_SELECT,
"option": "{{ option }}",
},
},
"optimistic": True,
"unique_id": "a",
"icon": f"{{% if (states('{_OPTION_INPUT_SELECT}') == 'a') %}}mdi:greater{{% else %}}mdi:less{{% endif %}}",
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get(_TEST_SELECT)
assert state.state == "a"
assert state.attributes[ATTR_ICON] == "mdi:greater"
await hass.services.async_call(
INPUT_SELECT_DOMAIN,
INPUT_SELECT_SERVICE_SELECT_OPTION,
{CONF_ENTITY_ID: _OPTION_INPUT_SELECT, INPUT_SELECT_ATTR_OPTION: "b"},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get(_TEST_SELECT)
assert state.state == "b"
assert state.attributes[ATTR_ICON] == "mdi:less"
async def test_template_icon_with_trigger(hass: HomeAssistant) -> None:
"""Test trigger based template select."""
with assert_setup_component(1, "input_select"):
assert await setup.async_setup_component(
hass,
"input_select",
{
"input_select": {
"option": {
"options": ["a", "b"],
"initial": "a",
"name": "Option",
},
}
},
)
assert await setup.async_setup_component(
hass,
"template",
{
"template": {
"trigger": {"platform": "state", "entity_id": _OPTION_INPUT_SELECT},
"select": {
"unique_id": "b",
"state": "{{ trigger.to_state.state }}",
"options": f"{{{{ state_attr('{_OPTION_INPUT_SELECT}', '{INPUT_SELECT_ATTR_OPTIONS}') }}}}",
"select_option": {
"service": "input_select.select_option",
"data": {
"entity_id": _OPTION_INPUT_SELECT,
"option": "{{ option }}",
},
},
"optimistic": True,
"icon": "{% if (trigger.to_state.state or '') == 'a' %}mdi:greater{% else %}mdi:less{% endif %}",
},
},
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
await hass.services.async_call(
INPUT_SELECT_DOMAIN,
INPUT_SELECT_SERVICE_SELECT_OPTION,
{CONF_ENTITY_ID: _OPTION_INPUT_SELECT, INPUT_SELECT_ATTR_OPTION: "b"},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get(_TEST_SELECT)
assert state is not None
assert state.state == "b"
assert state.attributes[ATTR_ICON] == "mdi:less"
await hass.services.async_call(
INPUT_SELECT_DOMAIN,
INPUT_SELECT_SERVICE_SELECT_OPTION,
{CONF_ENTITY_ID: _OPTION_INPUT_SELECT, INPUT_SELECT_ATTR_OPTION: "a"},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get(_TEST_SELECT)
assert state.state == "a"
assert state.attributes[ATTR_ICON] == "mdi:greater"
async def test_device_id(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for device for select template."""
device_config_entry = MockConfigEntry()
device_config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=device_config_entry.entry_id,
identifiers={("test", "identifier_test")},
connections={("mac", "30:31:32:33:34:35")},
)
await hass.async_block_till_done()
assert device_entry is not None
assert device_entry.id is not None
template_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"name": "My template",
"template_type": "select",
"state": "{{ 'on' }}",
"options": "{{ ['off', 'on', 'auto'] }}",
"device_id": device_entry.id,
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
template_entity = entity_registry.async_get("select.my_template")
assert template_entity is not None
assert template_entity.device_id == device_entry.id

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,736 @@
"""The tests for the Template switch platform."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant import setup
from homeassistant.components import template
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
)
from homeassistant.core import CoreState, HomeAssistant, ServiceCall, State
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import (
MockConfigEntry,
assert_setup_component,
mock_component,
mock_restore_cache,
)
OPTIMISTIC_SWITCH_CONFIG = {
"turn_on": {
"service": "test.automation",
"data_template": {
"action": "turn_on",
"caller": "{{ this.entity_id }}",
},
},
"turn_off": {
"service": "test.automation",
"data_template": {
"action": "turn_off",
"caller": "{{ this.entity_id }}",
},
},
}
async def test_setup_config_entry(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
) -> None:
"""Test the config flow."""
hass.states.async_set(
"switch.one",
"on",
{},
)
template_config_entry = MockConfigEntry(
data={},
domain=template.DOMAIN,
options={
"name": "My template",
"value_template": "{{ states('switch.one') }}",
"template_type": SWITCH_DOMAIN,
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("switch.my_template")
assert state is not None
assert state == snapshot
async def test_template_state_text(hass: HomeAssistant) -> None:
"""Test the state text of a template."""
with assert_setup_component(1, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_ON
hass.states.async_set("switch.test_state", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_OFF
async def test_template_state_boolean_on(hass: HomeAssistant) -> None:
"""Test the setting of the state with boolean on."""
with assert_setup_component(1, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{{ 1 == 1 }}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_ON
async def test_template_state_boolean_off(hass: HomeAssistant) -> None:
"""Test the setting of the state with off."""
with assert_setup_component(1, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{{ 1 == 2 }}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_OFF
async def test_icon_template(hass: HomeAssistant) -> None:
"""Test icon template."""
with assert_setup_component(1, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
"icon_template": (
"{% if states.switch.test_state.state %}"
"mdi:check"
"{% endif %}"
),
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.attributes.get("icon") == ""
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.attributes["icon"] == "mdi:check"
async def test_entity_picture_template(hass: HomeAssistant) -> None:
"""Test entity_picture template."""
with assert_setup_component(1, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
"entity_picture_template": (
"{% if states.switch.test_state.state %}"
"/local/switch.png"
"{% endif %}"
),
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.attributes.get("entity_picture") == ""
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.attributes["entity_picture"] == "/local/switch.png"
async def test_template_syntax_error(hass: HomeAssistant) -> None:
"""Test templating syntax error."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{% if rubbish %}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all("switch") == []
async def test_invalid_name_does_not_create(hass: HomeAssistant) -> None:
"""Test invalid name."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test INVALID switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{{ rubbish }",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all("switch") == []
async def test_invalid_switch_does_not_create(hass: HomeAssistant) -> None:
"""Test invalid switch."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {"test_template_switch": "Invalid"},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all("switch") == []
async def test_no_switches_does_not_create(hass: HomeAssistant) -> None:
"""Test if there are no switches no creation."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass, "switch", {"switch": {"platform": "template"}}
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all("switch") == []
async def test_missing_on_does_not_create(hass: HomeAssistant) -> None:
"""Test missing on."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ states.switch.test_state.state }}",
"not_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all("switch") == []
async def test_missing_off_does_not_create(hass: HomeAssistant) -> None:
"""Test missing off."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ states.switch.test_state.state }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"not_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all("switch") == []
async def test_on_action(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Test on action."""
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("switch.test_state", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.test_template_switch"},
blocking=True,
)
assert len(calls) == 1
assert calls[-1].data["action"] == "turn_on"
assert calls[-1].data["caller"] == "switch.test_template_switch"
async def test_on_action_optimistic(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test on action in optimistic mode."""
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
}
},
}
},
)
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("switch.test_template_switch", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.test_template_switch"},
blocking=True,
)
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_ON
assert len(calls) == 1
assert calls[-1].data["action"] == "turn_on"
assert calls[-1].data["caller"] == "switch.test_template_switch"
async def test_off_action(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Test off action."""
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{{ states.switch.test_state.state }}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.test_template_switch"},
blocking=True,
)
assert len(calls) == 1
assert calls[-1].data["action"] == "turn_off"
assert calls[-1].data["caller"] == "switch.test_template_switch"
async def test_off_action_optimistic(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test off action in optimistic mode."""
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
}
},
}
},
)
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("switch.test_template_switch", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.test_template_switch"},
blocking=True,
)
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_OFF
assert len(calls) == 1
assert calls[-1].data["action"] == "turn_off"
assert calls[-1].data["caller"] == "switch.test_template_switch"
async def test_restore_state(hass: HomeAssistant) -> None:
"""Test state restoration."""
mock_restore_cache(
hass,
(
State("switch.s1", STATE_ON),
State("switch.s2", STATE_OFF),
),
)
hass.set_state(CoreState.starting)
mock_component(hass, "recorder")
await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"s1": {
**OPTIMISTIC_SWITCH_CONFIG,
},
"s2": {
**OPTIMISTIC_SWITCH_CONFIG,
},
},
}
},
)
await hass.async_block_till_done()
state = hass.states.get("switch.s1")
assert state
assert state.state == STATE_ON
state = hass.states.get("switch.s2")
assert state
assert state.state == STATE_OFF
async def test_available_template_with_entities(hass: HomeAssistant) -> None:
"""Test availability templates with values from other entities."""
await setup.async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{{ 1 == 1 }}",
"availability_template": (
"{{ is_state('availability_state.state', 'on') }}"
),
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("availability_state.state", STATE_ON)
await hass.async_block_till_done()
assert hass.states.get("switch.test_template_switch").state != STATE_UNAVAILABLE
hass.states.async_set("availability_state.state", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("switch.test_template_switch").state == STATE_UNAVAILABLE
async def test_invalid_availability_template_keeps_component_available(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that an invalid availability keeps the device available."""
await setup.async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
**OPTIMISTIC_SWITCH_CONFIG,
"value_template": "{{ true }}",
"availability_template": "{{ x - 12 }}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.get("switch.test_template_switch").state != STATE_UNAVAILABLE
assert "UndefinedError: 'x' is undefined" in caplog.text
async def test_unique_id(hass: HomeAssistant) -> None:
"""Test unique_id option only creates one switch per id."""
await setup.async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch_01": {
**OPTIMISTIC_SWITCH_CONFIG,
"unique_id": "not-so-unique-anymore",
"value_template": "{{ true }}",
},
"test_template_switch_02": {
**OPTIMISTIC_SWITCH_CONFIG,
"unique_id": "not-so-unique-anymore",
"value_template": "{{ false }}",
},
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert len(hass.states.async_all("switch")) == 1
async def test_device_id(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for device for Template."""
device_config_entry = MockConfigEntry()
device_config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=device_config_entry.entry_id,
identifiers={("test", "identifier_test")},
connections={("mac", "30:31:32:33:34:35")},
)
await hass.async_block_till_done()
assert device_entry is not None
assert device_entry.id is not None
template_config_entry = MockConfigEntry(
data={},
domain=template.DOMAIN,
options={
"name": "My template",
"value_template": "{{ true }}",
"template_type": "switch",
"device_id": device_entry.id,
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
template_entity = entity_registry.async_get("switch.my_template")
assert template_entity is not None
assert template_entity.device_id == device_entry.id

View File

@@ -0,0 +1,24 @@
"""Test template entity."""
import pytest
from homeassistant.components.template import template_entity
from homeassistant.core import HomeAssistant
from homeassistant.helpers import template
async def test_template_entity_requires_hass_set(hass: HomeAssistant) -> None:
"""Test template entity requires hass to be set before accepting templates."""
entity = template_entity.TemplateEntity(hass)
with pytest.raises(ValueError, match="^hass cannot be None"):
entity.add_template_attribute("_hello", template.Template("Hello"))
entity.hass = object()
with pytest.raises(ValueError, match="^template.hass cannot be None"):
entity.add_template_attribute("_hello", template.Template("Hello", None))
tpl_with_hass = template.Template("Hello", entity.hass)
entity.add_template_attribute("_hello", tpl_with_hass)
assert len(entity._template_attrs.get(tpl_with_hass, [])) == 1

View File

@@ -0,0 +1,870 @@
"""The tests for the Template automation."""
from datetime import timedelta
from unittest import mock
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components import automation
from homeassistant.components.template import trigger as template_trigger
from homeassistant.const import (
ATTR_ENTITY_ID,
ENTITY_MATCH_ALL,
SERVICE_TURN_OFF,
STATE_UNAVAILABLE,
)
from homeassistant.core import Context, HomeAssistant, ServiceCall, callback
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from tests.common import async_fire_time_changed, mock_component
@pytest.fixture(autouse=True)
def setup_comp(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Initialize components."""
mock_component(hass, "group")
hass.states.async_set("test.entity", "hello")
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": (
'{{ states.test.entity.state == "world" and true }}'
),
},
"action": {
"service": "test.automation",
"data_template": {"id": "{{ trigger.id}}"},
},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_fires_on_change_bool(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on boolean change."""
assert len(calls) == 0
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 1
await hass.services.async_call(
automation.DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: ENTITY_MATCH_ALL},
blocking=True,
)
hass.states.async_set("test.entity", "planet")
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["id"] == 0
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
("config", "call_setup"),
[
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": (
'{{ states.test.entity.state == "world" and "true" }}'
),
},
"action": {"service": "test.automation"},
}
},
[(1, "world", False)],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": (
'{{ states.test.entity.state == "world" and "TrUE" }}'
),
},
"action": {"service": "test.automation"},
}
},
[(1, "world", False)],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": (
'{{ states.test.entity.state == "world" and false }}'
),
},
"action": {"service": "test.automation"},
}
},
[(0, "world", False)],
),
(
{
automation.DOMAIN: {
"trigger": {"platform": "template", "value_template": "true"},
"action": {"service": "test.automation"},
}
},
[(0, "world", False)],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ "Anything other than true is false." }}',
},
"action": {"service": "test.automation"},
}
},
[(0, "world", False)],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ is_state("test.entity", "world") }}',
},
"action": {"service": "test.automation"},
}
},
[(1, "world", False)],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ is_state("test.entity", "hello") }}',
},
"action": {"service": "test.automation"},
}
},
[(0, "world", False)],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ states.test.entity.state == 'world' }}",
},
"action": {"service": "test.automation"},
}
},
[(1, "world", False), (1, "world", False)],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ states.test.entity.state == "hello" }}',
},
"action": {"service": "test.automation"},
},
},
[(0, "world", True)],
),
(
{
automation.DOMAIN: {
"trigger_variables": {"entity": "test.entity"},
"trigger": {
"platform": "template",
"value_template": (
'{{ is_state(entity|default("test.entity2"), "hello") }}'
),
},
"action": {"service": "test.automation"},
},
},
[(0, "hello", True), (0, "goodbye", True), (1, "hello", True)],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": """{%- if is_state("test.entity", "world") -%}
true
{%- else -%}
false
{%- endif -%}""",
},
"action": {"service": "test.automation"},
}
},
[(0, "worldz", False), (0, "hello", True)],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ not is_state("test.entity", "world") }}',
},
"action": {"service": "test.automation"},
}
},
[
(0, "world", False),
(1, "home", False),
(1, "work", False),
(1, "not_home", False),
(1, "world", False),
(2, "home", False),
],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ xyz | round(0) }}",
},
"action": {"service": "test.automation"},
}
},
[(0, "world", False)],
),
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
"for": {"seconds": 0},
},
"action": {"service": "test.automation"},
}
},
[(1, "world", False)],
),
(
{
automation.DOMAIN: {
"trigger": {"platform": "template", "value_template": "{{ true }}"},
"action": {"service": "test.automation"},
}
},
[(0, "hello", False)],
),
],
)
@pytest.mark.usefixtures("start_ha")
async def test_general(
hass: HomeAssistant, call_setup, calls: list[ServiceCall]
) -> None:
"""Test for firing on change."""
assert len(calls) == 0
for call_len, call_name, call_force in call_setup:
hass.states.async_set("test.entity", call_name, force_update=call_force)
await hass.async_block_till_done()
assert len(calls) == call_len
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
("config", "call_setup"),
[
(
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": (
"{{ 84 / states.test.number.state|int == 42 }}"
),
},
"action": {"service": "test.automation"},
}
},
[
(0, "1"),
(1, "2"),
(1, "0"),
(1, "2"),
],
),
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_not_fires_because_fail(
hass: HomeAssistant, call_setup, calls: list[ServiceCall]
) -> None:
"""Test for not firing after TemplateError."""
assert len(calls) == 0
for call_len, call_number in call_setup:
hass.states.async_set("test.number", call_number)
await hass.async_block_till_done()
assert len(calls) == call_len
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ is_state("test.entity", "world") }}',
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"{{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_fires_on_change_with_template_advanced(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with template advanced."""
context = Context()
await hass.async_block_till_done()
hass.states.async_set("test.entity", "world", context=context)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].context.parent_id == context.id
assert calls[0].data["some"] == "template - test.entity - hello - world - None"
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": [
{
"condition": "template",
"value_template": '{{ is_state("test.entity", "world") }}',
}
],
"action": {"service": "test.automation"},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_action(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Test for firing if action."""
# Condition is not true yet
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(calls) == 0
# Change condition to true, but it shouldn't be triggered yet
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
# Condition is true and event is triggered
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(calls) == 1
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {"platform": "template", "value_template": "{{ "},
"action": {"service": "test.automation"},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_fires_on_change_with_bad_template(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with bad template."""
assert hass.states.get("automation.automation_0").state == STATE_UNAVAILABLE
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ states.test.entity.state == 'world' }}",
},
"action": [
{"event": "test_event"},
{"wait_template": "{{ is_state(trigger.entity_id, 'hello') }}"},
{
"service": "test.automation",
"data_template": {
"some": (
"{{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
],
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_wait_template_with_trigger(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test using wait template with 'trigger.entity_id'."""
await hass.async_block_till_done()
@callback
def event_handler(event):
hass.states.async_set("test.entity", "hello")
hass.bus.async_listen_once("test_event", event_handler)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["some"] == "template - test.entity - hello - world - None"
async def test_if_fires_on_change_with_for(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with for."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
"for": {"seconds": 5},
},
"action": {"service": "test.automation"},
}
},
)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ is_state("test.entity", "world") }}',
"for": {"seconds": 5},
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"{{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_fires_on_change_with_for_advanced(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with for advanced."""
context = Context()
await hass.async_block_till_done()
hass.states.async_set("test.entity", "world", context=context)
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].context.parent_id == context.id
assert calls[0].data["some"] == "template - test.entity - hello - world - 0:00:05"
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ is_state("test.entity", "world") }}',
"for": {"seconds": 0},
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"{{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_fires_on_change_with_for_0_advanced(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with for: 0 advanced."""
context = Context()
await hass.async_block_till_done()
hass.states.async_set("test.entity", "world", context=context)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].context.parent_id == context.id
assert calls[0].data["some"] == "template - test.entity - hello - world - 0:00:00"
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
"for": 5,
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"{{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_fires_on_change_with_for_2(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with for."""
context = Context()
hass.states.async_set("test.entity", "world", context=context)
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].context.parent_id == context.id
assert calls[0].data["some"] == "template - test.entity - hello - world - 0:00:05"
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
"for": {"seconds": 5},
},
"action": {"service": "test.automation"},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_not_fires_on_change_with_for(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with for."""
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=4))
await hass.async_block_till_done()
assert len(calls) == 0
hass.states.async_set("test.entity", "hello")
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=6))
await hass.async_block_till_done()
assert len(calls) == 0
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
"for": {"seconds": 5},
},
"action": {"service": "test.automation"},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_not_fires_when_turned_off_with_for(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with for."""
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=4))
await hass.async_block_till_done()
assert len(calls) == 0
await hass.services.async_call(
automation.DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: ENTITY_MATCH_ALL},
blocking=True,
)
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=6))
await hass.async_block_till_done()
assert len(calls) == 0
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
"for": {"seconds": "{{ 5 }}"},
},
"action": {"service": "test.automation"},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_fires_on_change_with_for_template_1(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with for template."""
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
"for": "{{ 5 }}",
},
"action": {"service": "test.automation"},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_fires_on_change_with_for_template_2(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with for template."""
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
"for": "00:00:{{ 5 }}",
},
"action": {"service": "test.automation"},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_fires_on_change_with_for_template_3(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with for template."""
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
"for": {"seconds": "{{ five }}"},
},
"action": {"service": "test.automation"},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_invalid_for_template_1(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for invalid for template."""
with mock.patch.object(template_trigger, "_LOGGER") as mock_logger:
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert mock_logger.error.called
async def test_if_fires_on_time_change(
hass: HomeAssistant, freezer: FrozenDateTimeFactory, calls: list[ServiceCall]
) -> None:
"""Test for firing on time changes."""
start_time = dt_util.utcnow() + timedelta(hours=24)
time_that_will_not_match_right_away = start_time.replace(minute=1, second=0)
freezer.move_to(time_that_will_not_match_right_away)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ utcnow().minute % 2 == 0 }}",
},
"action": {"service": "test.automation"},
}
},
)
await hass.async_block_till_done()
assert len(calls) == 0
# Trigger once (match template)
first_time = start_time.replace(minute=2, second=0)
freezer.move_to(first_time)
async_fire_time_changed(hass, first_time)
await hass.async_block_till_done()
assert len(calls) == 1
# Trigger again (match template)
second_time = start_time.replace(minute=4, second=0)
freezer.move_to(second_time)
async_fire_time_changed(hass, second_time)
await hass.async_block_till_done()
await hass.async_block_till_done()
assert len(calls) == 1
# Trigger again (do not match template)
third_time = start_time.replace(minute=5, second=0)
freezer.move_to(third_time)
async_fire_time_changed(hass, third_time)
await hass.async_block_till_done()
await hass.async_block_till_done()
assert len(calls) == 1
# Trigger again (match template)
forth_time = start_time.replace(minute=8, second=0)
freezer.move_to(forth_time)
async_fire_time_changed(hass, forth_time)
await hass.async_block_till_done()
await hass.async_block_till_done()
assert len(calls) == 2

View File

@@ -0,0 +1,699 @@
"""The tests for the Template vacuum platform."""
import pytest
from homeassistant import setup
from homeassistant.components.vacuum import ATTR_BATTERY_LEVEL, VacuumActivity
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_component import async_update_entity
from tests.common import assert_setup_component
from tests.components.vacuum import common
_TEST_VACUUM = "vacuum.test_vacuum"
_STATE_INPUT_SELECT = "input_select.state"
_SPOT_CLEANING_INPUT_BOOLEAN = "input_boolean.spot_cleaning"
_LOCATING_INPUT_BOOLEAN = "input_boolean.locating"
_FAN_SPEED_INPUT_SELECT = "input_select.fan_speed"
_BATTERY_LEVEL_INPUT_NUMBER = "input_number.battery_level"
@pytest.mark.parametrize(("count", "domain"), [(1, "vacuum")])
@pytest.mark.parametrize(
("parm1", "parm2", "config"),
[
(
STATE_UNKNOWN,
None,
{
"vacuum": {
"platform": "template",
"vacuums": {
"test_vacuum": {"start": {"service": "script.vacuum_start"}}
},
}
},
),
(
VacuumActivity.CLEANING,
100,
{
"vacuum": {
"platform": "template",
"vacuums": {
"test_vacuum": {
"value_template": "{{ 'cleaning' }}",
"battery_level_template": "{{ 100 }}",
"start": {"service": "script.vacuum_start"},
}
},
}
},
),
(
STATE_UNKNOWN,
None,
{
"vacuum": {
"platform": "template",
"vacuums": {
"test_vacuum": {
"value_template": "{{ 'abc' }}",
"battery_level_template": "{{ 101 }}",
"start": {"service": "script.vacuum_start"},
}
},
}
},
),
(
STATE_UNKNOWN,
None,
{
"vacuum": {
"platform": "template",
"vacuums": {
"test_vacuum": {
"value_template": "{{ this_function_does_not_exist() }}",
"battery_level_template": "{{ this_function_does_not_exist() }}",
"fan_speed_template": "{{ this_function_does_not_exist() }}",
"start": {"service": "script.vacuum_start"},
}
},
}
},
),
],
)
@pytest.mark.usefixtures("start_ha")
async def test_valid_configs(hass: HomeAssistant, count, parm1, parm2) -> None:
"""Test: configs."""
assert len(hass.states.async_all("vacuum")) == count
_verify(hass, parm1, parm2)
@pytest.mark.parametrize(("count", "domain"), [(0, "vacuum")])
@pytest.mark.parametrize(
"config",
[
{
"vacuum": {
"platform": "template",
"vacuums": {"test_vacuum": {"value_template": "{{ 'on' }}"}},
}
},
{
"platform": "template",
"vacuums": {"test_vacuum": {"start": {"service": "script.vacuum_start"}}},
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_invalid_configs(hass: HomeAssistant, count) -> None:
"""Test: configs."""
assert len(hass.states.async_all("vacuum")) == count
@pytest.mark.parametrize(
("count", "domain", "config"),
[
(
1,
"vacuum",
{
"vacuum": {
"platform": "template",
"vacuums": {
"test_vacuum": {
"value_template": "{{ states('input_select.state') }}",
"battery_level_template": "{{ states('input_number.battery_level') }}",
"start": {"service": "script.vacuum_start"},
}
},
}
},
)
],
)
@pytest.mark.usefixtures("start_ha")
async def test_templates_with_entities(hass: HomeAssistant) -> None:
"""Test templates with values from other entities."""
_verify(hass, STATE_UNKNOWN, None)
hass.states.async_set(_STATE_INPUT_SELECT, VacuumActivity.CLEANING)
hass.states.async_set(_BATTERY_LEVEL_INPUT_NUMBER, 100)
await hass.async_block_till_done()
_verify(hass, VacuumActivity.CLEANING, 100)
@pytest.mark.parametrize(
("count", "domain", "config"),
[
(
1,
"vacuum",
{
"vacuum": {
"platform": "template",
"vacuums": {
"test_template_vacuum": {
"availability_template": "{{ is_state('availability_state.state', 'on') }}",
"start": {"service": "script.vacuum_start"},
}
},
}
},
)
],
)
@pytest.mark.usefixtures("start_ha")
async def test_available_template_with_entities(hass: HomeAssistant) -> None:
"""Test availability templates with values from other entities."""
# When template returns true..
hass.states.async_set("availability_state.state", STATE_ON)
await hass.async_block_till_done()
# Device State should not be unavailable
assert hass.states.get("vacuum.test_template_vacuum").state != STATE_UNAVAILABLE
# When Availability template returns false
hass.states.async_set("availability_state.state", STATE_OFF)
await hass.async_block_till_done()
# device state should be unavailable
assert hass.states.get("vacuum.test_template_vacuum").state == STATE_UNAVAILABLE
@pytest.mark.parametrize(
("count", "domain", "config"),
[
(
1,
"vacuum",
{
"vacuum": {
"platform": "template",
"vacuums": {
"test_template_vacuum": {
"availability_template": "{{ x - 12 }}",
"start": {"service": "script.vacuum_start"},
}
},
}
},
)
],
)
@pytest.mark.usefixtures("start_ha")
async def test_invalid_availability_template_keeps_component_available(
hass: HomeAssistant, caplog_setup_text
) -> None:
"""Test that an invalid availability keeps the device available."""
assert hass.states.get("vacuum.test_template_vacuum") != STATE_UNAVAILABLE
assert "UndefinedError: 'x' is undefined" in caplog_setup_text
@pytest.mark.parametrize(
("count", "domain", "config"),
[
(
1,
"vacuum",
{
"vacuum": {
"platform": "template",
"vacuums": {
"test_template_vacuum": {
"value_template": "{{ 'cleaning' }}",
"start": {"service": "script.vacuum_start"},
"attribute_templates": {
"test_attribute": "It {{ states.sensor.test_state.state }}."
},
}
},
}
},
)
],
)
@pytest.mark.usefixtures("start_ha")
async def test_attribute_templates(hass: HomeAssistant) -> None:
"""Test attribute_templates template."""
state = hass.states.get("vacuum.test_template_vacuum")
assert state.attributes["test_attribute"] == "It ."
hass.states.async_set("sensor.test_state", "Works")
await hass.async_block_till_done()
await async_update_entity(hass, "vacuum.test_template_vacuum")
state = hass.states.get("vacuum.test_template_vacuum")
assert state.attributes["test_attribute"] == "It Works."
@pytest.mark.parametrize(
("count", "domain", "config"),
[
(
1,
"vacuum",
{
"vacuum": {
"platform": "template",
"vacuums": {
"invalid_template": {
"value_template": "{{ states('input_select.state') }}",
"start": {"service": "script.vacuum_start"},
"attribute_templates": {
"test_attribute": "{{ this_function_does_not_exist() }}"
},
}
},
}
},
)
],
)
@pytest.mark.usefixtures("start_ha")
async def test_invalid_attribute_template(
hass: HomeAssistant, caplog_setup_text
) -> None:
"""Test that errors are logged if rendering template fails."""
assert len(hass.states.async_all("vacuum")) == 1
assert "test_attribute" in caplog_setup_text
assert "TemplateError" in caplog_setup_text
@pytest.mark.parametrize(
("count", "domain", "config"),
[
(
1,
"vacuum",
{
"vacuum": {
"platform": "template",
"vacuums": {
"test_template_vacuum_01": {
"unique_id": "not-so-unique-anymore",
"value_template": "{{ true }}",
"start": {"service": "script.vacuum_start"},
},
"test_template_vacuum_02": {
"unique_id": "not-so-unique-anymore",
"value_template": "{{ false }}",
"start": {"service": "script.vacuum_start"},
},
},
}
},
),
],
)
@pytest.mark.usefixtures("start_ha")
async def test_unique_id(hass: HomeAssistant) -> None:
"""Test unique_id option only creates one vacuum per id."""
assert len(hass.states.async_all("vacuum")) == 1
async def test_unused_services(hass: HomeAssistant) -> None:
"""Test calling unused services raises."""
await _register_basic_vacuum(hass)
# Pause vacuum
with pytest.raises(HomeAssistantError):
await common.async_pause(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# Stop vacuum
with pytest.raises(HomeAssistantError):
await common.async_stop(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# Return vacuum to base
with pytest.raises(HomeAssistantError):
await common.async_return_to_base(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# Spot cleaning
with pytest.raises(HomeAssistantError):
await common.async_clean_spot(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# Locate vacuum
with pytest.raises(HomeAssistantError):
await common.async_locate(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# Set fan's speed
with pytest.raises(HomeAssistantError):
await common.async_set_fan_speed(hass, "medium", _TEST_VACUUM)
await hass.async_block_till_done()
_verify(hass, STATE_UNKNOWN, None)
async def test_state_services(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Test state services."""
await _register_components(hass)
# Start vacuum
await common.async_start(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# verify
assert hass.states.get(_STATE_INPUT_SELECT).state == VacuumActivity.CLEANING
_verify(hass, VacuumActivity.CLEANING, None)
assert len(calls) == 1
assert calls[-1].data["action"] == "start"
assert calls[-1].data["caller"] == _TEST_VACUUM
# Pause vacuum
await common.async_pause(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# verify
assert hass.states.get(_STATE_INPUT_SELECT).state == VacuumActivity.PAUSED
_verify(hass, VacuumActivity.PAUSED, None)
assert len(calls) == 2
assert calls[-1].data["action"] == "pause"
assert calls[-1].data["caller"] == _TEST_VACUUM
# Stop vacuum
await common.async_stop(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# verify
assert hass.states.get(_STATE_INPUT_SELECT).state == VacuumActivity.IDLE
_verify(hass, VacuumActivity.IDLE, None)
assert len(calls) == 3
assert calls[-1].data["action"] == "stop"
assert calls[-1].data["caller"] == _TEST_VACUUM
# Return vacuum to base
await common.async_return_to_base(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# verify
assert hass.states.get(_STATE_INPUT_SELECT).state == VacuumActivity.RETURNING
_verify(hass, VacuumActivity.RETURNING, None)
assert len(calls) == 4
assert calls[-1].data["action"] == "return_to_base"
assert calls[-1].data["caller"] == _TEST_VACUUM
async def test_clean_spot_service(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test clean spot service."""
await _register_components(hass)
# Clean spot
await common.async_clean_spot(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# verify
assert hass.states.get(_SPOT_CLEANING_INPUT_BOOLEAN).state == STATE_ON
assert len(calls) == 1
assert calls[-1].data["action"] == "clean_spot"
assert calls[-1].data["caller"] == _TEST_VACUUM
async def test_locate_service(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Test locate service."""
await _register_components(hass)
# Locate vacuum
await common.async_locate(hass, _TEST_VACUUM)
await hass.async_block_till_done()
# verify
assert hass.states.get(_LOCATING_INPUT_BOOLEAN).state == STATE_ON
assert len(calls) == 1
assert calls[-1].data["action"] == "locate"
assert calls[-1].data["caller"] == _TEST_VACUUM
async def test_set_fan_speed(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Test set valid fan speed."""
await _register_components(hass)
# Set vacuum's fan speed to high
await common.async_set_fan_speed(hass, "high", _TEST_VACUUM)
await hass.async_block_till_done()
# verify
assert hass.states.get(_FAN_SPEED_INPUT_SELECT).state == "high"
assert len(calls) == 1
assert calls[-1].data["action"] == "set_fan_speed"
assert calls[-1].data["caller"] == _TEST_VACUUM
assert calls[-1].data["option"] == "high"
# Set fan's speed to medium
await common.async_set_fan_speed(hass, "medium", _TEST_VACUUM)
await hass.async_block_till_done()
# verify
assert hass.states.get(_FAN_SPEED_INPUT_SELECT).state == "medium"
assert len(calls) == 2
assert calls[-1].data["action"] == "set_fan_speed"
assert calls[-1].data["caller"] == _TEST_VACUUM
assert calls[-1].data["option"] == "medium"
async def test_set_invalid_fan_speed(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test set invalid fan speed when fan has valid speed."""
await _register_components(hass)
# Set vacuum's fan speed to high
await common.async_set_fan_speed(hass, "high", _TEST_VACUUM)
await hass.async_block_till_done()
# verify
assert hass.states.get(_FAN_SPEED_INPUT_SELECT).state == "high"
# Set vacuum's fan speed to 'invalid'
await common.async_set_fan_speed(hass, "invalid", _TEST_VACUUM)
await hass.async_block_till_done()
# verify fan speed is unchanged
assert hass.states.get(_FAN_SPEED_INPUT_SELECT).state == "high"
def _verify(
hass: HomeAssistant, expected_state: str, expected_battery_level: int
) -> None:
"""Verify vacuum's state and speed."""
state = hass.states.get(_TEST_VACUUM)
attributes = state.attributes
assert state.state == expected_state
assert attributes.get(ATTR_BATTERY_LEVEL) == expected_battery_level
async def _register_basic_vacuum(hass: HomeAssistant) -> None:
"""Register basic vacuum with only required options for testing."""
with assert_setup_component(1, "input_select"):
assert await setup.async_setup_component(
hass,
"input_select",
{
"input_select": {
"state": {"name": "State", "options": [VacuumActivity.CLEANING]}
}
},
)
with assert_setup_component(1, "vacuum"):
assert await setup.async_setup_component(
hass,
"vacuum",
{
"vacuum": {
"platform": "template",
"vacuums": {
"test_vacuum": {
"start": {
"service": "input_select.select_option",
"data": {
"entity_id": _STATE_INPUT_SELECT,
"option": VacuumActivity.CLEANING,
},
}
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
async def _register_components(hass: HomeAssistant) -> None:
"""Register basic components for testing."""
with assert_setup_component(2, "input_boolean"):
assert await setup.async_setup_component(
hass,
"input_boolean",
{"input_boolean": {"spot_cleaning": None, "locating": None}},
)
with assert_setup_component(2, "input_select"):
assert await setup.async_setup_component(
hass,
"input_select",
{
"input_select": {
"state": {
"name": "State",
"options": [
VacuumActivity.CLEANING,
VacuumActivity.DOCKED,
VacuumActivity.IDLE,
VacuumActivity.PAUSED,
VacuumActivity.RETURNING,
],
},
"fan_speed": {
"name": "Fan speed",
"options": ["", "low", "medium", "high"],
},
}
},
)
with assert_setup_component(1, "vacuum"):
test_vacuum_config = {
"value_template": "{{ states('input_select.state') }}",
"fan_speed_template": "{{ states('input_select.fan_speed') }}",
"start": [
{
"service": "input_select.select_option",
"data": {
"entity_id": _STATE_INPUT_SELECT,
"option": VacuumActivity.CLEANING,
},
},
{
"service": "test.automation",
"data_template": {
"action": "start",
"caller": "{{ this.entity_id }}",
},
},
],
"pause": [
{
"service": "input_select.select_option",
"data": {
"entity_id": _STATE_INPUT_SELECT,
"option": VacuumActivity.PAUSED,
},
},
{
"service": "test.automation",
"data_template": {
"action": "pause",
"caller": "{{ this.entity_id }}",
},
},
],
"stop": [
{
"service": "input_select.select_option",
"data": {
"entity_id": _STATE_INPUT_SELECT,
"option": VacuumActivity.IDLE,
},
},
{
"service": "test.automation",
"data_template": {
"action": "stop",
"caller": "{{ this.entity_id }}",
},
},
],
"return_to_base": [
{
"service": "input_select.select_option",
"data": {
"entity_id": _STATE_INPUT_SELECT,
"option": VacuumActivity.RETURNING,
},
},
{
"service": "test.automation",
"data_template": {
"action": "return_to_base",
"caller": "{{ this.entity_id }}",
},
},
],
"clean_spot": [
{
"service": "input_boolean.turn_on",
"entity_id": _SPOT_CLEANING_INPUT_BOOLEAN,
},
{
"service": "test.automation",
"data_template": {
"action": "clean_spot",
"caller": "{{ this.entity_id }}",
},
},
],
"locate": [
{
"service": "input_boolean.turn_on",
"entity_id": _LOCATING_INPUT_BOOLEAN,
},
{
"service": "test.automation",
"data_template": {
"action": "locate",
"caller": "{{ this.entity_id }}",
},
},
],
"set_fan_speed": [
{
"service": "input_select.select_option",
"data_template": {
"entity_id": _FAN_SPEED_INPUT_SELECT,
"option": "{{ fan_speed }}",
},
},
{
"service": "test.automation",
"data_template": {
"action": "set_fan_speed",
"caller": "{{ this.entity_id }}",
"option": "{{ fan_speed }}",
},
},
],
"fan_speeds": ["low", "medium", "high"],
"attribute_templates": {
"test_attribute": "It {{ states.sensor.test_state.state }}."
},
}
assert await setup.async_setup_component(
hass,
"vacuum",
{
"vacuum": {
"platform": "template",
"vacuums": {"test_vacuum": test_vacuum_config},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()

View File

@@ -0,0 +1,930 @@
"""The tests for the Template Weather platform."""
from typing import Any
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.weather import (
ATTR_WEATHER_APPARENT_TEMPERATURE,
ATTR_WEATHER_CLOUD_COVERAGE,
ATTR_WEATHER_DEW_POINT,
ATTR_WEATHER_HUMIDITY,
ATTR_WEATHER_OZONE,
ATTR_WEATHER_PRESSURE,
ATTR_WEATHER_TEMPERATURE,
ATTR_WEATHER_VISIBILITY,
ATTR_WEATHER_WIND_BEARING,
ATTR_WEATHER_WIND_GUST_SPEED,
ATTR_WEATHER_WIND_SPEED,
DOMAIN as WEATHER_DOMAIN,
SERVICE_GET_FORECASTS,
Forecast,
)
from homeassistant.const import ATTR_ATTRIBUTION, STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import Context, HomeAssistant, State
from homeassistant.helpers.restore_state import STORAGE_KEY as RESTORE_STATE_KEY
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.common import (
assert_setup_component,
async_mock_restore_state_shutdown_restart,
mock_restore_cache_with_extra_data,
)
ATTR_FORECAST = "forecast"
@pytest.mark.parametrize(("count", "domain"), [(1, WEATHER_DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
"weather": [
{"weather": {"platform": "demo"}},
{
"platform": "template",
"name": "test",
"attribution_template": "{{ states('sensor.attribution') }}",
"condition_template": "sunny",
"temperature_template": "{{ states('sensor.temperature') | float }}",
"humidity_template": "{{ states('sensor.humidity') | int }}",
"pressure_template": "{{ states('sensor.pressure') }}",
"wind_speed_template": "{{ states('sensor.windspeed') }}",
"wind_bearing_template": "{{ states('sensor.windbearing') }}",
"ozone_template": "{{ states('sensor.ozone') }}",
"visibility_template": "{{ states('sensor.visibility') }}",
"wind_gust_speed_template": "{{ states('sensor.wind_gust_speed') }}",
"cloud_coverage_template": "{{ states('sensor.cloud_coverage') }}",
"dew_point_template": "{{ states('sensor.dew_point') }}",
"apparent_temperature_template": "{{ states('sensor.apparent_temperature') }}",
},
]
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_template_state_text(hass: HomeAssistant) -> None:
"""Test the state text of a template."""
for attr, v_attr, value in (
(
"sensor.attribution",
ATTR_ATTRIBUTION,
"The custom attribution",
),
("sensor.temperature", ATTR_WEATHER_TEMPERATURE, 22.3),
("sensor.humidity", ATTR_WEATHER_HUMIDITY, 60),
("sensor.pressure", ATTR_WEATHER_PRESSURE, 1000),
("sensor.windspeed", ATTR_WEATHER_WIND_SPEED, 20),
("sensor.windbearing", ATTR_WEATHER_WIND_BEARING, 180),
("sensor.ozone", ATTR_WEATHER_OZONE, 25),
("sensor.visibility", ATTR_WEATHER_VISIBILITY, 4.6),
("sensor.wind_gust_speed", ATTR_WEATHER_WIND_GUST_SPEED, 30),
("sensor.cloud_coverage", ATTR_WEATHER_CLOUD_COVERAGE, 75),
("sensor.dew_point", ATTR_WEATHER_DEW_POINT, 2.2),
("sensor.apparent_temperature", ATTR_WEATHER_APPARENT_TEMPERATURE, 25),
):
hass.states.async_set(attr, value)
await hass.async_block_till_done()
state = hass.states.get("weather.test")
assert state is not None
assert state.state == "sunny"
assert state.attributes.get(v_attr) == value
@pytest.mark.parametrize(
("service"),
[SERVICE_GET_FORECASTS],
)
@pytest.mark.parametrize(("count", "domain"), [(1, WEATHER_DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
"weather": [
{
"platform": "template",
"name": "forecast",
"condition_template": "sunny",
"forecast_daily_template": "{{ states.weather.forecast.attributes.forecast }}",
"forecast_hourly_template": "{{ states.weather.forecast.attributes.forecast }}",
"forecast_twice_daily_template": "{{ states.weather.forecast_twice_daily.attributes.forecast }}",
"temperature_template": "{{ states('sensor.temperature') | float }}",
"humidity_template": "{{ states('sensor.humidity') | int }}",
},
]
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_forecasts(
hass: HomeAssistant, snapshot: SnapshotAssertion, service: str
) -> None:
"""Test forecast service."""
for attr, _v_attr, value in (
("sensor.temperature", ATTR_WEATHER_TEMPERATURE, 22.3),
("sensor.humidity", ATTR_WEATHER_HUMIDITY, 60),
):
hass.states.async_set(attr, value)
await hass.async_block_till_done()
hass.states.async_set(
"weather.forecast",
"sunny",
{
ATTR_FORECAST: [
Forecast(
condition="cloudy",
datetime="2023-02-17T14:00:00+00:00",
temperature=14.2,
)
]
},
)
hass.states.async_set(
"weather.forecast_twice_daily",
"fog",
{
ATTR_FORECAST: [
Forecast(
condition="fog",
datetime="2023-02-17T14:00:00+00:00",
temperature=14.2,
is_daytime=True,
)
]
},
)
await hass.async_block_till_done()
state = hass.states.get("weather.forecast")
assert state is not None
assert state.state == "sunny"
state2 = hass.states.get("weather.forecast_twice_daily")
assert state2 is not None
assert state2.state == "fog"
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{"entity_id": "weather.forecast", "type": "daily"},
blocking=True,
return_response=True,
)
assert response == snapshot
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{"entity_id": "weather.forecast", "type": "hourly"},
blocking=True,
return_response=True,
)
assert response == snapshot
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{"entity_id": "weather.forecast", "type": "twice_daily"},
blocking=True,
return_response=True,
)
assert response == snapshot
hass.states.async_set(
"weather.forecast",
"sunny",
{
ATTR_FORECAST: [
Forecast(
condition="cloudy",
datetime="2023-02-17T14:00:00+00:00",
temperature=16.9,
)
]
},
)
await hass.async_block_till_done()
state = hass.states.get("weather.forecast")
assert state is not None
assert state.state == "sunny"
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{"entity_id": "weather.forecast", "type": "daily"},
blocking=True,
return_response=True,
)
assert response == snapshot
@pytest.mark.parametrize(
("service", "expected"),
[
(SERVICE_GET_FORECASTS, {"weather.forecast": {"forecast": []}}),
],
)
@pytest.mark.parametrize(("count", "domain"), [(1, WEATHER_DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
"weather": [
{
"platform": "template",
"name": "forecast",
"condition_template": "sunny",
"forecast_daily_template": "{{ states.weather.forecast.attributes.forecast }}",
"forecast_hourly_template": "{{ states.weather.forecast_hourly.attributes.forecast }}",
"temperature_template": "{{ states('sensor.temperature') | float }}",
"humidity_template": "{{ states('sensor.humidity') | int }}",
},
]
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_forecast_invalid(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
service: str,
expected: dict[str, Any],
) -> None:
"""Test invalid forecasts."""
for attr, _v_attr, value in (
("sensor.temperature", ATTR_WEATHER_TEMPERATURE, 22.3),
("sensor.humidity", ATTR_WEATHER_HUMIDITY, 60),
):
hass.states.async_set(attr, value)
await hass.async_block_till_done()
hass.states.async_set(
"weather.forecast",
"sunny",
{
ATTR_FORECAST: [
Forecast(
condition="cloudy",
datetime="2023-02-17T14:00:00+00:00",
temperature=14.2,
not_correct=1,
)
]
},
)
hass.states.async_set(
"weather.forecast_hourly",
"sunny",
{ATTR_FORECAST: None},
)
await hass.async_block_till_done()
state = hass.states.get("weather.forecast_hourly")
assert state is not None
assert state.state == "sunny"
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{"entity_id": "weather.forecast", "type": "daily"},
blocking=True,
return_response=True,
)
assert response == expected
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{"entity_id": "weather.forecast", "type": "hourly"},
blocking=True,
return_response=True,
)
assert response == expected
assert "Only valid keys in Forecast are allowed" in caplog.text
@pytest.mark.parametrize(
("service", "expected"),
[
(SERVICE_GET_FORECASTS, {"weather.forecast": {"forecast": []}}),
],
)
@pytest.mark.parametrize(("count", "domain"), [(1, WEATHER_DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
"weather": [
{
"platform": "template",
"name": "forecast",
"condition_template": "sunny",
"forecast_twice_daily_template": "{{ states.weather.forecast_twice_daily.attributes.forecast }}",
"temperature_template": "{{ states('sensor.temperature') | float }}",
"humidity_template": "{{ states('sensor.humidity') | int }}",
},
]
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_forecast_invalid_is_daytime_missing_in_twice_daily(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
service: str,
expected: dict[str, Any],
) -> None:
"""Test forecast service invalid when is_daytime missing in twice_daily forecast."""
for attr, _v_attr, value in (
("sensor.temperature", ATTR_WEATHER_TEMPERATURE, 22.3),
("sensor.humidity", ATTR_WEATHER_HUMIDITY, 60),
):
hass.states.async_set(attr, value)
await hass.async_block_till_done()
hass.states.async_set(
"weather.forecast_twice_daily",
"sunny",
{
ATTR_FORECAST: [
Forecast(
condition="cloudy",
datetime="2023-02-17T14:00:00+00:00",
temperature=14.2,
)
]
},
)
await hass.async_block_till_done()
state = hass.states.get("weather.forecast_twice_daily")
assert state is not None
assert state.state == "sunny"
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{"entity_id": "weather.forecast", "type": "twice_daily"},
blocking=True,
return_response=True,
)
assert response == expected
assert "`is_daytime` is missing in twice_daily forecast" in caplog.text
@pytest.mark.parametrize(
("service", "expected"),
[
(SERVICE_GET_FORECASTS, {"weather.forecast": {"forecast": []}}),
],
)
@pytest.mark.parametrize(("count", "domain"), [(1, WEATHER_DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
"weather": [
{
"platform": "template",
"name": "forecast",
"condition_template": "sunny",
"forecast_twice_daily_template": "{{ states.weather.forecast_twice_daily.attributes.forecast }}",
"temperature_template": "{{ states('sensor.temperature') | float }}",
"humidity_template": "{{ states('sensor.humidity') | int }}",
},
]
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_forecast_invalid_datetime_missing(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
service: str,
expected: dict[str, Any],
) -> None:
"""Test forecast service invalid when datetime missing."""
for attr, _v_attr, value in (
("sensor.temperature", ATTR_WEATHER_TEMPERATURE, 22.3),
("sensor.humidity", ATTR_WEATHER_HUMIDITY, 60),
):
hass.states.async_set(attr, value)
await hass.async_block_till_done()
hass.states.async_set(
"weather.forecast_twice_daily",
"sunny",
{
ATTR_FORECAST: [
Forecast(
condition="cloudy",
temperature=14.2,
is_daytime=True,
)
]
},
)
await hass.async_block_till_done()
state = hass.states.get("weather.forecast_twice_daily")
assert state is not None
assert state.state == "sunny"
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{"entity_id": "weather.forecast", "type": "twice_daily"},
blocking=True,
return_response=True,
)
assert response == expected
assert "`datetime` is required in forecasts" in caplog.text
@pytest.mark.parametrize(
("service"),
[SERVICE_GET_FORECASTS],
)
@pytest.mark.parametrize(("count", "domain"), [(1, WEATHER_DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
"weather": [
{
"platform": "template",
"name": "forecast",
"condition_template": "sunny",
"forecast_daily_template": "{{ states.weather.forecast_daily.attributes.forecast }}",
"forecast_hourly_template": "{{ states.weather.forecast_hourly.attributes.forecast }}",
"temperature_template": "{{ states('sensor.temperature') | float }}",
"humidity_template": "{{ states('sensor.humidity') | int }}",
},
]
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_forecast_format_error(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, service: str
) -> None:
"""Test forecast service invalid on incorrect format."""
for attr, _v_attr, value in (
("sensor.temperature", ATTR_WEATHER_TEMPERATURE, 22.3),
("sensor.humidity", ATTR_WEATHER_HUMIDITY, 60),
):
hass.states.async_set(attr, value)
await hass.async_block_till_done()
hass.states.async_set(
"weather.forecast_daily",
"sunny",
{
ATTR_FORECAST: [
"cloudy",
"2023-02-17T14:00:00+00:00",
14.2,
1,
]
},
)
hass.states.async_set(
"weather.forecast_hourly",
"sunny",
{
ATTR_FORECAST: {
"condition": "cloudy",
"temperature": 14.2,
"is_daytime": True,
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
WEATHER_DOMAIN,
service,
{"entity_id": "weather.forecast", "type": "daily"},
blocking=True,
return_response=True,
)
assert "Forecasts is not a list, see Weather documentation" in caplog.text
await hass.services.async_call(
WEATHER_DOMAIN,
service,
{"entity_id": "weather.forecast", "type": "hourly"},
blocking=True,
return_response=True,
)
assert "Forecast in list is not a dict, see Weather documentation" in caplog.text
SAVED_EXTRA_DATA = {
"last_apparent_temperature": None,
"last_cloud_coverage": None,
"last_dew_point": None,
"last_forecast": None,
"last_humidity": 10,
"last_ozone": None,
"last_pressure": None,
"last_temperature": 20,
"last_visibility": None,
"last_wind_bearing": None,
"last_wind_gust_speed": None,
"last_wind_speed": None,
}
SAVED_EXTRA_DATA_WITH_FUTURE_KEY = {
"last_apparent_temperature": None,
"last_cloud_coverage": None,
"last_dew_point": None,
"last_forecast": None,
"last_humidity": 10,
"last_ozone": None,
"last_pressure": None,
"last_temperature": 20,
"last_visibility": None,
"last_wind_bearing": None,
"last_wind_gust_speed": None,
"last_wind_speed": None,
"some_key_added_in_the_future": 123,
}
@pytest.mark.parametrize(("count", "domain"), [(1, "template")])
@pytest.mark.parametrize(
"config",
[
{
"template": {
"trigger": {"platform": "event", "event_type": "test_event"},
"weather": {
"name": "test",
"condition_template": "{{ trigger.event.data.condition }}",
"temperature_template": "{{ trigger.event.data.temperature | float }}",
"temperature_unit": "°C",
"humidity_template": "{{ trigger.event.data.humidity | float }}",
},
},
},
],
)
@pytest.mark.parametrize(
("saved_state", "saved_extra_data", "initial_state"),
[
("sunny", SAVED_EXTRA_DATA, "sunny"),
("sunny", SAVED_EXTRA_DATA_WITH_FUTURE_KEY, "sunny"),
(STATE_UNAVAILABLE, SAVED_EXTRA_DATA, STATE_UNKNOWN),
(STATE_UNKNOWN, SAVED_EXTRA_DATA, STATE_UNKNOWN),
],
)
async def test_trigger_entity_restore_state(
hass: HomeAssistant,
count: int,
domain: str,
config: dict,
saved_state: str,
saved_extra_data: dict | None,
initial_state: str,
) -> None:
"""Test restoring trigger template weather."""
restored_attributes = { # These should be ignored
"temperature": -10,
"humidity": 50,
}
fake_state = State(
"weather.test",
saved_state,
restored_attributes,
)
mock_restore_cache_with_extra_data(hass, ((fake_state, saved_extra_data),))
with assert_setup_component(count, domain):
assert await async_setup_component(
hass,
domain,
config,
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("weather.test")
assert state.state == initial_state
hass.bus.async_fire(
"test_event", {"condition": "cloudy", "temperature": 15, "humidity": 25}
)
await hass.async_block_till_done()
state = hass.states.get("weather.test")
state = hass.states.get("weather.test")
assert state.state == "cloudy"
assert state.attributes["temperature"] == 15.0
assert state.attributes["humidity"] == 25.0
@pytest.mark.parametrize(("count", "domain"), [(1, "template")])
@pytest.mark.parametrize(
"config",
[
{
"template": [
{
"unique_id": "listening-test-event",
"trigger": {"platform": "event", "event_type": "test_event"},
"action": [
{
"variables": {
"my_variable": "{{ trigger.event.data.temperature + 1 }}"
},
},
],
"weather": [
{
"name": "Hello Name",
"condition_template": "sunny",
"temperature_unit": "°C",
"humidity_template": "{{ 20 }}",
"temperature_template": "{{ my_variable + 1 }}",
}
],
},
],
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_trigger_action(hass: HomeAssistant) -> None:
"""Test trigger entity with an action works."""
state = hass.states.get("weather.hello_name")
assert state is not None
assert state.state == STATE_UNKNOWN
context = Context()
hass.bus.async_fire("test_event", {"temperature": 1}, context=context)
await hass.async_block_till_done()
state = hass.states.get("weather.hello_name")
assert state.state == "sunny"
assert state.attributes["temperature"] == 3.0
assert state.context is context
@pytest.mark.parametrize(
("service"),
[SERVICE_GET_FORECASTS],
)
@pytest.mark.parametrize(("count", "domain"), [(1, "template")])
@pytest.mark.parametrize(
"config",
[
{
"template": [
{
"unique_id": "listening-test-event",
"trigger": {"platform": "event", "event_type": "test_event"},
"action": [
{
"variables": {
"my_variable": "{{ trigger.event.data.information + 1 }}",
"var_forecast_daily": "{{ trigger.event.data.forecast_daily }}",
"var_forecast_hourly": "{{ trigger.event.data.forecast_hourly }}",
"var_forecast_twice_daily": "{{ trigger.event.data.forecast_twice_daily }}",
},
},
],
"weather": [
{
"name": "Test",
"condition_template": "sunny",
"precipitation_unit": "mm",
"pressure_unit": "hPa",
"visibility_unit": "km",
"wind_speed_unit": "km/h",
"temperature_unit": "°C",
"temperature_template": "{{ my_variable + 1 }}",
"humidity_template": "{{ my_variable + 1 }}",
"wind_speed_template": "{{ my_variable + 1 }}",
"wind_bearing_template": "{{ my_variable + 1 }}",
"ozone_template": "{{ my_variable + 1 }}",
"visibility_template": "{{ my_variable + 1 }}",
"pressure_template": "{{ my_variable + 1 }}",
"wind_gust_speed_template": "{{ my_variable + 1 }}",
"cloud_coverage_template": "{{ my_variable + 1 }}",
"dew_point_template": "{{ my_variable + 1 }}",
"apparent_temperature_template": "{{ my_variable + 1 }}",
"forecast_daily_template": "{{ var_forecast_daily }}",
"forecast_hourly_template": "{{ var_forecast_hourly }}",
"forecast_twice_daily_template": "{{ var_forecast_twice_daily }}",
}
],
},
],
},
],
)
@pytest.mark.usefixtures("start_ha")
@pytest.mark.freeze_time("2023-10-19 13:50:05")
async def test_trigger_weather_services(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
service: str,
) -> None:
"""Test trigger weather entity with services."""
state = hass.states.get("weather.test")
assert state is not None
assert state.state == STATE_UNKNOWN
context = Context()
now = dt_util.now().isoformat()
hass.bus.async_fire(
"test_event",
{
"information": 1,
"forecast_daily": [
{
"datetime": now,
"condition": "sunny",
"precipitation": 20,
"temperature": 20,
"templow": 15,
}
],
"forecast_hourly": [
{
"datetime": now,
"condition": "sunny",
"precipitation": 20,
"temperature": 20,
"templow": 15,
}
],
"forecast_twice_daily": [
{
"datetime": now,
"condition": "sunny",
"precipitation": 20,
"temperature": 20,
"templow": 15,
"is_daytime": True,
}
],
},
context=context,
)
await hass.async_block_till_done()
state = hass.states.get("weather.test")
assert state.state == "sunny"
assert state.attributes["temperature"] == 3.0
assert state.attributes["humidity"] == 3.0
assert state.attributes["wind_speed"] == 3.0
assert state.attributes["wind_bearing"] == 3.0
assert state.attributes["ozone"] == 3.0
assert state.attributes["visibility"] == 3.0
assert state.attributes["pressure"] == 3.0
assert state.attributes["wind_gust_speed"] == 3.0
assert state.attributes["cloud_coverage"] == 3.0
assert state.attributes["dew_point"] == 3.0
assert state.attributes["apparent_temperature"] == 3.0
assert state.context is context
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{
"entity_id": state.entity_id,
"type": "daily",
},
blocking=True,
return_response=True,
)
assert response == snapshot
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{
"entity_id": state.entity_id,
"type": "hourly",
},
blocking=True,
return_response=True,
)
assert response == snapshot
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{
"entity_id": state.entity_id,
"type": "twice_daily",
},
blocking=True,
return_response=True,
)
assert response == snapshot
async def test_restore_weather_save_state(
hass: HomeAssistant, hass_storage: dict[str, Any], snapshot: SnapshotAssertion
) -> None:
"""Test Restore saved state for Weather trigger template."""
assert await async_setup_component(
hass,
"template",
{
"template": {
"trigger": {"platform": "event", "event_type": "test_event"},
"weather": {
"name": "test",
"condition_template": "{{ trigger.event.data.condition }}",
"temperature_template": "{{ trigger.event.data.temperature | float }}",
"temperature_unit": "°C",
"humidity_template": "{{ trigger.event.data.humidity | float }}",
},
},
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
hass.bus.async_fire(
"test_event", {"condition": "cloudy", "temperature": 15, "humidity": 25}
)
await hass.async_block_till_done()
entity = hass.states.get("weather.test")
# 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"] == entity.entity_id
extra_data = hass_storage[RESTORE_STATE_KEY]["data"][0]["extra_data"]
assert extra_data == snapshot
SAVED_ATTRIBUTES_1 = {
"humidity": 20,
"temperature": 10,
}
SAVED_EXTRA_DATA_MISSING_KEY = {
"last_cloud_coverage": None,
"last_dew_point": None,
"last_humidity": 20,
"last_ozone": None,
"last_pressure": None,
"last_temperature": 20,
"last_visibility": None,
"last_wind_bearing": None,
"last_wind_gust_speed": None,
"last_wind_speed": None,
}
@pytest.mark.parametrize(
("saved_attributes", "saved_extra_data"),
[
(SAVED_ATTRIBUTES_1, SAVED_EXTRA_DATA_MISSING_KEY),
(SAVED_ATTRIBUTES_1, None),
],
)
async def test_trigger_entity_restore_state_fail(
hass: HomeAssistant,
saved_attributes: dict,
saved_extra_data: dict | None,
) -> None:
"""Test restoring trigger template weather fails due to missing attribute."""
saved_state = State(
"weather.test",
None,
saved_attributes,
)
mock_restore_cache_with_extra_data(hass, ((saved_state, saved_extra_data),))
assert await async_setup_component(
hass,
"template",
{
"template": {
"trigger": {"platform": "event", "event_type": "test_event"},
"weather": {
"name": "test",
"condition_template": "{{ trigger.event.data.condition }}",
"temperature_template": "{{ trigger.event.data.temperature | float }}",
"temperature_unit": "°C",
"humidity_template": "{{ trigger.event.data.humidity | float }}",
},
},
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("weather.test")
assert state.state == STATE_UNKNOWN
assert state.attributes.get("temperature") is None