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,5 @@
"""The tests for Sensor platforms."""
import pytest
pytest.register_assert_rewrite("tests.components.recorder.common")

View File

@@ -0,0 +1,122 @@
"""Common test utilities for sensor entity component tests."""
from homeassistant.components.sensor import (
RestoreSensor,
SensorDeviceClass,
SensorEntity,
)
from homeassistant.const import (
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
CONCENTRATION_PARTS_PER_MILLION,
LIGHT_LUX,
PERCENTAGE,
SIGNAL_STRENGTH_DECIBELS,
UnitOfApparentPower,
UnitOfFrequency,
UnitOfPressure,
UnitOfReactivePower,
UnitOfVolume,
)
from tests.common import MockEntity
UNITS_OF_MEASUREMENT = {
SensorDeviceClass.APPARENT_POWER: UnitOfApparentPower.VOLT_AMPERE, # apparent power (VA)
SensorDeviceClass.BATTERY: PERCENTAGE, # % of battery that is left
SensorDeviceClass.CO: CONCENTRATION_PARTS_PER_MILLION, # ppm of CO concentration
SensorDeviceClass.CO2: CONCENTRATION_PARTS_PER_MILLION, # ppm of CO2 concentration
SensorDeviceClass.HUMIDITY: PERCENTAGE, # % of humidity in the air
SensorDeviceClass.ILLUMINANCE: LIGHT_LUX, # current light level lx
SensorDeviceClass.MOISTURE: PERCENTAGE, # % of water in a substance
SensorDeviceClass.NITROGEN_DIOXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of nitrogen dioxide
SensorDeviceClass.NITROGEN_MONOXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of nitrogen monoxide
SensorDeviceClass.NITROUS_OXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of nitrogen oxide
SensorDeviceClass.OZONE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of ozone
SensorDeviceClass.PM1: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of PM1
SensorDeviceClass.PM10: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of PM10
SensorDeviceClass.PM25: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of PM2.5
SensorDeviceClass.SIGNAL_STRENGTH: SIGNAL_STRENGTH_DECIBELS, # signal strength (dB/dBm)
SensorDeviceClass.SULPHUR_DIOXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of sulphur dioxide
SensorDeviceClass.TEMPERATURE: "C", # temperature (C/F)
SensorDeviceClass.PRESSURE: UnitOfPressure.HPA, # pressure (hPa/mbar)
SensorDeviceClass.POWER: "kW", # power (W/kW)
SensorDeviceClass.CURRENT: "A", # current (A)
SensorDeviceClass.ENERGY: "kWh", # energy (Wh/kWh/MWh)
SensorDeviceClass.FREQUENCY: UnitOfFrequency.GIGAHERTZ, # energy (Hz/kHz/MHz/GHz)
SensorDeviceClass.POWER_FACTOR: PERCENTAGE, # power factor (no unit, min: -1.0, max: 1.0)
SensorDeviceClass.REACTIVE_POWER: UnitOfReactivePower.VOLT_AMPERE_REACTIVE, # reactive power (var)
SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of vocs
SensorDeviceClass.VOLTAGE: "V", # voltage (V)
SensorDeviceClass.GAS: UnitOfVolume.CUBIC_METERS, # gas (m³)
}
class MockSensor(MockEntity, SensorEntity):
"""Mock Sensor class."""
@property
def device_class(self):
"""Return the class of this sensor."""
return self._handle("device_class")
@property
def last_reset(self):
"""Return the last_reset of this sensor."""
return self._handle("last_reset")
@property
def suggested_display_precision(self):
"""Return the number of digits after the decimal point."""
return self._handle("suggested_display_precision")
@property
def native_unit_of_measurement(self):
"""Return the native unit_of_measurement of this sensor."""
return self._handle("native_unit_of_measurement")
@property
def native_value(self):
"""Return the native value of this sensor."""
return self._handle("native_value")
@property
def options(self):
"""Return the options for this sensor."""
return self._handle("options")
@property
def state_class(self):
"""Return the state class of this sensor."""
return self._handle("state_class")
@property
def suggested_unit_of_measurement(self):
"""Return the state class of this sensor."""
return self._handle("suggested_unit_of_measurement")
class MockRestoreSensor(MockSensor, RestoreSensor):
"""Mock RestoreSensor class."""
async def async_added_to_hass(self) -> None:
"""Restore native_value and native_unit_of_measurement."""
await super().async_added_to_hass()
if (last_sensor_data := await self.async_get_last_sensor_data()) is None:
return
self._values["native_value"] = last_sensor_data.native_value
self._values["native_unit_of_measurement"] = (
last_sensor_data.native_unit_of_measurement
)
def get_mock_sensor_entities() -> dict[str, MockSensor]:
"""Get mock sensor entities."""
return {
device_class: MockSensor(
name=f"{device_class} sensor",
unique_id=f"unique_{device_class}",
device_class=device_class,
native_unit_of_measurement=UNITS_OF_MEASUREMENT.get(device_class),
)
for device_class in SensorDeviceClass
}

View File

@@ -0,0 +1,786 @@
"""The test for sensor device automation."""
import pytest
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.sensor import (
ATTR_STATE_CLASS,
DOMAIN,
SensorDeviceClass,
SensorStateClass,
device_condition,
)
from homeassistant.components.sensor.const import NON_NUMERIC_DEVICE_CLASSES
from homeassistant.components.sensor.device_condition import ENTITY_CONDITIONS
from homeassistant.const import CONF_PLATFORM, PERCENTAGE, STATE_UNKNOWN, EntityCategory
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
from homeassistant.util.json import load_json
from .common import UNITS_OF_MEASUREMENT, MockSensor
from tests.common import (
MockConfigEntry,
async_get_device_automation_capabilities,
async_get_device_automations,
setup_test_component_platform,
)
@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."""
@pytest.mark.parametrize(
"device_class",
[
device_class
for device_class in SensorDeviceClass
if device_class not in NON_NUMERIC_DEVICE_CLASSES
],
)
def test_matches_device_classes(device_class: SensorDeviceClass) -> None:
"""Ensure device class constants are declared in device_condition module."""
# Ensure it has corresponding CONF_IS_*** constant
constant_name = {
SensorDeviceClass.BATTERY: "CONF_IS_BATTERY_LEVEL",
SensorDeviceClass.CO: "CONF_IS_CO",
SensorDeviceClass.CO2: "CONF_IS_CO2",
SensorDeviceClass.ENERGY_STORAGE: "CONF_IS_ENERGY",
SensorDeviceClass.VOLUME_STORAGE: "CONF_IS_VOLUME",
}.get(device_class, f"CONF_IS_{device_class.value.upper()}")
assert hasattr(device_condition, constant_name), f"Missing constant {constant_name}"
# Ensure it has correct value
constant_value = {
SensorDeviceClass.BATTERY: "is_battery_level",
SensorDeviceClass.ENERGY_STORAGE: "is_energy",
SensorDeviceClass.VOLUME_STORAGE: "is_volume",
}.get(device_class, f"is_{device_class.value}")
assert getattr(device_condition, constant_name) == constant_value
# Ensure it is present in ENTITY_CONDITIONS
assert device_class in ENTITY_CONDITIONS
# Ensure it is present in CONDITION_SCHEMA
schema_types = (
device_condition.CONDITION_SCHEMA.validators[0].schema["type"].container
)
assert constant_value in schema_types
# Ensure it is present in string.json
strings = load_json("homeassistant/components/sensor/strings.json")
assert constant_value in strings["device_automation"]["condition_type"]
async def test_get_conditions(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
mock_sensor_entities: dict[str, MockSensor],
) -> None:
"""Test we get the expected conditions from a sensor."""
setup_test_component_platform(hass, DOMAIN, mock_sensor_entities.values())
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
sensor_entries = {}
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
for device_class in SensorDeviceClass:
sensor_entries[device_class] = entity_registry.async_get_or_create(
DOMAIN,
"test",
mock_sensor_entities[device_class].unique_id,
device_id=device_entry.id,
)
expected_conditions = [
{
"condition": "device",
"domain": DOMAIN,
"type": condition["type"],
"device_id": device_entry.id,
"entity_id": sensor_entries[device_class].id,
"metadata": {"secondary": False},
}
for device_class in SensorDeviceClass
if device_class in UNITS_OF_MEASUREMENT
for condition in ENTITY_CONDITIONS[device_class]
if device_class != "none"
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert len(conditions) == 27
assert conditions == unordered(expected_conditions)
@pytest.mark.parametrize(
("hidden_by", "entity_category"),
[
(RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
],
)
async def test_get_conditions_hidden_auxiliary(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by,
entity_category,
) -> None:
"""Test we get the expected conditions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
unit_of_measurement="dogs",
)
expected_conditions = [
{
"condition": "device",
"domain": DOMAIN,
"type": condition,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": True},
}
for condition in ("is_value",)
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert conditions == unordered(expected_conditions)
async def test_get_conditions_no_state(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected conditions from a sensor."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
sensor_entries = {}
for device_class in SensorDeviceClass:
sensor_entries[device_class] = entity_registry.async_get_or_create(
DOMAIN,
"test",
f"5678_{device_class}",
device_id=device_entry.id,
original_device_class=device_class,
unit_of_measurement=UNITS_OF_MEASUREMENT.get(device_class),
)
await hass.async_block_till_done()
expected_conditions = [
{
"condition": "device",
"domain": DOMAIN,
"type": condition["type"],
"device_id": device_entry.id,
"entity_id": sensor_entries[device_class].id,
"metadata": {"secondary": False},
}
for device_class in SensorDeviceClass
if device_class in UNITS_OF_MEASUREMENT
for condition in ENTITY_CONDITIONS[device_class]
if device_class != "none"
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert conditions == unordered(expected_conditions)
@pytest.mark.parametrize(
("state_class", "unit", "condition_types"),
[
(SensorStateClass.MEASUREMENT, None, ["is_value"]),
(SensorStateClass.TOTAL, None, ["is_value"]),
(SensorStateClass.TOTAL_INCREASING, None, ["is_value"]),
(SensorStateClass.MEASUREMENT, "dogs", ["is_value"]),
(None, None, []),
],
)
async def test_get_conditions_no_unit_or_stateclass(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
state_class,
unit,
condition_types,
) -> None:
"""Test we get the expected conditions from an entity with no unit or state class."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
capabilities={ATTR_STATE_CLASS: state_class},
device_id=device_entry.id,
unit_of_measurement=unit,
)
expected_conditions = [
{
"condition": "device",
"domain": DOMAIN,
"type": condition,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
for condition in condition_types
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert conditions == unordered(expected_conditions)
@pytest.mark.parametrize(
("set_state", "device_class_reg", "device_class_state", "unit_reg", "unit_state"),
[
(False, SensorDeviceClass.BATTERY, None, PERCENTAGE, None),
(True, None, SensorDeviceClass.BATTERY, None, PERCENTAGE),
],
)
async def test_get_condition_capabilities(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
mock_sensor_entities: dict[str, MockSensor],
set_state,
device_class_reg,
device_class_state,
unit_reg,
unit_state,
) -> None:
"""Test we get the expected capabilities from a sensor condition."""
setup_test_component_platform(hass, DOMAIN, mock_sensor_entities.values())
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_id = entity_registry.async_get_or_create(
DOMAIN,
"test",
mock_sensor_entities["battery"].unique_id,
device_id=device_entry.id,
original_device_class=device_class_reg,
unit_of_measurement=unit_reg,
).entity_id
if set_state:
hass.states.async_set(
entity_id,
None,
{"device_class": device_class_state, "unit_of_measurement": unit_state},
)
expected_capabilities = {
"extra_fields": [
{
"description": {"suffix": PERCENTAGE},
"name": "above",
"optional": True,
"type": "float",
},
{
"description": {"suffix": PERCENTAGE},
"name": "below",
"optional": True,
"type": "float",
},
]
}
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert len(conditions) == 1
for condition in conditions:
capabilities = await async_get_device_automation_capabilities(
hass, DeviceAutomationType.CONDITION, condition
)
assert capabilities == expected_capabilities
@pytest.mark.parametrize(
("set_state", "device_class_reg", "device_class_state", "unit_reg", "unit_state"),
[
(False, SensorDeviceClass.BATTERY, None, PERCENTAGE, None),
(True, None, SensorDeviceClass.BATTERY, None, PERCENTAGE),
],
)
async def test_get_condition_capabilities_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
mock_sensor_entities: dict[str, MockSensor],
set_state,
device_class_reg,
device_class_state,
unit_reg,
unit_state,
) -> None:
"""Test we get the expected capabilities from a sensor condition."""
setup_test_component_platform(hass, DOMAIN, mock_sensor_entities.values())
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_id = entity_registry.async_get_or_create(
DOMAIN,
"test",
mock_sensor_entities["battery"].unique_id,
device_id=device_entry.id,
original_device_class=device_class_reg,
unit_of_measurement=unit_reg,
).entity_id
if set_state:
hass.states.async_set(
entity_id,
None,
{"device_class": device_class_state, "unit_of_measurement": unit_state},
)
expected_capabilities = {
"extra_fields": [
{
"description": {"suffix": PERCENTAGE},
"name": "above",
"optional": True,
"type": "float",
},
{
"description": {"suffix": PERCENTAGE},
"name": "below",
"optional": True,
"type": "float",
},
]
}
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert len(conditions) == 1
for condition in conditions:
condition["entity_id"] = entity_registry.async_get(
condition["entity_id"]
).entity_id
capabilities = await async_get_device_automation_capabilities(
hass, DeviceAutomationType.CONDITION, condition
)
assert capabilities == expected_capabilities
async def test_get_condition_capabilities_none(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected capabilities from a sensor condition."""
entity = MockSensor(
name="none sensor",
unique_id="unique_none",
)
setup_test_component_platform(hass, DOMAIN, [entity])
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
entry_none = entity_registry.async_get_or_create(
DOMAIN,
"test",
entity.unique_id,
)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
conditions = [
{
"condition": "device",
"device_id": "8770c43885354d5fa27604db6817f63f",
"domain": "sensor",
"entity_id": "01234567890123456789012345678901",
"type": "is_battery_level",
},
{
"condition": "device",
"device_id": "8770c43885354d5fa27604db6817f63f",
"domain": "sensor",
"entity_id": entry_none.id,
"type": "is_battery_level",
},
]
expected_capabilities = {}
for condition in conditions:
capabilities = await async_get_device_automation_capabilities(
hass, DeviceAutomationType.CONDITION, condition
)
assert capabilities == expected_capabilities
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_state_not_above_below(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test for bad value conditions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_battery_level",
}
],
"action": {"service": "test.automation"},
}
]
},
)
assert "must contain at least one of below, above" in caplog.text
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_state_above(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for value conditions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_battery_level",
"above": 10,
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": (
"{{ trigger.platform }}"
" - {{ trigger.event.event_type }}"
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 9)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 11)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["some"] == "event - test_event1"
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_state_above_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for value conditions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.entity_id,
"type": "is_battery_level",
"above": 10,
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": (
"{{ trigger.platform }}"
" - {{ trigger.event.event_type }}"
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 9)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 11)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["some"] == "event - test_event1"
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_state_below(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for value conditions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_battery_level",
"below": 10,
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": (
"{{ trigger.platform }}"
" - {{ trigger.event.event_type }}"
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 11)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 9)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["some"] == "event - test_event1"
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_state_between(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for value conditions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_battery_level",
"above": 10,
"below": 20,
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": (
"{{ trigger.platform }}"
" - {{ trigger.event.event_type }}"
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 9)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 11)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["some"] == "event - test_event1"
hass.states.async_set(entry.entity_id, 21)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 1
hass.states.async_set(entry.entity_id, 19)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(service_calls) == 2
assert service_calls[1].data["some"] == "event - test_event1"

View File

@@ -0,0 +1,797 @@
"""The test for sensor device automation."""
from datetime import timedelta
import pytest
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.sensor import (
ATTR_STATE_CLASS,
DOMAIN,
SensorDeviceClass,
SensorStateClass,
device_trigger,
)
from homeassistant.components.sensor.const import NON_NUMERIC_DEVICE_CLASSES
from homeassistant.components.sensor.device_trigger import ENTITY_TRIGGERS
from homeassistant.const import CONF_PLATFORM, PERCENTAGE, STATE_UNKNOWN, EntityCategory
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from homeassistant.util.json import load_json
from .common import UNITS_OF_MEASUREMENT, MockSensor
from tests.common import (
MockConfigEntry,
async_fire_time_changed,
async_get_device_automation_capabilities,
async_get_device_automations,
setup_test_component_platform,
)
@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."""
@pytest.mark.parametrize(
"device_class",
[
device_class
for device_class in SensorDeviceClass
if device_class not in NON_NUMERIC_DEVICE_CLASSES
],
)
def test_matches_device_classes(device_class: SensorDeviceClass) -> None:
"""Ensure device class constants are declared in device_trigger module."""
# Ensure it has corresponding CONF_*** constant
constant_name = {
SensorDeviceClass.BATTERY: "CONF_BATTERY_LEVEL",
SensorDeviceClass.CO: "CONF_CO",
SensorDeviceClass.CO2: "CONF_CO2",
SensorDeviceClass.ENERGY_STORAGE: "CONF_ENERGY",
SensorDeviceClass.VOLUME_STORAGE: "CONF_VOLUME",
}.get(device_class, f"CONF_{device_class.value.upper()}")
assert hasattr(device_trigger, constant_name), f"Missing constant {constant_name}"
# Ensure it has correct value
constant_value = {
SensorDeviceClass.BATTERY: "battery_level",
SensorDeviceClass.ENERGY_STORAGE: "energy",
SensorDeviceClass.VOLUME_STORAGE: "volume",
}.get(device_class, device_class.value)
assert getattr(device_trigger, constant_name) == constant_value
# Ensure it is present in ENTITY_TRIGGERS
assert device_class in ENTITY_TRIGGERS
# Ensure it is present in TRIGGER_SCHEMA
schema_types = device_trigger.TRIGGER_SCHEMA.validators[0].schema["type"].container
assert constant_value in schema_types
# Ensure it is present in string.json
strings = load_json("homeassistant/components/sensor/strings.json")
assert constant_value in strings["device_automation"]["trigger_type"]
async def test_get_triggers(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
mock_sensor_entities: dict[str, MockSensor],
) -> None:
"""Test we get the expected triggers from a sensor."""
setup_test_component_platform(hass, DOMAIN, mock_sensor_entities.values())
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
sensor_entries: dict[SensorDeviceClass, er.RegistryEntry] = {}
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
for device_class in SensorDeviceClass:
sensor_entries[device_class] = entity_registry.async_get_or_create(
DOMAIN,
"test",
mock_sensor_entities[device_class].unique_id,
device_id=device_entry.id,
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": trigger["type"],
"device_id": device_entry.id,
"entity_id": sensor_entries[device_class].id,
"metadata": {"secondary": False},
}
for device_class in SensorDeviceClass
if device_class in UNITS_OF_MEASUREMENT
for trigger in ENTITY_TRIGGERS[device_class]
if device_class != "none"
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert len(triggers) == 27
assert triggers == unordered(expected_triggers)
@pytest.mark.parametrize(
("hidden_by", "entity_category"),
[
(RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
],
)
async def test_get_triggers_hidden_auxiliary(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by,
entity_category,
) -> None:
"""Test we get the expected triggers from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
unit_of_measurement="dogs",
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": True},
}
for trigger in ("value",)
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert triggers == unordered(expected_triggers)
@pytest.mark.parametrize(
("state_class", "unit", "trigger_types"),
[
(SensorStateClass.MEASUREMENT, None, ["value"]),
(SensorStateClass.TOTAL, None, ["value"]),
(SensorStateClass.TOTAL_INCREASING, None, ["value"]),
(SensorStateClass.MEASUREMENT, "dogs", ["value"]),
(None, None, []),
],
)
async def test_get_triggers_no_unit_or_stateclass(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
state_class,
unit,
trigger_types,
) -> None:
"""Test we get the expected triggers from an entity with no unit or state class."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
capabilities={ATTR_STATE_CLASS: state_class},
device_id=device_entry.id,
unit_of_measurement=unit,
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
for trigger in trigger_types
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert triggers == unordered(expected_triggers)
@pytest.mark.parametrize(
("set_state", "device_class_reg", "device_class_state", "unit_reg", "unit_state"),
[
(False, SensorDeviceClass.BATTERY, None, PERCENTAGE, None),
(True, None, SensorDeviceClass.BATTERY, None, PERCENTAGE),
],
)
async def test_get_trigger_capabilities(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
mock_sensor_entities: dict[str, MockSensor],
set_state,
device_class_reg,
device_class_state,
unit_reg,
unit_state,
) -> None:
"""Test we get the expected capabilities from a sensor trigger."""
setup_test_component_platform(hass, DOMAIN, mock_sensor_entities)
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_id = entity_registry.async_get_or_create(
DOMAIN,
"test",
mock_sensor_entities["battery"].unique_id,
device_id=device_entry.id,
original_device_class=device_class_reg,
unit_of_measurement=unit_reg,
).entity_id
if set_state:
hass.states.async_set(
entity_id,
None,
{"device_class": device_class_state, "unit_of_measurement": unit_state},
)
expected_capabilities = {
"extra_fields": [
{
"description": {"suffix": PERCENTAGE},
"name": "above",
"optional": True,
"type": "float",
},
{
"description": {"suffix": PERCENTAGE},
"name": "below",
"optional": True,
"type": "float",
},
{"name": "for", "optional": True, "type": "positive_time_period_dict"},
]
}
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert len(triggers) == 1
for trigger in triggers:
capabilities = await async_get_device_automation_capabilities(
hass, DeviceAutomationType.TRIGGER, trigger
)
assert capabilities == expected_capabilities
@pytest.mark.parametrize(
("set_state", "device_class_reg", "device_class_state", "unit_reg", "unit_state"),
[
(False, SensorDeviceClass.BATTERY, None, PERCENTAGE, None),
(True, None, SensorDeviceClass.BATTERY, None, PERCENTAGE),
],
)
async def test_get_trigger_capabilities_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
mock_sensor_entities: dict[str, MockSensor],
set_state,
device_class_reg,
device_class_state,
unit_reg,
unit_state,
) -> None:
"""Test we get the expected capabilities from a sensor trigger."""
setup_test_component_platform(hass, DOMAIN, mock_sensor_entities)
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_id = entity_registry.async_get_or_create(
DOMAIN,
"test",
mock_sensor_entities["battery"].unique_id,
device_id=device_entry.id,
original_device_class=device_class_reg,
unit_of_measurement=unit_reg,
).entity_id
if set_state:
hass.states.async_set(
entity_id,
None,
{"device_class": device_class_state, "unit_of_measurement": unit_state},
)
expected_capabilities = {
"extra_fields": [
{
"description": {"suffix": PERCENTAGE},
"name": "above",
"optional": True,
"type": "float",
},
{
"description": {"suffix": PERCENTAGE},
"name": "below",
"optional": True,
"type": "float",
},
{"name": "for", "optional": True, "type": "positive_time_period_dict"},
]
}
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert len(triggers) == 1
for trigger in triggers:
trigger["entity_id"] = entity_registry.async_get(trigger["entity_id"]).entity_id
capabilities = await async_get_device_automation_capabilities(
hass, DeviceAutomationType.TRIGGER, trigger
)
assert capabilities == expected_capabilities
async def test_get_trigger_capabilities_none(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected capabilities from a sensor trigger."""
entity = MockSensor(
name="none sensor",
unique_id="unique_none",
)
setup_test_component_platform(hass, DOMAIN, [entity])
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
entry_none = entity_registry.async_get_or_create(
DOMAIN,
"test",
entity.unique_id,
)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
triggers = [
{
"platform": "device",
"device_id": "8770c43885354d5fa27604db6817f63f",
"domain": "sensor",
"entity_id": "01234567890123456789012345678901",
"type": "is_battery_level",
},
{
"platform": "device",
"device_id": "8770c43885354d5fa27604db6817f63f",
"domain": "sensor",
"entity_id": entry_none.id,
"type": "is_battery_level",
},
]
expected_capabilities = {}
for trigger in triggers:
capabilities = await async_get_device_automation_capabilities(
hass, DeviceAutomationType.TRIGGER, trigger
)
assert capabilities == expected_capabilities
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_fires_not_on_above_below(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test for value triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "battery_level",
},
"action": {"service": "test.automation"},
}
]
},
)
assert "must contain at least one of below, above" in caplog.text
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_fires_on_state_above(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for value triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "battery_level",
"above": 10,
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"bat_low {{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 9)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 11)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== f"bat_low device - {entry.entity_id} - 9 - 11 - None"
)
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_fires_on_state_below(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for value triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "battery_level",
"below": 10,
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"bat_low {{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 11)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 9)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== f"bat_low device - {entry.entity_id} - 11 - 9 - None"
)
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_fires_on_state_between(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for value triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "battery_level",
"above": 10,
"below": 20,
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"bat_low {{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 9)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 11)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== f"bat_low device - {entry.entity_id} - 9 - 11 - None"
)
hass.states.async_set(entry.entity_id, 21)
await hass.async_block_till_done()
assert len(service_calls) == 1
hass.states.async_set(entry.entity_id, 19)
await hass.async_block_till_done()
assert len(service_calls) == 2
assert (
service_calls[1].data["some"]
== f"bat_low device - {entry.entity_id} - 21 - 19 - None"
)
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_fires_on_state_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for value triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.entity_id,
"type": "battery_level",
"above": 10,
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"bat_low {{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 9)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 11)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== f"bat_low device - {entry.entity_id} - 9 - 11 - None"
)
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_if_fires_on_state_change_with_for(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for triggers firing with delay."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "battery_level",
"above": 10,
"for": {"seconds": 5},
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"turn_off {{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert len(service_calls) == 0
hass.states.async_set(entry.entity_id, 10)
hass.states.async_set(entry.entity_id, 11)
await hass.async_block_till_done()
assert len(service_calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(service_calls) == 1
await hass.async_block_till_done()
assert (
service_calls[0].data["some"]
== f"turn_off device - {entry.entity_id} - 10 - 11 - 0:00:05"
)

View File

@@ -0,0 +1,41 @@
"""The test for sensor helpers."""
import pytest
from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.components.sensor.helpers import async_parse_date_datetime
def test_async_parse_datetime(caplog: pytest.LogCaptureFixture) -> None:
"""Test async_parse_date_datetime."""
entity_id = "sensor.timestamp"
device_class = SensorDeviceClass.TIMESTAMP
assert (
async_parse_date_datetime(
"2021-12-12 12:12Z", entity_id, device_class
).isoformat()
== "2021-12-12T12:12:00+00:00"
)
assert not caplog.text
# No timezone
assert (
async_parse_date_datetime("2021-12-12 12:12", entity_id, device_class) is None
)
assert "sensor.timestamp rendered timestamp without timezone" in caplog.text
# Invalid timestamp
assert async_parse_date_datetime("12 past 12", entity_id, device_class) is None
assert "sensor.timestamp rendered invalid timestamp: 12 past 12" in caplog.text
device_class = SensorDeviceClass.DATE
caplog.clear()
assert (
async_parse_date_datetime("2021-12-12", entity_id, device_class).isoformat()
== "2021-12-12"
)
assert not caplog.text
# Invalid date
assert async_parse_date_datetime("December 12th", entity_id, device_class) is None
assert "sensor.timestamp rendered invalid date December 12th" in caplog.text

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,134 @@
"""The tests for sensor recorder platform can catch up."""
from datetime import datetime, timedelta
import threading
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components.recorder import get_instance
from homeassistant.components.recorder.history import get_significant_states
from homeassistant.components.recorder.statistics import (
get_latest_short_term_statistics_with_session,
statistics_during_period,
)
from homeassistant.components.recorder.util import session_scope
from homeassistant.core import CoreState
from homeassistant.helpers import recorder as recorder_helper
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from tests.common import async_test_home_assistant
from tests.components.recorder.common import (
async_wait_recording_done,
do_adhoc_statistics,
)
from tests.typing import RecorderInstanceGenerator
POWER_SENSOR_ATTRIBUTES = {
"device_class": "energy",
"state_class": "measurement",
"unit_of_measurement": "kWh",
}
@pytest.fixture(autouse=True)
def disable_db_issue_creation():
"""Disable the creation of the database issue."""
with patch(
"homeassistant.components.recorder.util._async_create_mariadb_range_index_regression_issue"
):
yield
@pytest.mark.timeout(25)
@pytest.mark.parametrize("persistent_database", [True])
@pytest.mark.parametrize("enable_missing_statistics", [True])
@pytest.mark.usefixtures("hass_storage") # Prevent test hass from writing to storage
async def test_compile_missing_statistics(
async_test_recorder: RecorderInstanceGenerator, freezer: FrozenDateTimeFactory
) -> None:
"""Test compile missing statistics."""
three_days_ago = datetime(2021, 1, 1, 0, 0, 0, tzinfo=dt_util.UTC)
start_time = three_days_ago + timedelta(days=3)
freezer.move_to(three_days_ago)
async with (
async_test_home_assistant(initial_state=CoreState.not_running) as hass,
async_test_recorder(hass, wait_recorder=False),
):
recorder_helper.async_initialize_recorder(hass)
await async_setup_component(hass, "sensor", {})
get_instance(hass).recorder_and_worker_thread_ids.add(threading.get_ident())
await hass.async_start()
await async_wait_recording_done(hass)
await async_wait_recording_done(hass)
hass.states.async_set("sensor.test1", "0", POWER_SENSOR_ATTRIBUTES)
await async_wait_recording_done(hass)
two_days_ago = three_days_ago + timedelta(days=1)
freezer.move_to(two_days_ago)
do_adhoc_statistics(hass, start=two_days_ago)
await async_wait_recording_done(hass)
with session_scope(hass=hass, read_only=True) as session:
latest = get_latest_short_term_statistics_with_session(
hass, session, {"sensor.test1"}, {"state", "sum"}
)
latest_stat = latest["sensor.test1"][0]
assert latest_stat["start"] == 1609545600.0
assert latest_stat["end"] == 1609545600.0 + 300
count = 1
past_time = two_days_ago
while past_time <= start_time:
freezer.move_to(past_time)
hass.states.async_set("sensor.test1", str(count), POWER_SENSOR_ATTRIBUTES)
past_time += timedelta(minutes=5)
count += 1
await async_wait_recording_done(hass)
states = get_significant_states(
hass, three_days_ago, past_time, ["sensor.test1"]
)
assert len(states["sensor.test1"]) == 577
await hass.async_stop()
await hass.async_block_till_done()
freezer.move_to(start_time)
async with (
async_test_home_assistant(initial_state=CoreState.not_running) as hass,
async_test_recorder(hass, wait_recorder=False),
):
recorder_helper.async_initialize_recorder(hass)
await async_setup_component(hass, "sensor", {})
hass.states.async_set("sensor.test1", "0", POWER_SENSOR_ATTRIBUTES)
get_instance(hass).recorder_and_worker_thread_ids.add(threading.get_ident())
await hass.async_start()
await async_wait_recording_done(hass)
await async_wait_recording_done(hass)
with session_scope(hass=hass, read_only=True) as session:
latest = get_latest_short_term_statistics_with_session(
hass, session, {"sensor.test1"}, {"state", "sum", "max", "mean", "min"}
)
latest_stat = latest["sensor.test1"][0]
assert latest_stat["start"] == 1609718100.0
assert latest_stat["end"] == 1609718100.0 + 300
assert latest_stat["mean"] == 576.0
assert latest_stat["min"] == 575.0
assert latest_stat["max"] == 576.0
stats = statistics_during_period(
hass,
two_days_ago,
start_time,
units={"energy": "kWh"},
statistic_ids={"sensor.test1"},
period="hour",
types={"mean"},
)
# Make sure we have 48 hours of statistics
assert len(stats["sensor.test1"]) == 48
# Make sure the last mean is 570.5
assert stats["sensor.test1"][-1]["mean"] == 570.5
await hass.async_stop()

View File

@@ -0,0 +1,68 @@
"""Test the sensor significant change platform."""
import pytest
from homeassistant.components.sensor import SensorDeviceClass, significant_change
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_UNIT_OF_MEASUREMENT,
UnitOfTemperature,
)
AQI_ATTRS = {
ATTR_DEVICE_CLASS: SensorDeviceClass.AQI,
}
BATTERY_ATTRS = {
ATTR_DEVICE_CLASS: SensorDeviceClass.BATTERY,
}
HUMIDITY_ATTRS = {
ATTR_DEVICE_CLASS: SensorDeviceClass.HUMIDITY,
}
TEMP_CELSIUS_ATTRS = {
ATTR_DEVICE_CLASS: SensorDeviceClass.TEMPERATURE,
ATTR_UNIT_OF_MEASUREMENT: UnitOfTemperature.CELSIUS,
}
TEMP_FREEDOM_ATTRS = {
ATTR_DEVICE_CLASS: SensorDeviceClass.TEMPERATURE,
ATTR_UNIT_OF_MEASUREMENT: UnitOfTemperature.FAHRENHEIT,
}
@pytest.mark.parametrize(
("old_state", "new_state", "attrs", "result"),
[
("0", "1", AQI_ATTRS, True),
("1", "0", AQI_ATTRS, True),
("0.1", "0.5", AQI_ATTRS, False),
("0.5", "0.1", AQI_ATTRS, False),
("99", "100", AQI_ATTRS, False),
("100", "99", AQI_ATTRS, False),
("101", "99", AQI_ATTRS, False),
("99", "101", AQI_ATTRS, True),
("100", "100", BATTERY_ATTRS, False),
("100", "99", BATTERY_ATTRS, True),
("100", "100", HUMIDITY_ATTRS, False),
("100", "99", HUMIDITY_ATTRS, True),
("12", "12", TEMP_CELSIUS_ATTRS, False),
("12", "13", TEMP_CELSIUS_ATTRS, True),
("12.1", "12.2", TEMP_CELSIUS_ATTRS, False),
("70", "71", TEMP_FREEDOM_ATTRS, True),
("70", "70.5", TEMP_FREEDOM_ATTRS, False),
("fail", "70", TEMP_FREEDOM_ATTRS, True),
("70", "fail", TEMP_FREEDOM_ATTRS, False),
],
)
async def test_significant_change_temperature(
old_state, new_state, attrs, result
) -> None:
"""Detect temperature significant changes."""
assert (
significant_change.async_check_significant_change(
None, old_state, attrs, new_state, attrs
)
is result
)

View File

@@ -0,0 +1,100 @@
"""Test the sensor websocket API."""
from pytest_unordered import unordered
from homeassistant.components.sensor.const import (
DOMAIN,
NON_NUMERIC_DEVICE_CLASSES,
SensorDeviceClass,
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.typing import WebSocketGenerator
async def test_device_class_units(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test we can get supported units."""
assert await async_setup_component(hass, DOMAIN, {})
client = await hass_ws_client(hass)
# Device class with units which sensor allows customizing & converting
await client.send_json_auto_id(
{
"type": "sensor/device_class_convertible_units",
"device_class": "speed",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"units": [
"Beaufort",
"ft/s",
"in/d",
"in/h",
"in/s",
"km/h",
"kn",
"m/s",
"mm/d",
"mm/h",
"mm/s",
"mph",
]
}
# Device class with units which include `None`
await client.send_json_auto_id(
{
"type": "sensor/device_class_convertible_units",
"device_class": "power_factor",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {"units": ["%", None]}
# Device class with units which sensor doesn't allow customizing & converting
await client.send_json_auto_id(
{
"type": "sensor/device_class_convertible_units",
"device_class": "pm1",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {"units": []}
# Unknown device class
await client.send_json_auto_id(
{
"type": "sensor/device_class_convertible_units",
"device_class": "kebabsås",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {"units": []}
async def test_numeric_device_classes(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test we can get numeric device classes."""
numeric_device_classes = set(SensorDeviceClass) - NON_NUMERIC_DEVICE_CLASSES
assert await async_setup_component(hass, DOMAIN, {})
client = await hass_ws_client(hass)
# Device class with units which sensor allows customizing & converting
await client.send_json_auto_id({"type": "sensor/numeric_device_classes"})
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"numeric_device_classes": unordered(list(numeric_device_classes))
}