init home-assistant

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

View File

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

View File

@@ -0,0 +1,142 @@
"""Fixtures for the lock entity platform tests."""
from collections.abc import Generator
from typing import Any
from unittest.mock import MagicMock
import pytest
from homeassistant.components.lock import (
DOMAIN as LOCK_DOMAIN,
LockEntity,
LockEntityFeature,
)
from homeassistant.config_entries import ConfigEntry, ConfigFlow
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from tests.common import (
MockConfigEntry,
MockModule,
MockPlatform,
mock_config_flow,
mock_integration,
mock_platform,
)
TEST_DOMAIN = "test"
class MockLock(LockEntity):
"""Mocked lock entity."""
def __init__(
self,
supported_features: LockEntityFeature = LockEntityFeature(0),
code_format: str | None = None,
) -> None:
"""Initialize the lock."""
self.calls_open = MagicMock()
self.calls_lock = MagicMock()
self.calls_unlock = MagicMock()
self._attr_code_format = code_format
self._attr_supported_features = supported_features
self._attr_has_entity_name = True
self._attr_name = "test_lock"
self._attr_unique_id = "very_unique_lock_id"
super().__init__()
def lock(self, **kwargs: Any) -> None:
"""Mock lock lock calls."""
self.calls_lock(**kwargs)
def unlock(self, **kwargs: Any) -> None:
"""Mock lock unlock calls."""
self.calls_unlock(**kwargs)
def open(self, **kwargs: Any) -> None:
"""Mock lock open calls."""
self.calls_open(**kwargs)
class MockFlow(ConfigFlow):
"""Test flow."""
@pytest.fixture(autouse=True)
def config_flow_fixture(hass: HomeAssistant) -> Generator[None]:
"""Mock config flow."""
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
with mock_config_flow(TEST_DOMAIN, MockFlow):
yield
@pytest.fixture
async def code_format() -> str | None:
"""Return the code format for the test lock entity."""
return None
@pytest.fixture(name="supported_features")
async def lock_supported_features() -> LockEntityFeature:
"""Return the supported features for the test lock entity."""
return LockEntityFeature.OPEN
@pytest.fixture(name="mock_lock_entity")
async def setup_lock_platform_test_entity(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
code_format: str | None,
supported_features: LockEntityFeature,
) -> MagicMock:
"""Set up lock entity using an entity platform."""
async def async_setup_entry_init(
hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Set up test config entry."""
await hass.config_entries.async_forward_entry_setups(
config_entry, [LOCK_DOMAIN]
)
return True
mock_integration(
hass,
MockModule(
TEST_DOMAIN,
async_setup_entry=async_setup_entry_init,
),
)
# Unnamed sensor without device class -> no name
entity = MockLock(
supported_features=supported_features,
code_format=code_format,
)
async def async_setup_entry_platform(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up test lock platform via config entry."""
async_add_entities([entity])
mock_platform(
hass,
f"{TEST_DOMAIN}.{LOCK_DOMAIN}",
MockPlatform(async_setup_entry=async_setup_entry_platform),
)
config_entry = MockConfigEntry(domain=TEST_DOMAIN)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(entity.entity_id)
assert state is not None
return entity

View File

@@ -0,0 +1,269 @@
"""The tests for Lock device actions."""
import pytest
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.lock import DOMAIN, LockEntityFeature
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
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 tests.common import (
MockConfigEntry,
async_get_device_automations,
async_mock_service,
)
@pytest.fixture(autouse=True, name="stub_blueprint_populate")
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
"""Stub copying the blueprints to the config folder."""
@pytest.mark.parametrize(
("set_state", "features_reg", "features_state", "expected_action_types"),
[
(False, 0, 0, []),
(False, LockEntityFeature.OPEN, 0, ["open"]),
(True, 0, 0, []),
(True, 0, LockEntityFeature.OPEN, ["open"]),
],
)
async def test_get_actions(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
set_state,
features_reg,
features_state,
expected_action_types,
) -> None:
"""Test we get the expected actions from a lock."""
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,
supported_features=features_reg,
)
if set_state:
hass.states.async_set(
f"{DOMAIN}.test_5678", "attributes", {"supported_features": features_state}
)
expected_actions = []
basic_action_types = ["lock", "unlock"]
expected_actions += [
{
"domain": DOMAIN,
"type": action,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
for action in basic_action_types
]
expected_actions += [
{
"domain": DOMAIN,
"type": action,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
for action in expected_action_types
]
actions = await async_get_device_automations(
hass, DeviceAutomationType.ACTION, device_entry.id
)
assert actions == unordered(expected_actions)
@pytest.mark.parametrize(
("hidden_by", "entity_category"),
[
(RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
],
)
async def test_get_actions_hidden_auxiliary(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by,
entity_category,
) -> None:
"""Test we get the expected actions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
supported_features=0,
)
expected_actions = []
expected_actions += [
{
"domain": DOMAIN,
"type": action,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": True},
}
for action in ("lock", "unlock")
]
actions = await async_get_device_automations(
hass, DeviceAutomationType.ACTION, device_entry.id
)
assert actions == unordered(expected_actions)
async def test_action(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for lock actions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event_lock"},
"action": {
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "lock",
},
},
{
"trigger": {"platform": "event", "event_type": "test_event_unlock"},
"action": {
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "unlock",
},
},
{
"trigger": {"platform": "event", "event_type": "test_event_open"},
"action": {
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "open",
},
},
]
},
)
await hass.async_block_till_done()
lock_calls = async_mock_service(hass, "lock", "lock")
unlock_calls = async_mock_service(hass, "lock", "unlock")
open_calls = async_mock_service(hass, "lock", "open")
hass.bus.async_fire("test_event_lock")
await hass.async_block_till_done()
assert len(lock_calls) == 1
assert len(unlock_calls) == 0
assert len(open_calls) == 0
hass.bus.async_fire("test_event_unlock")
await hass.async_block_till_done()
assert len(lock_calls) == 1
assert len(unlock_calls) == 1
assert len(open_calls) == 0
hass.bus.async_fire("test_event_open")
await hass.async_block_till_done()
assert len(lock_calls) == 1
assert len(unlock_calls) == 1
assert len(open_calls) == 1
assert lock_calls[0].domain == DOMAIN
assert lock_calls[0].service == "lock"
assert lock_calls[0].data == {"entity_id": entry.entity_id}
assert unlock_calls[0].domain == DOMAIN
assert unlock_calls[0].service == "unlock"
assert unlock_calls[0].data == {"entity_id": entry.entity_id}
assert open_calls[0].domain == DOMAIN
assert open_calls[0].service == "open"
assert open_calls[0].data == {"entity_id": entry.entity_id}
async def test_action_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for lock actions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event_lock"},
"action": {
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "lock",
},
},
]
},
)
await hass.async_block_till_done()
lock_calls = async_mock_service(hass, "lock", "lock")
hass.bus.async_fire("test_event_lock")
await hass.async_block_till_done()
assert len(lock_calls) == 1
assert lock_calls[0].domain == DOMAIN
assert lock_calls[0].service == "lock"
assert lock_calls[0].data == {"entity_id": entry.entity_id}

View File

@@ -0,0 +1,365 @@
"""The tests for Lock device conditions."""
import pytest
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.lock import DOMAIN, LockState
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, async_get_device_automations
@pytest.fixture(autouse=True, name="stub_blueprint_populate")
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
"""Stub copying the blueprints to the config folder."""
async def test_get_conditions(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected conditions from a lock."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
expected_conditions = [
{
"condition": "device",
"domain": DOMAIN,
"type": condition,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
for condition in (
"is_locked",
"is_unlocked",
"is_unlocking",
"is_locking",
"is_jammed",
"is_open",
"is_opening",
)
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
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,
)
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_locked",
"is_unlocked",
"is_unlocking",
"is_locking",
"is_jammed",
"is_open",
"is_opening",
)
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert conditions == unordered(expected_conditions)
async def test_if_state(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for turn_on and turn_off 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, LockState.LOCKED)
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_locked",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_locked - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event2"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_unlocked",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_unlocked - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event3"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_unlocking",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_unlocking - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event4"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_locking",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_locking - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event5"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_jammed",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_jammed - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event6"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_opening",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_opening - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event7"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_open",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_open - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
]
},
)
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["some"] == "is_locked - event - test_event1"
hass.states.async_set(entry.entity_id, LockState.UNLOCKED)
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(service_calls) == 2
assert service_calls[1].data["some"] == "is_unlocked - event - test_event2"
hass.states.async_set(entry.entity_id, LockState.UNLOCKING)
hass.bus.async_fire("test_event3")
await hass.async_block_till_done()
assert len(service_calls) == 3
assert service_calls[2].data["some"] == "is_unlocking - event - test_event3"
hass.states.async_set(entry.entity_id, LockState.LOCKING)
hass.bus.async_fire("test_event4")
await hass.async_block_till_done()
assert len(service_calls) == 4
assert service_calls[3].data["some"] == "is_locking - event - test_event4"
hass.states.async_set(entry.entity_id, LockState.JAMMED)
hass.bus.async_fire("test_event5")
await hass.async_block_till_done()
assert len(service_calls) == 5
assert service_calls[4].data["some"] == "is_jammed - event - test_event5"
hass.states.async_set(entry.entity_id, LockState.OPENING)
hass.bus.async_fire("test_event6")
await hass.async_block_till_done()
assert len(service_calls) == 6
assert service_calls[5].data["some"] == "is_opening - event - test_event6"
hass.states.async_set(entry.entity_id, LockState.OPEN)
hass.bus.async_fire("test_event7")
await hass.async_block_till_done()
assert len(service_calls) == 7
assert service_calls[6].data["some"] == "is_open - event - test_event7"
async def test_if_state_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for turn_on and turn_off 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, LockState.LOCKED)
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_locked",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_locked - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
]
},
)
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["some"] == "is_locked - event - test_event1"

View File

@@ -0,0 +1,563 @@
"""The tests for Lock device triggers."""
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.lock import DOMAIN, LockEntityFeature, LockState
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from tests.common import (
MockConfigEntry,
async_fire_time_changed,
async_get_device_automation_capabilities,
async_get_device_automations,
)
@pytest.fixture(autouse=True, name="stub_blueprint_populate")
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
"""Stub copying the blueprints to the config folder."""
async def test_get_triggers(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected triggers from a lock."""
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,
supported_features=LockEntityFeature.OPEN,
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
for trigger in (
"locked",
"unlocked",
"unlocking",
"locking",
"jammed",
"open",
"opening",
)
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
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,
supported_features=LockEntityFeature.OPEN,
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": True},
}
for trigger in (
"locked",
"unlocked",
"unlocking",
"locking",
"jammed",
"open",
"opening",
)
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert triggers == unordered(expected_triggers)
async def test_get_trigger_capabilities(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected capabilities from a lock."""
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_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert len(triggers) == 7
for trigger in triggers:
capabilities = await async_get_device_automation_capabilities(
hass, DeviceAutomationType.TRIGGER, trigger
)
assert capabilities == {
"extra_fields": [
{"name": "for", "optional": True, "type": "positive_time_period_dict"}
]
}
async def test_get_trigger_capabilities_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected capabilities from a lock."""
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_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert len(triggers) == 7
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 == {
"extra_fields": [
{"name": "for", "optional": True, "type": "positive_time_period_dict"}
]
}
async def test_if_fires_on_state_change(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for turn_on and turn_off triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, LockState.UNLOCKED)
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": "locked",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"locked - {{ trigger.platform}} - "
"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - "
"{{ trigger.to_state.state}} - {{ trigger.for }}"
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "unlocked",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"unlocked - {{ trigger.platform}} - "
"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - "
"{{ trigger.to_state.state}} - {{ trigger.for }}"
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "open",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"open - {{ trigger.platform}} - "
"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - "
"{{ trigger.to_state.state}} - {{ trigger.for }}"
)
},
},
},
]
},
)
# Fake that the entity is turning on.
hass.states.async_set(entry.entity_id, LockState.LOCKED)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== f"locked - device - {entry.entity_id} - unlocked - locked - None"
)
# Fake that the entity is turning off.
hass.states.async_set(entry.entity_id, LockState.UNLOCKED)
await hass.async_block_till_done()
assert len(service_calls) == 2
assert (
service_calls[1].data["some"]
== f"unlocked - device - {entry.entity_id} - locked - unlocked - None"
)
# Fake that the entity is opens.
hass.states.async_set(entry.entity_id, LockState.OPEN)
await hass.async_block_till_done()
assert len(service_calls) == 3
assert (
service_calls[2].data["some"]
== f"open - device - {entry.entity_id} - unlocked - open - None"
)
async def test_if_fires_on_state_change_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for turn_on and turn_off triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, LockState.UNLOCKED)
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": "locked",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"locked - {{ trigger.platform}} - "
"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - "
"{{ trigger.to_state.state}} - {{ trigger.for }}"
)
},
},
},
]
},
)
# Fake that the entity is turning on.
hass.states.async_set(entry.entity_id, LockState.LOCKED)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== f"locked - device - {entry.entity_id} - unlocked - locked - None"
)
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, LockState.UNLOCKED)
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": "locked",
"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 }}"
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "unlocking",
"for": {"seconds": 5},
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"turn_on {{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "jammed",
"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 }}"
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "locking",
"for": {"seconds": 5},
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"turn_on {{ trigger.platform }}"
" - {{ trigger.entity_id }}"
" - {{ trigger.from_state.state }}"
" - {{ trigger.to_state.state }}"
" - {{ trigger.for }}"
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "opening",
"for": {"seconds": 5},
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"turn_on {{ 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, LockState.LOCKED)
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} - unlocked - locked - 0:00:05"
)
hass.states.async_set(entry.entity_id, LockState.UNLOCKING)
await hass.async_block_till_done()
assert len(service_calls) == 1
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=16))
await hass.async_block_till_done()
assert len(service_calls) == 2
await hass.async_block_till_done()
assert (
service_calls[1].data["some"]
== f"turn_on device - {entry.entity_id} - locked - unlocking - 0:00:05"
)
hass.states.async_set(entry.entity_id, LockState.JAMMED)
await hass.async_block_till_done()
assert len(service_calls) == 2
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=21))
await hass.async_block_till_done()
assert len(service_calls) == 3
await hass.async_block_till_done()
assert (
service_calls[2].data["some"]
== f"turn_off device - {entry.entity_id} - unlocking - jammed - 0:00:05"
)
hass.states.async_set(entry.entity_id, LockState.LOCKING)
await hass.async_block_till_done()
assert len(service_calls) == 3
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=27))
await hass.async_block_till_done()
assert len(service_calls) == 4
await hass.async_block_till_done()
assert (
service_calls[3].data["some"]
== f"turn_on device - {entry.entity_id} - jammed - locking - 0:00:05"
)
hass.states.async_set(entry.entity_id, LockState.OPENING)
await hass.async_block_till_done()
assert len(service_calls) == 4
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=27))
await hass.async_block_till_done()
assert len(service_calls) == 5
await hass.async_block_till_done()
assert (
service_calls[4].data["some"]
== f"turn_on device - {entry.entity_id} - locking - opening - 0:00:05"
)

View File

@@ -0,0 +1,419 @@
"""The tests for the lock component."""
from __future__ import annotations
from enum import Enum
import re
from typing import Any
import pytest
from homeassistant.components import lock
from homeassistant.components.lock import (
ATTR_CODE,
CONF_DEFAULT_CODE,
DOMAIN,
SERVICE_LOCK,
SERVICE_OPEN,
SERVICE_UNLOCK,
LockEntityFeature,
LockState,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
import homeassistant.helpers.entity_registry as er
from homeassistant.helpers.typing import UNDEFINED, UndefinedType
from .conftest import MockLock
from tests.common import help_test_all, import_and_test_deprecated_constant_enum
async def help_test_async_lock_service(
hass: HomeAssistant,
entity_id: str,
service: str,
code: str | None | UndefinedType = UNDEFINED,
) -> None:
"""Help to lock a test lock."""
data: dict[str, Any] = {"entity_id": entity_id}
if code is not UNDEFINED:
data[ATTR_CODE] = code
await hass.services.async_call(DOMAIN, service, data, blocking=True)
async def test_lock_default(hass: HomeAssistant, mock_lock_entity: MockLock) -> None:
"""Test lock entity with defaults."""
assert mock_lock_entity.code_format is None
assert mock_lock_entity.state is None
assert mock_lock_entity.is_jammed is None
assert mock_lock_entity.is_locked is None
assert mock_lock_entity.is_locking is None
assert mock_lock_entity.is_unlocking is None
assert mock_lock_entity.is_opening is None
assert mock_lock_entity.is_open is None
async def test_lock_states(hass: HomeAssistant, mock_lock_entity: MockLock) -> None:
"""Test lock entity states."""
assert mock_lock_entity.state is None
mock_lock_entity._attr_is_locking = True
assert mock_lock_entity.is_locking
assert mock_lock_entity.state == LockState.LOCKING
mock_lock_entity._attr_is_locked = True
mock_lock_entity._attr_is_locking = False
assert mock_lock_entity.is_locked
assert mock_lock_entity.state == LockState.LOCKED
mock_lock_entity._attr_is_unlocking = True
assert mock_lock_entity.is_unlocking
assert mock_lock_entity.state == LockState.UNLOCKING
mock_lock_entity._attr_is_locked = False
mock_lock_entity._attr_is_unlocking = False
assert not mock_lock_entity.is_locked
assert mock_lock_entity.state == LockState.UNLOCKED
mock_lock_entity._attr_is_jammed = True
assert mock_lock_entity.is_jammed
assert mock_lock_entity.state == LockState.JAMMED
assert not mock_lock_entity.is_locked
mock_lock_entity._attr_is_jammed = False
mock_lock_entity._attr_is_opening = True
assert mock_lock_entity.is_opening
assert mock_lock_entity.state == LockState.OPENING
assert mock_lock_entity.is_opening
mock_lock_entity._attr_is_opening = False
mock_lock_entity._attr_is_open = True
assert not mock_lock_entity.is_opening
assert mock_lock_entity.state == LockState.OPEN
assert not mock_lock_entity.is_opening
assert mock_lock_entity.is_open
@pytest.mark.parametrize(
("code_format", "supported_features"),
[(r"^\d{4}$", LockEntityFeature.OPEN)],
)
async def test_set_mock_lock_options(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_lock_entity: MockLock,
) -> None:
"""Test mock attributes and default code stored in the registry."""
entity_registry.async_update_entity_options(
"lock.test_lock", "lock", {CONF_DEFAULT_CODE: "1234"}
)
await hass.async_block_till_done()
assert mock_lock_entity._lock_option_default_code == "1234"
state = hass.states.get(mock_lock_entity.entity_id)
assert state is not None
assert state.attributes["code_format"] == r"^\d{4}$"
assert state.attributes["supported_features"] == LockEntityFeature.OPEN
@pytest.mark.parametrize("code_format", [r"^\d{4}$"])
async def test_default_code_option_update(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_lock_entity: MockLock,
) -> None:
"""Test default code stored in the registry is updated."""
assert mock_lock_entity._lock_option_default_code == ""
entity_registry.async_update_entity_options(
"lock.test_lock", "lock", {CONF_DEFAULT_CODE: "4321"}
)
await hass.async_block_till_done()
assert mock_lock_entity._lock_option_default_code == "4321"
@pytest.mark.parametrize(
("code_format", "supported_features"),
[(r"^\d{4}$", LockEntityFeature.OPEN)],
)
async def test_lock_open_with_code(
hass: HomeAssistant, mock_lock_entity: MockLock
) -> None:
"""Test lock entity with open service."""
state = hass.states.get(mock_lock_entity.entity_id)
assert state.attributes["code_format"] == r"^\d{4}$"
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_OPEN
)
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_OPEN, code=""
)
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_OPEN, code="HELLO"
)
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_OPEN, code="1234"
)
assert mock_lock_entity.calls_open.call_count == 1
mock_lock_entity.calls_open.assert_called_with(code="1234")
@pytest.mark.parametrize(
("code_format", "supported_features"),
[(r"^\d{4}$", LockEntityFeature.OPEN)],
)
async def test_lock_lock_with_code(
hass: HomeAssistant, mock_lock_entity: MockLock
) -> None:
"""Test lock entity with open service."""
state = hass.states.get(mock_lock_entity.entity_id)
assert state.attributes["code_format"] == r"^\d{4}$"
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_UNLOCK, code="1234"
)
mock_lock_entity.calls_unlock.assert_called_with(code="1234")
assert mock_lock_entity.calls_lock.call_count == 0
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_LOCK
)
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_LOCK, code=""
)
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_LOCK, code="HELLO"
)
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_LOCK, code="1234"
)
assert mock_lock_entity.calls_lock.call_count == 1
mock_lock_entity.calls_lock.assert_called_with(code="1234")
@pytest.mark.parametrize(
("code_format", "supported_features"),
[(r"^\d{4}$", LockEntityFeature.OPEN)],
)
async def test_lock_unlock_with_code(
hass: HomeAssistant, mock_lock_entity: MockLock
) -> None:
"""Test unlock entity with open service."""
state = hass.states.get(mock_lock_entity.entity_id)
assert state.attributes["code_format"] == r"^\d{4}$"
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_LOCK, code="1234"
)
mock_lock_entity.calls_lock.assert_called_with(code="1234")
assert mock_lock_entity.calls_unlock.call_count == 0
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_UNLOCK
)
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_UNLOCK, code=""
)
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_UNLOCK, code="HELLO"
)
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_UNLOCK, code="1234"
)
assert mock_lock_entity.calls_unlock.call_count == 1
mock_lock_entity.calls_unlock.assert_called_with(code="1234")
@pytest.mark.parametrize(
("code_format", "supported_features"),
[(r"^\d{4}$", LockEntityFeature.OPEN)],
)
async def test_lock_with_illegal_code(
hass: HomeAssistant, mock_lock_entity: MockLock
) -> None:
"""Test lock entity with default code that does not match the code format."""
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_OPEN, code="123456"
)
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_LOCK, code="123456"
)
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_UNLOCK, code="123456"
)
@pytest.mark.parametrize(
("code_format", "supported_features"),
[(None, LockEntityFeature.OPEN)],
)
async def test_lock_with_no_code(
hass: HomeAssistant, mock_lock_entity: MockLock
) -> None:
"""Test lock entity without code."""
await help_test_async_lock_service(hass, mock_lock_entity.entity_id, SERVICE_OPEN)
mock_lock_entity.calls_open.assert_called_with()
await help_test_async_lock_service(hass, mock_lock_entity.entity_id, SERVICE_LOCK)
mock_lock_entity.calls_lock.assert_called_with()
await help_test_async_lock_service(hass, mock_lock_entity.entity_id, SERVICE_UNLOCK)
mock_lock_entity.calls_unlock.assert_called_with()
mock_lock_entity.calls_open.reset_mock()
mock_lock_entity.calls_lock.reset_mock()
mock_lock_entity.calls_unlock.reset_mock()
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_OPEN, code=""
)
mock_lock_entity.calls_open.assert_called_with()
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_LOCK, code=""
)
mock_lock_entity.calls_lock.assert_called_with()
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_UNLOCK, code=""
)
mock_lock_entity.calls_unlock.assert_called_with()
@pytest.mark.parametrize(
("code_format", "supported_features"),
[(r"^\d{4}$", LockEntityFeature.OPEN)],
)
async def test_lock_with_default_code(
hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_lock_entity: MockLock
) -> None:
"""Test lock entity with default code."""
entity_registry.async_update_entity_options(
"lock.test_lock", "lock", {CONF_DEFAULT_CODE: "1234"}
)
await hass.async_block_till_done()
assert mock_lock_entity.state_attributes == {"code_format": r"^\d{4}$"}
assert mock_lock_entity._lock_option_default_code == "1234"
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_OPEN, code="1234"
)
mock_lock_entity.calls_open.assert_called_with(code="1234")
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_LOCK, code="1234"
)
mock_lock_entity.calls_lock.assert_called_with(code="1234")
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_UNLOCK, code="1234"
)
mock_lock_entity.calls_unlock.assert_called_with(code="1234")
mock_lock_entity.calls_open.reset_mock()
mock_lock_entity.calls_lock.reset_mock()
mock_lock_entity.calls_unlock.reset_mock()
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_OPEN, code=""
)
mock_lock_entity.calls_open.assert_called_with(code="1234")
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_LOCK, code=""
)
mock_lock_entity.calls_lock.assert_called_with(code="1234")
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_UNLOCK, code=""
)
mock_lock_entity.calls_unlock.assert_called_with(code="1234")
@pytest.mark.parametrize(
("code_format", "supported_features"),
[(r"^\d{4}$", LockEntityFeature.OPEN)],
)
async def test_lock_with_illegal_default_code(
hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_lock_entity: MockLock
) -> None:
"""Test lock entity with illegal default code."""
entity_registry.async_update_entity_options(
"lock.test_lock", "lock", {CONF_DEFAULT_CODE: "123456"}
)
await hass.async_block_till_done()
assert mock_lock_entity.state_attributes == {"code_format": r"^\d{4}$"}
assert mock_lock_entity._lock_option_default_code == ""
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_OPEN
)
with pytest.raises(ServiceValidationError):
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_LOCK
)
with pytest.raises(
ServiceValidationError,
match=re.escape(
rf"The code for lock.test_lock doesn't match pattern ^\d{{{4}}}$"
),
) as exc:
await help_test_async_lock_service(
hass, mock_lock_entity.entity_id, SERVICE_UNLOCK
)
assert (
str(exc.value)
== rf"The code for lock.test_lock doesn't match pattern ^\d{{{4}}}$"
)
assert exc.value.translation_key == "add_default_code"
def test_all() -> None:
"""Test module.__all__ is correctly set."""
help_test_all(lock)
def _create_tuples(
enum: type[Enum], constant_prefix: str, remove_in_version: str
) -> list[tuple[Enum, str]]:
return [
(enum_field, constant_prefix, remove_in_version)
for enum_field in enum
if enum_field
not in [
lock.LockState.OPEN,
lock.LockState.OPENING,
]
]
@pytest.mark.parametrize(
("enum", "constant_prefix", "remove_in_version"),
_create_tuples(lock.LockState, "STATE_", "2025.10"),
)
def test_deprecated_constants(
caplog: pytest.LogCaptureFixture,
enum: Enum,
constant_prefix: str,
remove_in_version: str,
) -> None:
"""Test deprecated constants."""
import_and_test_deprecated_constant_enum(
caplog, lock, enum, constant_prefix, remove_in_version
)

View File

@@ -0,0 +1,67 @@
"""Test reproduce state for Lock."""
import pytest
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers.state import async_reproduce_state
from tests.common import async_mock_service
async def test_reproducing_states(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test reproducing Lock states."""
hass.states.async_set("lock.entity_locked", "locked", {})
hass.states.async_set("lock.entity_unlocked", "unlocked", {})
hass.states.async_set("lock.entity_opened", "open", {})
lock_calls = async_mock_service(hass, "lock", "lock")
unlock_calls = async_mock_service(hass, "lock", "unlock")
open_calls = async_mock_service(hass, "lock", "open")
# These calls should do nothing as entities already in desired state
await async_reproduce_state(
hass,
[
State("lock.entity_locked", "locked"),
State("lock.entity_unlocked", "unlocked", {}),
State("lock.entity_opened", "open", {}),
],
)
assert len(lock_calls) == 0
assert len(unlock_calls) == 0
assert len(open_calls) == 0
# Test invalid state is handled
await async_reproduce_state(hass, [State("lock.entity_locked", "not_supported")])
assert "not_supported" in caplog.text
assert len(lock_calls) == 0
assert len(unlock_calls) == 0
assert len(open_calls) == 0
# Make sure correct services are called
await async_reproduce_state(
hass,
[
State("lock.entity_locked", "open"),
State("lock.entity_unlocked", "locked"),
State("lock.entity_opened", "unlocked"),
# Should not raise
State("lock.non_existing", "on"),
],
)
assert len(lock_calls) == 1
assert lock_calls[0].domain == "lock"
assert lock_calls[0].data == {"entity_id": "lock.entity_unlocked"}
assert len(unlock_calls) == 1
assert unlock_calls[0].domain == "lock"
assert unlock_calls[0].data == {"entity_id": "lock.entity_opened"}
assert len(open_calls) == 1
assert open_calls[0].domain == "lock"
assert open_calls[0].data == {"entity_id": "lock.entity_locked"}

View File

@@ -0,0 +1,24 @@
"""Test the Lock significant change platform."""
from homeassistant.components.lock.significant_change import (
async_check_significant_change,
)
async def test_significant_change() -> None:
"""Detect Lock significant changes."""
old_attrs = {"attr_1": "a"}
new_attrs = {"attr_1": "b"}
assert (
async_check_significant_change(None, "locked", old_attrs, "locked", old_attrs)
is False
)
assert (
async_check_significant_change(None, "locked", old_attrs, "locked", new_attrs)
is False
)
assert (
async_check_significant_change(None, "locked", old_attrs, "unlocked", old_attrs)
is True
)