Clean up unnecessary registry mocks from helpers (#87734)

This commit is contained in:
Franck Nijhof 2023-02-09 02:15:29 +01:00 committed by GitHub
parent 1c02f19d9a
commit 80bf632e2d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 722 additions and 672 deletions

View File

@ -2,15 +2,9 @@
import pytest import pytest
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.helpers import area_registry from homeassistant.helpers import area_registry as ar
from tests.common import ANY, flush_store, mock_area_registry from tests.common import ANY, flush_store
@pytest.fixture
def registry(hass):
"""Return an empty, loaded, registry."""
return mock_area_registry(hass)
@pytest.fixture @pytest.fixture
@ -22,29 +16,29 @@ def update_events(hass):
def async_capture(event): def async_capture(event):
events.append(event.data) events.append(event.data)
hass.bus.async_listen(area_registry.EVENT_AREA_REGISTRY_UPDATED, async_capture) hass.bus.async_listen(ar.EVENT_AREA_REGISTRY_UPDATED, async_capture)
return events return events
async def test_list_areas(registry): async def test_list_areas(area_registry):
"""Make sure that we can read areas.""" """Make sure that we can read areas."""
registry.async_create("mock") area_registry.async_create("mock")
areas = registry.async_list_areas() areas = area_registry.async_list_areas()
assert len(areas) == len(registry.areas) assert len(areas) == len(area_registry.areas)
async def test_create_area(hass, registry, update_events): async def test_create_area(hass, area_registry, update_events):
"""Make sure that we can create an area.""" """Make sure that we can create an area."""
# Create area with only mandatory parameters # Create area with only mandatory parameters
area = registry.async_create("mock") area = area_registry.async_create("mock")
assert area == area_registry.AreaEntry( assert area == ar.AreaEntry(
name="mock", normalized_name=ANY, aliases=set(), id=ANY, picture=None name="mock", normalized_name=ANY, aliases=set(), id=ANY, picture=None
) )
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
await hass.async_block_till_done() await hass.async_block_till_done()
@ -53,18 +47,18 @@ async def test_create_area(hass, registry, update_events):
assert update_events[-1]["area_id"] == area.id assert update_events[-1]["area_id"] == area.id
# Create area with all parameters # Create area with all parameters
area = registry.async_create( area = area_registry.async_create(
"mock 2", aliases={"alias_1", "alias_2"}, picture="/image/example.png" "mock 2", aliases={"alias_1", "alias_2"}, picture="/image/example.png"
) )
assert area == area_registry.AreaEntry( assert area == ar.AreaEntry(
name="mock 2", name="mock 2",
normalized_name=ANY, normalized_name=ANY,
aliases={"alias_1", "alias_2"}, aliases={"alias_1", "alias_2"},
id=ANY, id=ANY,
picture="/image/example.png", picture="/image/example.png",
) )
assert len(registry.areas) == 2 assert len(area_registry.areas) == 2
await hass.async_block_till_done() await hass.async_block_till_done()
@ -73,39 +67,39 @@ async def test_create_area(hass, registry, update_events):
assert update_events[-1]["area_id"] == area.id assert update_events[-1]["area_id"] == area.id
async def test_create_area_with_name_already_in_use(hass, registry, update_events): async def test_create_area_with_name_already_in_use(hass, area_registry, update_events):
"""Make sure that we can't create an area with a name already in use.""" """Make sure that we can't create an area with a name already in use."""
area1 = registry.async_create("mock") area1 = area_registry.async_create("mock")
with pytest.raises(ValueError) as e_info: with pytest.raises(ValueError) as e_info:
area2 = registry.async_create("mock") area2 = area_registry.async_create("mock")
assert area1 != area2 assert area1 != area2
assert e_info == "The name mock 2 (mock2) is already in use" assert e_info == "The name mock 2 (mock2) is already in use"
await hass.async_block_till_done() await hass.async_block_till_done()
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
assert len(update_events) == 1 assert len(update_events) == 1
async def test_create_area_with_id_already_in_use(registry): async def test_create_area_with_id_already_in_use(area_registry):
"""Make sure that we can't create an area with a name already in use.""" """Make sure that we can't create an area with a name already in use."""
area1 = registry.async_create("mock") area1 = area_registry.async_create("mock")
updated_area1 = registry.async_update(area1.id, name="New Name") updated_area1 = area_registry.async_update(area1.id, name="New Name")
assert updated_area1.id == area1.id assert updated_area1.id == area1.id
area2 = registry.async_create("mock") area2 = area_registry.async_create("mock")
assert area2.id == "mock_2" assert area2.id == "mock_2"
async def test_delete_area(hass, registry, update_events): async def test_delete_area(hass, area_registry, update_events):
"""Make sure that we can delete an area.""" """Make sure that we can delete an area."""
area = registry.async_create("mock") area = area_registry.async_create("mock")
registry.async_delete(area.id) area_registry.async_delete(area.id)
assert not registry.areas assert not area_registry.areas
await hass.async_block_till_done() await hass.async_block_till_done()
@ -116,21 +110,21 @@ async def test_delete_area(hass, registry, update_events):
assert update_events[1]["area_id"] == area.id assert update_events[1]["area_id"] == area.id
async def test_delete_non_existing_area(registry): async def test_delete_non_existing_area(area_registry):
"""Make sure that we can't delete an area that doesn't exist.""" """Make sure that we can't delete an area that doesn't exist."""
registry.async_create("mock") area_registry.async_create("mock")
with pytest.raises(KeyError): with pytest.raises(KeyError):
await registry.async_delete("") await area_registry.async_delete("")
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
async def test_update_area(hass, registry, update_events): async def test_update_area(hass, area_registry, update_events):
"""Make sure that we can read areas.""" """Make sure that we can read areas."""
area = registry.async_create("mock") area = area_registry.async_create("mock")
updated_area = registry.async_update( updated_area = area_registry.async_update(
area.id, area.id,
aliases={"alias_1", "alias_2"}, aliases={"alias_1", "alias_2"},
name="mock1", name="mock1",
@ -138,14 +132,14 @@ async def test_update_area(hass, registry, update_events):
) )
assert updated_area != area assert updated_area != area
assert updated_area == area_registry.AreaEntry( assert updated_area == ar.AreaEntry(
name="mock1", name="mock1",
normalized_name=ANY, normalized_name=ANY,
aliases={"alias_1", "alias_2"}, aliases={"alias_1", "alias_2"},
id=ANY, id=ANY,
picture="/image/example.png", picture="/image/example.png",
) )
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
await hass.async_block_till_done() await hass.async_block_till_done()
@ -156,68 +150,68 @@ async def test_update_area(hass, registry, update_events):
assert update_events[1]["area_id"] == area.id assert update_events[1]["area_id"] == area.id
async def test_update_area_with_same_name(registry): async def test_update_area_with_same_name(area_registry):
"""Make sure that we can reapply the same name to the area.""" """Make sure that we can reapply the same name to the area."""
area = registry.async_create("mock") area = area_registry.async_create("mock")
updated_area = registry.async_update(area.id, name="mock") updated_area = area_registry.async_update(area.id, name="mock")
assert updated_area == area assert updated_area == area
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
async def test_update_area_with_same_name_change_case(registry): async def test_update_area_with_same_name_change_case(area_registry):
"""Make sure that we can reapply the same name with a different case to the area.""" """Make sure that we can reapply the same name with a different case to the area."""
area = registry.async_create("mock") area = area_registry.async_create("mock")
updated_area = registry.async_update(area.id, name="Mock") updated_area = area_registry.async_update(area.id, name="Mock")
assert updated_area.name == "Mock" assert updated_area.name == "Mock"
assert updated_area.id == area.id assert updated_area.id == area.id
assert updated_area.normalized_name == area.normalized_name assert updated_area.normalized_name == area.normalized_name
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
async def test_update_area_with_name_already_in_use(registry): async def test_update_area_with_name_already_in_use(area_registry):
"""Make sure that we can't update an area with a name already in use.""" """Make sure that we can't update an area with a name already in use."""
area1 = registry.async_create("mock1") area1 = area_registry.async_create("mock1")
area2 = registry.async_create("mock2") area2 = area_registry.async_create("mock2")
with pytest.raises(ValueError) as e_info: with pytest.raises(ValueError) as e_info:
registry.async_update(area1.id, name="mock2") area_registry.async_update(area1.id, name="mock2")
assert e_info == "The name mock 2 (mock2) is already in use" assert e_info == "The name mock 2 (mock2) is already in use"
assert area1.name == "mock1" assert area1.name == "mock1"
assert area2.name == "mock2" assert area2.name == "mock2"
assert len(registry.areas) == 2 assert len(area_registry.areas) == 2
async def test_update_area_with_normalized_name_already_in_use(registry): async def test_update_area_with_normalized_name_already_in_use(area_registry):
"""Make sure that we can't update an area with a normalized name already in use.""" """Make sure that we can't update an area with a normalized name already in use."""
area1 = registry.async_create("mock1") area1 = area_registry.async_create("mock1")
area2 = registry.async_create("Moc k2") area2 = area_registry.async_create("Moc k2")
with pytest.raises(ValueError) as e_info: with pytest.raises(ValueError) as e_info:
registry.async_update(area1.id, name="mock2") area_registry.async_update(area1.id, name="mock2")
assert e_info == "The name mock 2 (mock2) is already in use" assert e_info == "The name mock 2 (mock2) is already in use"
assert area1.name == "mock1" assert area1.name == "mock1"
assert area2.name == "Moc k2" assert area2.name == "Moc k2"
assert len(registry.areas) == 2 assert len(area_registry.areas) == 2
async def test_load_area(hass, registry): async def test_load_area(hass, area_registry):
"""Make sure that we can load/save data correctly.""" """Make sure that we can load/save data correctly."""
area1 = registry.async_create("mock1") area1 = area_registry.async_create("mock1")
area2 = registry.async_create("mock2") area2 = area_registry.async_create("mock2")
assert len(registry.areas) == 2 assert len(area_registry.areas) == 2
registry2 = area_registry.AreaRegistry(hass) registry2 = ar.AreaRegistry(hass)
await flush_store(registry._store) await flush_store(area_registry._store)
await registry2.async_load() await registry2.async_load()
assert list(registry.areas) == list(registry2.areas) assert list(area_registry.areas) == list(registry2.areas)
area1_registry2 = registry2.async_get_or_create("mock1") area1_registry2 = registry2.async_get_or_create("mock1")
assert area1_registry2.id == area1.id assert area1_registry2.id == area1.id
@ -228,9 +222,9 @@ async def test_load_area(hass, registry):
@pytest.mark.parametrize("load_registries", [False]) @pytest.mark.parametrize("load_registries", [False])
async def test_loading_area_from_storage(hass, hass_storage): async def test_loading_area_from_storage(hass, hass_storage):
"""Test loading stored areas on start.""" """Test loading stored areas on start."""
hass_storage[area_registry.STORAGE_KEY] = { hass_storage[ar.STORAGE_KEY] = {
"version": area_registry.STORAGE_VERSION_MAJOR, "version": ar.STORAGE_VERSION_MAJOR,
"minor_version": area_registry.STORAGE_VERSION_MINOR, "minor_version": ar.STORAGE_VERSION_MINOR,
"data": { "data": {
"areas": [ "areas": [
{ {
@ -243,8 +237,8 @@ async def test_loading_area_from_storage(hass, hass_storage):
}, },
} }
await area_registry.async_load(hass) await ar.async_load(hass)
registry = area_registry.async_get(hass) registry = ar.async_get(hass)
assert len(registry.areas) == 1 assert len(registry.areas) == 1
@ -252,13 +246,13 @@ async def test_loading_area_from_storage(hass, hass_storage):
@pytest.mark.parametrize("load_registries", [False]) @pytest.mark.parametrize("load_registries", [False])
async def test_migration_from_1_1(hass, hass_storage): async def test_migration_from_1_1(hass, hass_storage):
"""Test migration from version 1.1.""" """Test migration from version 1.1."""
hass_storage[area_registry.STORAGE_KEY] = { hass_storage[ar.STORAGE_KEY] = {
"version": 1, "version": 1,
"data": {"areas": [{"id": "12345A", "name": "mock"}]}, "data": {"areas": [{"id": "12345A", "name": "mock"}]},
} }
await area_registry.async_load(hass) await ar.async_load(hass)
registry = area_registry.async_get(hass) registry = ar.async_get(hass)
# Test data was loaded # Test data was loaded
entry = registry.async_get_or_create("mock") entry = registry.async_get_or_create("mock")
@ -266,49 +260,49 @@ async def test_migration_from_1_1(hass, hass_storage):
# Check we store migrated data # Check we store migrated data
await flush_store(registry._store) await flush_store(registry._store)
assert hass_storage[area_registry.STORAGE_KEY] == { assert hass_storage[ar.STORAGE_KEY] == {
"version": area_registry.STORAGE_VERSION_MAJOR, "version": ar.STORAGE_VERSION_MAJOR,
"minor_version": area_registry.STORAGE_VERSION_MINOR, "minor_version": ar.STORAGE_VERSION_MINOR,
"key": area_registry.STORAGE_KEY, "key": ar.STORAGE_KEY,
"data": { "data": {
"areas": [{"aliases": [], "id": "12345A", "name": "mock", "picture": None}] "areas": [{"aliases": [], "id": "12345A", "name": "mock", "picture": None}]
}, },
} }
async def test_async_get_or_create(hass, registry): async def test_async_get_or_create(area_registry):
"""Make sure we can get the area by name.""" """Make sure we can get the area by name."""
area = registry.async_get_or_create("Mock1") area = area_registry.async_get_or_create("Mock1")
area2 = registry.async_get_or_create("mock1") area2 = area_registry.async_get_or_create("mock1")
area3 = registry.async_get_or_create("mock 1") area3 = area_registry.async_get_or_create("mock 1")
assert area == area2 assert area == area2
assert area == area3 assert area == area3
assert area2 == area3 assert area2 == area3
async def test_async_get_area_by_name(hass, registry): async def test_async_get_area_by_name(area_registry):
"""Make sure we can get the area by name.""" """Make sure we can get the area by name."""
registry.async_create("Mock1") area_registry.async_create("Mock1")
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
assert registry.async_get_area_by_name("M o c k 1").normalized_name == "mock1" assert area_registry.async_get_area_by_name("M o c k 1").normalized_name == "mock1"
async def test_async_get_area_by_name_not_found(hass, registry): async def test_async_get_area_by_name_not_found(area_registry):
"""Make sure we return None for non-existent areas.""" """Make sure we return None for non-existent areas."""
registry.async_create("Mock1") area_registry.async_create("Mock1")
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
assert registry.async_get_area_by_name("non_exist") is None assert area_registry.async_get_area_by_name("non_exist") is None
async def test_async_get_area(hass, registry): async def test_async_get_area(area_registry):
"""Make sure we can get the area by id.""" """Make sure we can get the area by id."""
area = registry.async_create("Mock1") area = area_registry.async_create("Mock1")
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
assert registry.async_get_area(area.id).normalized_name == "mock1" assert area_registry.async_get_area(area.id).normalized_name == "mock1"

File diff suppressed because it is too large Load Diff

View File

@ -776,19 +776,21 @@ async def test_removing_entity_unavailable(hass: HomeAssistant) -> None:
assert state.state == STATE_UNAVAILABLE assert state.state == STATE_UNAVAILABLE
async def test_get_supported_features_entity_registry(hass: HomeAssistant) -> None: async def test_get_supported_features_entity_registry(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test get_supported_features falls back to entity registry.""" """Test get_supported_features falls back to entity registry."""
entity_reg = mock_registry(hass) entity_id = entity_registry.async_get_or_create(
entity_id = entity_reg.async_get_or_create(
"hello", "world", "5678", supported_features=456 "hello", "world", "5678", supported_features=456
).entity_id ).entity_id
assert entity.get_supported_features(hass, entity_id) == 456 assert entity.get_supported_features(hass, entity_id) == 456
async def test_get_supported_features_prioritize_state(hass: HomeAssistant) -> None: async def test_get_supported_features_prioritize_state(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test get_supported_features gives priority to state.""" """Test get_supported_features gives priority to state."""
entity_reg = mock_registry(hass) entity_id = entity_registry.async_get_or_create(
entity_id = entity_reg.async_get_or_create(
"hello", "world", "5678", supported_features=456 "hello", "world", "5678", supported_features=456
).entity_id ).entity_id
assert entity.get_supported_features(hass, entity_id) == 456 assert entity.get_supported_features(hass, entity_id) == 456

View File

@ -508,13 +508,14 @@ async def test_using_prescribed_entity_id_with_unique_id(hass: HomeAssistant) ->
async def test_using_prescribed_entity_id_which_is_registered( async def test_using_prescribed_entity_id_which_is_registered(
hass: HomeAssistant, hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None: ) -> None:
"""Test not allowing predefined entity ID that already registered.""" """Test not allowing predefined entity ID that already registered."""
component = EntityComponent(_LOGGER, DOMAIN, hass) component = EntityComponent(_LOGGER, DOMAIN, hass)
registry = mock_registry(hass)
# Register test_domain.world # Register test_domain.world
registry.async_get_or_create(DOMAIN, "test", "1234", suggested_object_id="world") entity_registry.async_get_or_create(
DOMAIN, "test", "1234", suggested_object_id="world"
)
# This entity_id will be rewritten # This entity_id will be rewritten
await component.async_add_entities([MockEntity(entity_id="test_domain.world")]) await component.async_add_entities([MockEntity(entity_id="test_domain.world")])
@ -522,13 +523,16 @@ async def test_using_prescribed_entity_id_which_is_registered(
assert "test_domain.world_2" in hass.states.async_entity_ids() assert "test_domain.world_2" in hass.states.async_entity_ids()
async def test_name_which_conflict_with_registered(hass: HomeAssistant) -> None: async def test_name_which_conflict_with_registered(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test not generating conflicting entity ID based on name.""" """Test not generating conflicting entity ID based on name."""
component = EntityComponent(_LOGGER, DOMAIN, hass) component = EntityComponent(_LOGGER, DOMAIN, hass)
registry = mock_registry(hass)
# Register test_domain.world # Register test_domain.world
registry.async_get_or_create(DOMAIN, "test", "1234", suggested_object_id="world") entity_registry.async_get_or_create(
DOMAIN, "test", "1234", suggested_object_id="world"
)
await component.async_add_entities([MockEntity(name="world")]) await component.async_add_entities([MockEntity(name="world")])
@ -570,9 +574,10 @@ async def test_overriding_name_from_registry(hass: HomeAssistant) -> None:
assert state.name == "Overridden" assert state.name == "Overridden"
async def test_registry_respect_entity_namespace(hass: HomeAssistant) -> None: async def test_registry_respect_entity_namespace(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test that the registry respects entity namespace.""" """Test that the registry respects entity namespace."""
mock_registry(hass)
platform = MockEntityPlatform(hass, entity_namespace="ns") platform = MockEntityPlatform(hass, entity_namespace="ns")
entity = MockEntity(unique_id="1234", name="Device Name") entity = MockEntity(unique_id="1234", name="Device Name")
await platform.async_add_entities([entity]) await platform.async_add_entities([entity])
@ -652,9 +657,10 @@ async def test_entity_registry_updates_name(hass: HomeAssistant) -> None:
assert state.name == "after update" assert state.name == "after update"
async def test_setup_entry(hass: HomeAssistant) -> None: async def test_setup_entry(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test we can setup an entry.""" """Test we can setup an entry."""
registry = mock_registry(hass)
async def async_setup_entry(hass, config_entry, async_add_entities): async def async_setup_entry(hass, config_entry, async_add_entities):
"""Mock setup entry method.""" """Mock setup entry method."""
@ -672,8 +678,10 @@ async def test_setup_entry(hass: HomeAssistant) -> None:
full_name = f"{entity_platform.domain}.{config_entry.domain}" full_name = f"{entity_platform.domain}.{config_entry.domain}"
assert full_name in hass.config.components assert full_name in hass.config.components
assert len(hass.states.async_entity_ids()) == 1 assert len(hass.states.async_entity_ids()) == 1
assert len(registry.entities) == 1 assert len(entity_registry.entities) == 1
assert registry.entities["test_domain.test1"].config_entry_id == "super-mock-id" assert (
entity_registry.entities["test_domain.test1"].config_entry_id == "super-mock-id"
)
async def test_setup_entry_platform_not_ready(hass, caplog): async def test_setup_entry_platform_not_ready(hass, caplog):
@ -1275,10 +1283,11 @@ async def test_entity_info_added_to_entity_registry(hass: HomeAssistant) -> None
) )
async def test_override_restored_entities(hass: HomeAssistant) -> None: async def test_override_restored_entities(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test that we allow overriding restored entities.""" """Test that we allow overriding restored entities."""
registry = mock_registry(hass) entity_registry.async_get_or_create(
registry.async_get_or_create(
"test_domain", "test_domain", "1234", suggested_object_id="world" "test_domain", "test_domain", "1234", suggested_object_id="world"
) )
@ -1369,9 +1378,10 @@ class MockBlockingEntity(MockEntity):
await asyncio.sleep(1000) await asyncio.sleep(1000)
async def test_setup_entry_with_entities_that_block_forever(hass, caplog): async def test_setup_entry_with_entities_that_block_forever(
hass, caplog, entity_registry
):
"""Test we cancel adding entities when we reach the timeout.""" """Test we cancel adding entities when we reach the timeout."""
registry = mock_registry(hass)
async def async_setup_entry(hass, config_entry, async_add_entities): async def async_setup_entry(hass, config_entry, async_add_entities):
"""Mock setup entry method.""" """Mock setup entry method."""
@ -1392,7 +1402,7 @@ async def test_setup_entry_with_entities_that_block_forever(hass, caplog):
full_name = f"{mock_entity_platform.domain}.{config_entry.domain}" full_name = f"{mock_entity_platform.domain}.{config_entry.domain}"
assert full_name in hass.config.components assert full_name in hass.config.components
assert len(hass.states.async_entity_ids()) == 0 assert len(hass.states.async_entity_ids()) == 0
assert len(registry.entities) == 1 assert len(entity_registry.entities) == 1
assert "Timed out adding entities" in caplog.text assert "Timed out adding entities" in caplog.text
assert "test_domain.test1" in caplog.text assert "test_domain.test1" in caplog.text
assert "test_domain" in caplog.text assert "test_domain" in caplog.text

View File

@ -11,22 +11,11 @@ from homeassistant.exceptions import MaxLengthExceeded
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity import EntityCategory
from tests.common import ( from tests.common import MockConfigEntry, flush_store
MockConfigEntry,
flush_store,
mock_device_registry,
mock_registry,
)
YAML__OPEN_PATH = "homeassistant.util.yaml.loader.open" YAML__OPEN_PATH = "homeassistant.util.yaml.loader.open"
@pytest.fixture
def registry(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
@pytest.fixture @pytest.fixture
def update_events(hass): def update_events(hass):
"""Capture update events.""" """Capture update events."""
@ -41,14 +30,14 @@ def update_events(hass):
return events return events
async def test_get_or_create_returns_same_entry(hass, registry, update_events): async def test_get_or_create_returns_same_entry(hass, entity_registry, update_events):
"""Make sure we do not duplicate entries.""" """Make sure we do not duplicate entries."""
entry = registry.async_get_or_create("light", "hue", "1234") entry = entity_registry.async_get_or_create("light", "hue", "1234")
entry2 = registry.async_get_or_create("light", "hue", "1234") entry2 = entity_registry.async_get_or_create("light", "hue", "1234")
await hass.async_block_till_done() await hass.async_block_till_done()
assert len(registry.entities) == 1 assert len(entity_registry.entities) == 1
assert entry is entry2 assert entry is entry2
assert entry.entity_id == "light.hue_1234" assert entry.entity_id == "light.hue_1234"
assert len(update_events) == 1 assert len(update_events) == 1
@ -56,20 +45,20 @@ async def test_get_or_create_returns_same_entry(hass, registry, update_events):
assert update_events[0]["entity_id"] == entry.entity_id assert update_events[0]["entity_id"] == entry.entity_id
def test_get_or_create_suggested_object_id(registry): def test_get_or_create_suggested_object_id(entity_registry):
"""Test that suggested_object_id works.""" """Test that suggested_object_id works."""
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "1234", suggested_object_id="beer" "light", "hue", "1234", suggested_object_id="beer"
) )
assert entry.entity_id == "light.beer" assert entry.entity_id == "light.beer"
def test_get_or_create_updates_data(registry): def test_get_or_create_updates_data(entity_registry):
"""Test that we update data in get_or_create.""" """Test that we update data in get_or_create."""
orig_config_entry = MockConfigEntry(domain="light") orig_config_entry = MockConfigEntry(domain="light")
orig_entry = registry.async_get_or_create( orig_entry = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
@ -113,7 +102,7 @@ def test_get_or_create_updates_data(registry):
new_config_entry = MockConfigEntry(domain="light") new_config_entry = MockConfigEntry(domain="light")
new_entry = registry.async_get_or_create( new_entry = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
@ -157,7 +146,7 @@ def test_get_or_create_updates_data(registry):
unit_of_measurement="updated-unit_of_measurement", unit_of_measurement="updated-unit_of_measurement",
) )
new_entry = registry.async_get_or_create( new_entry = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
@ -202,12 +191,12 @@ def test_get_or_create_updates_data(registry):
) )
def test_get_or_create_suggested_object_id_conflict_register(registry): def test_get_or_create_suggested_object_id_conflict_register(entity_registry):
"""Test that we don't generate an entity id that is already registered.""" """Test that we don't generate an entity id that is already registered."""
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "1234", suggested_object_id="beer" "light", "hue", "1234", suggested_object_id="beer"
) )
entry2 = registry.async_get_or_create( entry2 = entity_registry.async_get_or_create(
"light", "hue", "5678", suggested_object_id="beer" "light", "hue", "5678", suggested_object_id="beer"
) )
@ -215,27 +204,27 @@ def test_get_or_create_suggested_object_id_conflict_register(registry):
assert entry2.entity_id == "light.beer_2" assert entry2.entity_id == "light.beer_2"
def test_get_or_create_suggested_object_id_conflict_existing(hass, registry): def test_get_or_create_suggested_object_id_conflict_existing(hass, entity_registry):
"""Test that we don't generate an entity id that currently exists.""" """Test that we don't generate an entity id that currently exists."""
hass.states.async_set("light.hue_1234", "on") hass.states.async_set("light.hue_1234", "on")
entry = registry.async_get_or_create("light", "hue", "1234") entry = entity_registry.async_get_or_create("light", "hue", "1234")
assert entry.entity_id == "light.hue_1234_2" assert entry.entity_id == "light.hue_1234_2"
def test_create_triggers_save(hass, registry): def test_create_triggers_save(entity_registry):
"""Test that registering entry triggers a save.""" """Test that registering entry triggers a save."""
with patch.object(registry, "async_schedule_save") as mock_schedule_save: with patch.object(entity_registry, "async_schedule_save") as mock_schedule_save:
registry.async_get_or_create("light", "hue", "1234") entity_registry.async_get_or_create("light", "hue", "1234")
assert len(mock_schedule_save.mock_calls) == 1 assert len(mock_schedule_save.mock_calls) == 1
async def test_loading_saving_data(hass, registry): async def test_loading_saving_data(hass, entity_registry):
"""Test that we load/save data correctly.""" """Test that we load/save data correctly."""
mock_config = MockConfigEntry(domain="light") mock_config = MockConfigEntry(domain="light")
orig_entry1 = registry.async_get_or_create("light", "hue", "1234") orig_entry1 = entity_registry.async_get_or_create("light", "hue", "1234")
orig_entry2 = registry.async_get_or_create( orig_entry2 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
@ -253,7 +242,7 @@ async def test_loading_saving_data(hass, registry):
translation_key="initial-translation_key", translation_key="initial-translation_key",
unit_of_measurement="initial-unit_of_measurement", unit_of_measurement="initial-unit_of_measurement",
) )
registry.async_update_entity( entity_registry.async_update_entity(
orig_entry2.entity_id, orig_entry2.entity_id,
aliases={"initial_alias_1", "initial_alias_2"}, aliases={"initial_alias_1", "initial_alias_2"},
area_id="mock-area-id", area_id="mock-area-id",
@ -261,22 +250,22 @@ async def test_loading_saving_data(hass, registry):
name="User Name", name="User Name",
icon="hass:user-icon", icon="hass:user-icon",
) )
registry.async_update_entity_options( entity_registry.async_update_entity_options(
orig_entry2.entity_id, "light", {"minimum_brightness": 20} orig_entry2.entity_id, "light", {"minimum_brightness": 20}
) )
orig_entry2 = registry.async_get(orig_entry2.entity_id) orig_entry2 = entity_registry.async_get(orig_entry2.entity_id)
assert len(registry.entities) == 2 assert len(entity_registry.entities) == 2
# Now load written data in new registry # Now load written data in new registry
registry2 = er.EntityRegistry(hass) registry2 = er.EntityRegistry(hass)
await flush_store(registry._store) await flush_store(entity_registry._store)
await registry2.async_load() await registry2.async_load()
# Ensure same order # Ensure same order
assert list(registry.entities) == list(registry2.entities) assert list(entity_registry.entities) == list(registry2.entities)
new_entry1 = registry.async_get_or_create("light", "hue", "1234") new_entry1 = entity_registry.async_get_or_create("light", "hue", "1234")
new_entry2 = registry.async_get_or_create("light", "hue", "5678") new_entry2 = entity_registry.async_get_or_create("light", "hue", "5678")
assert orig_entry1 == new_entry1 assert orig_entry1 == new_entry1
assert orig_entry2 == new_entry2 assert orig_entry2 == new_entry2
@ -301,24 +290,30 @@ async def test_loading_saving_data(hass, registry):
assert new_entry2.unit_of_measurement == "initial-unit_of_measurement" assert new_entry2.unit_of_measurement == "initial-unit_of_measurement"
def test_generate_entity_considers_registered_entities(registry): def test_generate_entity_considers_registered_entities(entity_registry):
"""Test that we don't create entity id that are already registered.""" """Test that we don't create entity id that are already registered."""
entry = registry.async_get_or_create("light", "hue", "1234") entry = entity_registry.async_get_or_create("light", "hue", "1234")
assert entry.entity_id == "light.hue_1234" assert entry.entity_id == "light.hue_1234"
assert registry.async_generate_entity_id("light", "hue_1234") == "light.hue_1234_2" assert (
entity_registry.async_generate_entity_id("light", "hue_1234")
== "light.hue_1234_2"
)
def test_generate_entity_considers_existing_entities(hass, registry): def test_generate_entity_considers_existing_entities(hass, entity_registry):
"""Test that we don't create entity id that currently exists.""" """Test that we don't create entity id that currently exists."""
hass.states.async_set("light.kitchen", "on") hass.states.async_set("light.kitchen", "on")
assert registry.async_generate_entity_id("light", "kitchen") == "light.kitchen_2" assert (
entity_registry.async_generate_entity_id("light", "kitchen")
== "light.kitchen_2"
)
def test_is_registered(registry): def test_is_registered(entity_registry):
"""Test that is_registered works.""" """Test that is_registered works."""
entry = registry.async_get_or_create("light", "hue", "1234") entry = entity_registry.async_get_or_create("light", "hue", "1234")
assert registry.async_is_registered(entry.entity_id) assert entity_registry.async_is_registered(entry.entity_id)
assert not registry.async_is_registered("light.non_existing") assert not entity_registry.async_is_registered("light.non_existing")
@pytest.mark.parametrize("load_registries", [False]) @pytest.mark.parametrize("load_registries", [False])
@ -403,23 +398,25 @@ async def test_filter_on_load(hass, hass_storage):
assert entry_system_category.entity_category is None assert entry_system_category.entity_category is None
def test_async_get_entity_id(registry): def test_async_get_entity_id(entity_registry):
"""Test that entity_id is returned.""" """Test that entity_id is returned."""
entry = registry.async_get_or_create("light", "hue", "1234") entry = entity_registry.async_get_or_create("light", "hue", "1234")
assert entry.entity_id == "light.hue_1234" assert entry.entity_id == "light.hue_1234"
assert registry.async_get_entity_id("light", "hue", "1234") == "light.hue_1234" assert (
assert registry.async_get_entity_id("light", "hue", "123") is None entity_registry.async_get_entity_id("light", "hue", "1234") == "light.hue_1234"
)
assert entity_registry.async_get_entity_id("light", "hue", "123") is None
async def test_updating_config_entry_id(hass, registry, update_events): async def test_updating_config_entry_id(hass, entity_registry, update_events):
"""Test that we update config entry id in registry.""" """Test that we update config entry id in registry."""
mock_config_1 = MockConfigEntry(domain="light", entry_id="mock-id-1") mock_config_1 = MockConfigEntry(domain="light", entry_id="mock-id-1")
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "5678", config_entry=mock_config_1 "light", "hue", "5678", config_entry=mock_config_1
) )
mock_config_2 = MockConfigEntry(domain="light", entry_id="mock-id-2") mock_config_2 = MockConfigEntry(domain="light", entry_id="mock-id-2")
entry2 = registry.async_get_or_create( entry2 = entity_registry.async_get_or_create(
"light", "hue", "5678", config_entry=mock_config_2 "light", "hue", "5678", config_entry=mock_config_2
) )
assert entry.entity_id == entry2.entity_id assert entry.entity_id == entry2.entity_id
@ -435,17 +432,17 @@ async def test_updating_config_entry_id(hass, registry, update_events):
assert update_events[1]["changes"] == {"config_entry_id": "mock-id-1"} assert update_events[1]["changes"] == {"config_entry_id": "mock-id-1"}
async def test_removing_config_entry_id(hass, registry, update_events): async def test_removing_config_entry_id(hass, entity_registry, update_events):
"""Test that we update config entry id in registry.""" """Test that we update config entry id in registry."""
mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1") mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1")
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "5678", config_entry=mock_config "light", "hue", "5678", config_entry=mock_config
) )
assert entry.config_entry_id == "mock-id-1" assert entry.config_entry_id == "mock-id-1"
registry.async_clear_config_entry("mock-id-1") entity_registry.async_clear_config_entry("mock-id-1")
assert not registry.entities assert not entity_registry.entities
await hass.async_block_till_done() await hass.async_block_till_done()
@ -456,14 +453,16 @@ async def test_removing_config_entry_id(hass, registry, update_events):
assert update_events[1]["entity_id"] == entry.entity_id assert update_events[1]["entity_id"] == entry.entity_id
async def test_removing_area_id(registry): async def test_removing_area_id(entity_registry):
"""Make sure we can clear area id.""" """Make sure we can clear area id."""
entry = registry.async_get_or_create("light", "hue", "5678") entry = entity_registry.async_get_or_create("light", "hue", "5678")
entry_w_area = registry.async_update_entity(entry.entity_id, area_id="12345A") entry_w_area = entity_registry.async_update_entity(
entry.entity_id, area_id="12345A"
)
registry.async_clear_area_id("12345A") entity_registry.async_clear_area_id("12345A")
entry_wo_area = registry.async_get(entry.entity_id) entry_wo_area = entity_registry.async_get(entry.entity_id)
assert not entry_wo_area.area_id assert not entry_wo_area.area_id
assert entry_w_area != entry_wo_area assert entry_w_area != entry_wo_area
@ -568,69 +567,81 @@ async def test_migration_1_7(hass, hass_storage):
assert entry.original_device_class == "class_by_integration" assert entry.original_device_class == "class_by_integration"
async def test_update_entity_unique_id(registry): async def test_update_entity_unique_id(entity_registry):
"""Test entity's unique_id is updated.""" """Test entity's unique_id is updated."""
mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1") mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1")
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "5678", config_entry=mock_config "light", "hue", "5678", config_entry=mock_config
) )
assert registry.async_get_entity_id("light", "hue", "5678") == entry.entity_id assert (
entity_registry.async_get_entity_id("light", "hue", "5678") == entry.entity_id
)
new_unique_id = "1234" new_unique_id = "1234"
with patch.object(registry, "async_schedule_save") as mock_schedule_save: with patch.object(entity_registry, "async_schedule_save") as mock_schedule_save:
updated_entry = registry.async_update_entity( updated_entry = entity_registry.async_update_entity(
entry.entity_id, new_unique_id=new_unique_id entry.entity_id, new_unique_id=new_unique_id
) )
assert updated_entry != entry assert updated_entry != entry
assert updated_entry.unique_id == new_unique_id assert updated_entry.unique_id == new_unique_id
assert mock_schedule_save.call_count == 1 assert mock_schedule_save.call_count == 1
assert registry.async_get_entity_id("light", "hue", "5678") is None assert entity_registry.async_get_entity_id("light", "hue", "5678") is None
assert registry.async_get_entity_id("light", "hue", "1234") == entry.entity_id assert (
entity_registry.async_get_entity_id("light", "hue", "1234") == entry.entity_id
)
async def test_update_entity_unique_id_conflict(registry): async def test_update_entity_unique_id_conflict(entity_registry):
"""Test migration raises when unique_id already in use.""" """Test migration raises when unique_id already in use."""
mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1") mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1")
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "5678", config_entry=mock_config "light", "hue", "5678", config_entry=mock_config
) )
entry2 = registry.async_get_or_create( entry2 = entity_registry.async_get_or_create(
"light", "hue", "1234", config_entry=mock_config "light", "hue", "1234", config_entry=mock_config
) )
with patch.object( with patch.object(
registry, "async_schedule_save" entity_registry, "async_schedule_save"
) as mock_schedule_save, pytest.raises(ValueError): ) as mock_schedule_save, pytest.raises(ValueError):
registry.async_update_entity(entry.entity_id, new_unique_id=entry2.unique_id) entity_registry.async_update_entity(
entry.entity_id, new_unique_id=entry2.unique_id
)
assert mock_schedule_save.call_count == 0 assert mock_schedule_save.call_count == 0
assert registry.async_get_entity_id("light", "hue", "5678") == entry.entity_id assert (
assert registry.async_get_entity_id("light", "hue", "1234") == entry2.entity_id entity_registry.async_get_entity_id("light", "hue", "5678") == entry.entity_id
)
assert (
entity_registry.async_get_entity_id("light", "hue", "1234") == entry2.entity_id
)
async def test_update_entity_entity_id(registry): async def test_update_entity_entity_id(entity_registry):
"""Test entity's entity_id is updated.""" """Test entity's entity_id is updated."""
entry = registry.async_get_or_create("light", "hue", "5678") entry = entity_registry.async_get_or_create("light", "hue", "5678")
assert registry.async_get_entity_id("light", "hue", "5678") == entry.entity_id assert (
entity_registry.async_get_entity_id("light", "hue", "5678") == entry.entity_id
)
new_entity_id = "light.blah" new_entity_id = "light.blah"
assert new_entity_id != entry.entity_id assert new_entity_id != entry.entity_id
with patch.object(registry, "async_schedule_save") as mock_schedule_save: with patch.object(entity_registry, "async_schedule_save") as mock_schedule_save:
updated_entry = registry.async_update_entity( updated_entry = entity_registry.async_update_entity(
entry.entity_id, new_entity_id=new_entity_id entry.entity_id, new_entity_id=new_entity_id
) )
assert updated_entry != entry assert updated_entry != entry
assert updated_entry.entity_id == new_entity_id assert updated_entry.entity_id == new_entity_id
assert mock_schedule_save.call_count == 1 assert mock_schedule_save.call_count == 1
assert registry.async_get(entry.entity_id) is None assert entity_registry.async_get(entry.entity_id) is None
assert registry.async_get(new_entity_id) is not None assert entity_registry.async_get(new_entity_id) is not None
async def test_update_entity_entity_id_entity_id(hass: HomeAssistant, registry): async def test_update_entity_entity_id_entity_id(hass: HomeAssistant, entity_registry):
"""Test update raises when entity_id already in use.""" """Test update raises when entity_id already in use."""
entry = registry.async_get_or_create("light", "hue", "5678") entry = entity_registry.async_get_or_create("light", "hue", "5678")
entry2 = registry.async_get_or_create("light", "hue", "1234") entry2 = entity_registry.async_get_or_create("light", "hue", "1234")
state_entity_id = "light.blah" state_entity_id = "light.blah"
hass.states.async_set(state_entity_id, "on") hass.states.async_set(state_entity_id, "on")
assert entry.entity_id != state_entity_id assert entry.entity_id != state_entity_id
@ -638,30 +649,40 @@ async def test_update_entity_entity_id_entity_id(hass: HomeAssistant, registry):
# Try updating to a registered entity_id # Try updating to a registered entity_id
with patch.object( with patch.object(
registry, "async_schedule_save" entity_registry, "async_schedule_save"
) as mock_schedule_save, pytest.raises(ValueError): ) as mock_schedule_save, pytest.raises(ValueError):
registry.async_update_entity(entry.entity_id, new_entity_id=entry2.entity_id) entity_registry.async_update_entity(
entry.entity_id, new_entity_id=entry2.entity_id
)
assert mock_schedule_save.call_count == 0 assert mock_schedule_save.call_count == 0
assert registry.async_get_entity_id("light", "hue", "5678") == entry.entity_id assert (
assert registry.async_get(entry.entity_id) is entry entity_registry.async_get_entity_id("light", "hue", "5678") == entry.entity_id
assert registry.async_get_entity_id("light", "hue", "1234") == entry2.entity_id )
assert registry.async_get(entry2.entity_id) is entry2 assert entity_registry.async_get(entry.entity_id) is entry
assert (
entity_registry.async_get_entity_id("light", "hue", "1234") == entry2.entity_id
)
assert entity_registry.async_get(entry2.entity_id) is entry2
# Try updating to an entity_id which is in the state machine # Try updating to an entity_id which is in the state machine
with patch.object( with patch.object(
registry, "async_schedule_save" entity_registry, "async_schedule_save"
) as mock_schedule_save, pytest.raises(ValueError): ) as mock_schedule_save, pytest.raises(ValueError):
registry.async_update_entity(entry.entity_id, new_entity_id=state_entity_id) entity_registry.async_update_entity(
entry.entity_id, new_entity_id=state_entity_id
)
assert mock_schedule_save.call_count == 0 assert mock_schedule_save.call_count == 0
assert registry.async_get_entity_id("light", "hue", "5678") == entry.entity_id assert (
assert registry.async_get(entry.entity_id) is entry entity_registry.async_get_entity_id("light", "hue", "5678") == entry.entity_id
assert registry.async_get(state_entity_id) is None )
assert entity_registry.async_get(entry.entity_id) is entry
assert entity_registry.async_get(state_entity_id) is None
async def test_update_entity(registry): async def test_update_entity(entity_registry):
"""Test updating entity.""" """Test updating entity."""
mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1") mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1")
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "5678", config_entry=mock_config "light", "hue", "5678", config_entry=mock_config
) )
@ -672,73 +693,73 @@ async def test_update_entity(registry):
("name", "new name"), ("name", "new name"),
): ):
changes = {attr_name: new_value} changes = {attr_name: new_value}
updated_entry = registry.async_update_entity(entry.entity_id, **changes) updated_entry = entity_registry.async_update_entity(entry.entity_id, **changes)
assert updated_entry != entry assert updated_entry != entry
assert getattr(updated_entry, attr_name) == new_value assert getattr(updated_entry, attr_name) == new_value
assert getattr(updated_entry, attr_name) != getattr(entry, attr_name) assert getattr(updated_entry, attr_name) != getattr(entry, attr_name)
assert ( assert (
registry.async_get_entity_id("light", "hue", "5678") entity_registry.async_get_entity_id("light", "hue", "5678")
== updated_entry.entity_id == updated_entry.entity_id
) )
entry = updated_entry entry = updated_entry
async def test_update_entity_options(registry): async def test_update_entity_options(entity_registry):
"""Test updating entity.""" """Test updating entity."""
mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1") mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1")
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "5678", config_entry=mock_config "light", "hue", "5678", config_entry=mock_config
) )
registry.async_update_entity_options( entity_registry.async_update_entity_options(
entry.entity_id, "light", {"minimum_brightness": 20} entry.entity_id, "light", {"minimum_brightness": 20}
) )
new_entry_1 = registry.async_get(entry.entity_id) new_entry_1 = entity_registry.async_get(entry.entity_id)
assert entry.options == {} assert entry.options == {}
assert new_entry_1.options == {"light": {"minimum_brightness": 20}} assert new_entry_1.options == {"light": {"minimum_brightness": 20}}
registry.async_update_entity_options( entity_registry.async_update_entity_options(
entry.entity_id, "light", {"minimum_brightness": 30} entry.entity_id, "light", {"minimum_brightness": 30}
) )
new_entry_2 = registry.async_get(entry.entity_id) new_entry_2 = entity_registry.async_get(entry.entity_id)
assert entry.options == {} assert entry.options == {}
assert new_entry_1.options == {"light": {"minimum_brightness": 20}} assert new_entry_1.options == {"light": {"minimum_brightness": 20}}
assert new_entry_2.options == {"light": {"minimum_brightness": 30}} assert new_entry_2.options == {"light": {"minimum_brightness": 30}}
async def test_disabled_by(registry): async def test_disabled_by(entity_registry):
"""Test that we can disable an entry when we create it.""" """Test that we can disable an entry when we create it."""
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "5678", disabled_by=er.RegistryEntryDisabler.HASS "light", "hue", "5678", disabled_by=er.RegistryEntryDisabler.HASS
) )
assert entry.disabled_by is er.RegistryEntryDisabler.HASS assert entry.disabled_by is er.RegistryEntryDisabler.HASS
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "5678", disabled_by=er.RegistryEntryDisabler.INTEGRATION "light", "hue", "5678", disabled_by=er.RegistryEntryDisabler.INTEGRATION
) )
assert entry.disabled_by is er.RegistryEntryDisabler.HASS assert entry.disabled_by is er.RegistryEntryDisabler.HASS
entry2 = registry.async_get_or_create("light", "hue", "1234") entry2 = entity_registry.async_get_or_create("light", "hue", "1234")
assert entry2.disabled_by is None assert entry2.disabled_by is None
async def test_disabled_by_config_entry_pref(registry): async def test_disabled_by_config_entry_pref(entity_registry):
"""Test config entry preference setting disabled_by.""" """Test config entry preference setting disabled_by."""
mock_config = MockConfigEntry( mock_config = MockConfigEntry(
domain="light", domain="light",
entry_id="mock-id-1", entry_id="mock-id-1",
pref_disable_new_entities=True, pref_disable_new_entities=True,
) )
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "hue", "AAAA", config_entry=mock_config "light", "hue", "AAAA", config_entry=mock_config
) )
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
entry2 = registry.async_get_or_create( entry2 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"BBBB", "BBBB",
@ -893,9 +914,8 @@ async def test_async_get_device_class_lookup(hass: HomeAssistant) -> None:
} }
async def test_remove_device_removes_entities(hass, registry): async def test_remove_device_removes_entities(hass, entity_registry, device_registry):
"""Test that we remove entities tied to a device.""" """Test that we remove entities tied to a device."""
device_registry = mock_device_registry(hass)
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
device_entry = device_registry.async_get_or_create( device_entry = device_registry.async_get_or_create(
@ -903,7 +923,7 @@ async def test_remove_device_removes_entities(hass, registry):
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
@ -911,17 +931,18 @@ async def test_remove_device_removes_entities(hass, registry):
device_id=device_entry.id, device_id=device_entry.id,
) )
assert registry.async_is_registered(entry.entity_id) assert entity_registry.async_is_registered(entry.entity_id)
device_registry.async_remove_device(device_entry.id) device_registry.async_remove_device(device_entry.id)
await hass.async_block_till_done() await hass.async_block_till_done()
assert not registry.async_is_registered(entry.entity_id) assert not entity_registry.async_is_registered(entry.entity_id)
async def test_remove_config_entry_from_device_removes_entities(hass, registry): async def test_remove_config_entry_from_device_removes_entities(
hass, device_registry, entity_registry
):
"""Test that we remove entities tied to a device when config entry is removed.""" """Test that we remove entities tied to a device when config entry is removed."""
device_registry = mock_device_registry(hass)
config_entry_1 = MockConfigEntry(domain="hue") config_entry_1 = MockConfigEntry(domain="hue")
config_entry_2 = MockConfigEntry(domain="device_tracker") config_entry_2 = MockConfigEntry(domain="device_tracker")
@ -940,7 +961,7 @@ async def test_remove_config_entry_from_device_removes_entities(hass, registry):
} }
# Create one entity for each config entry # Create one entity for each config entry
entry_1 = registry.async_get_or_create( entry_1 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
@ -948,7 +969,7 @@ async def test_remove_config_entry_from_device_removes_entities(hass, registry):
device_id=device_entry.id, device_id=device_entry.id,
) )
entry_2 = registry.async_get_or_create( entry_2 = entity_registry.async_get_or_create(
"sensor", "sensor",
"device_tracker", "device_tracker",
"6789", "6789",
@ -956,8 +977,8 @@ async def test_remove_config_entry_from_device_removes_entities(hass, registry):
device_id=device_entry.id, device_id=device_entry.id,
) )
assert registry.async_is_registered(entry_1.entity_id) assert entity_registry.async_is_registered(entry_1.entity_id)
assert registry.async_is_registered(entry_2.entity_id) assert entity_registry.async_is_registered(entry_2.entity_id)
# Remove the first config entry from the device, the entity associated with it # Remove the first config entry from the device, the entity associated with it
# should be removed # should be removed
@ -967,8 +988,8 @@ async def test_remove_config_entry_from_device_removes_entities(hass, registry):
await hass.async_block_till_done() await hass.async_block_till_done()
assert device_registry.async_get(device_entry.id) assert device_registry.async_get(device_entry.id)
assert not registry.async_is_registered(entry_1.entity_id) assert not entity_registry.async_is_registered(entry_1.entity_id)
assert registry.async_is_registered(entry_2.entity_id) assert entity_registry.async_is_registered(entry_2.entity_id)
# Remove the second config entry from the device, the entity associated with it # Remove the second config entry from the device, the entity associated with it
# (and the device itself) should be removed # (and the device itself) should be removed
@ -978,13 +999,14 @@ async def test_remove_config_entry_from_device_removes_entities(hass, registry):
await hass.async_block_till_done() await hass.async_block_till_done()
assert not device_registry.async_get(device_entry.id) assert not device_registry.async_get(device_entry.id)
assert not registry.async_is_registered(entry_1.entity_id) assert not entity_registry.async_is_registered(entry_1.entity_id)
assert not registry.async_is_registered(entry_2.entity_id) assert not entity_registry.async_is_registered(entry_2.entity_id)
async def test_remove_config_entry_from_device_removes_entities_2(hass, registry): async def test_remove_config_entry_from_device_removes_entities_2(
hass, device_registry, entity_registry
):
"""Test that we don't remove entities with no config entry when device is modified.""" """Test that we don't remove entities with no config entry when device is modified."""
device_registry = mock_device_registry(hass)
config_entry_1 = MockConfigEntry(domain="hue") config_entry_1 = MockConfigEntry(domain="hue")
config_entry_2 = MockConfigEntry(domain="device_tracker") config_entry_2 = MockConfigEntry(domain="device_tracker")
@ -1003,14 +1025,14 @@ async def test_remove_config_entry_from_device_removes_entities_2(hass, registry
} }
# Create one entity for each config entry # Create one entity for each config entry
entry_1 = registry.async_get_or_create( entry_1 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
device_id=device_entry.id, device_id=device_entry.id,
) )
assert registry.async_is_registered(entry_1.entity_id) assert entity_registry.async_is_registered(entry_1.entity_id)
# Remove the first config entry from the device # Remove the first config entry from the device
device_registry.async_update_device( device_registry.async_update_device(
@ -1019,12 +1041,11 @@ async def test_remove_config_entry_from_device_removes_entities_2(hass, registry
await hass.async_block_till_done() await hass.async_block_till_done()
assert device_registry.async_get(device_entry.id) assert device_registry.async_get(device_entry.id)
assert registry.async_is_registered(entry_1.entity_id) assert entity_registry.async_is_registered(entry_1.entity_id)
async def test_update_device_race(hass, registry): async def test_update_device_race(hass, device_registry, entity_registry):
"""Test race when a device is created, updated and removed.""" """Test race when a device is created, updated and removed."""
device_registry = mock_device_registry(hass)
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
# Create device # Create device
@ -1039,7 +1060,7 @@ async def test_update_device_race(hass, registry):
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
# Add entity to the device # Add entity to the device
entry = registry.async_get_or_create( entry = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
@ -1047,17 +1068,16 @@ async def test_update_device_race(hass, registry):
device_id=device_entry.id, device_id=device_entry.id,
) )
assert registry.async_is_registered(entry.entity_id) assert entity_registry.async_is_registered(entry.entity_id)
device_registry.async_remove_device(device_entry.id) device_registry.async_remove_device(device_entry.id)
await hass.async_block_till_done() await hass.async_block_till_done()
assert not registry.async_is_registered(entry.entity_id) assert not entity_registry.async_is_registered(entry.entity_id)
async def test_disable_device_disables_entities(hass, registry): async def test_disable_device_disables_entities(hass, device_registry, entity_registry):
"""Test that we disable entities tied to a device.""" """Test that we disable entities tied to a device."""
device_registry = mock_device_registry(hass)
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -1066,14 +1086,14 @@ async def test_disable_device_disables_entities(hass, registry):
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
entry1 = registry.async_get_or_create( entry1 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
config_entry=config_entry, config_entry=config_entry,
device_id=device_entry.id, device_id=device_entry.id,
) )
entry2 = registry.async_get_or_create( entry2 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"ABCD", "ABCD",
@ -1081,7 +1101,7 @@ async def test_disable_device_disables_entities(hass, registry):
device_id=device_entry.id, device_id=device_entry.id,
disabled_by=er.RegistryEntryDisabler.USER, disabled_by=er.RegistryEntryDisabler.USER,
) )
entry3 = registry.async_get_or_create( entry3 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"EFGH", "EFGH",
@ -1099,32 +1119,33 @@ async def test_disable_device_disables_entities(hass, registry):
) )
await hass.async_block_till_done() await hass.async_block_till_done()
entry1 = registry.async_get(entry1.entity_id) entry1 = entity_registry.async_get(entry1.entity_id)
assert entry1.disabled assert entry1.disabled
assert entry1.disabled_by is er.RegistryEntryDisabler.DEVICE assert entry1.disabled_by is er.RegistryEntryDisabler.DEVICE
entry2 = registry.async_get(entry2.entity_id) entry2 = entity_registry.async_get(entry2.entity_id)
assert entry2.disabled assert entry2.disabled
assert entry2.disabled_by is er.RegistryEntryDisabler.USER assert entry2.disabled_by is er.RegistryEntryDisabler.USER
entry3 = registry.async_get(entry3.entity_id) entry3 = entity_registry.async_get(entry3.entity_id)
assert entry3.disabled assert entry3.disabled
assert entry3.disabled_by is er.RegistryEntryDisabler.CONFIG_ENTRY assert entry3.disabled_by is er.RegistryEntryDisabler.CONFIG_ENTRY
device_registry.async_update_device(device_entry.id, disabled_by=None) device_registry.async_update_device(device_entry.id, disabled_by=None)
await hass.async_block_till_done() await hass.async_block_till_done()
entry1 = registry.async_get(entry1.entity_id) entry1 = entity_registry.async_get(entry1.entity_id)
assert not entry1.disabled assert not entry1.disabled
entry2 = registry.async_get(entry2.entity_id) entry2 = entity_registry.async_get(entry2.entity_id)
assert entry2.disabled assert entry2.disabled
assert entry2.disabled_by is er.RegistryEntryDisabler.USER assert entry2.disabled_by is er.RegistryEntryDisabler.USER
entry3 = registry.async_get(entry3.entity_id) entry3 = entity_registry.async_get(entry3.entity_id)
assert entry3.disabled assert entry3.disabled
assert entry3.disabled_by is er.RegistryEntryDisabler.CONFIG_ENTRY assert entry3.disabled_by is er.RegistryEntryDisabler.CONFIG_ENTRY
async def test_disable_config_entry_disables_entities(hass, registry): async def test_disable_config_entry_disables_entities(
hass, device_registry, entity_registry
):
"""Test that we disable entities tied to a config entry.""" """Test that we disable entities tied to a config entry."""
device_registry = mock_device_registry(hass)
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -1133,14 +1154,14 @@ async def test_disable_config_entry_disables_entities(hass, registry):
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
entry1 = registry.async_get_or_create( entry1 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
config_entry=config_entry, config_entry=config_entry,
device_id=device_entry.id, device_id=device_entry.id,
) )
entry2 = registry.async_get_or_create( entry2 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"ABCD", "ABCD",
@ -1148,7 +1169,7 @@ async def test_disable_config_entry_disables_entities(hass, registry):
device_id=device_entry.id, device_id=device_entry.id,
disabled_by=er.RegistryEntryDisabler.USER, disabled_by=er.RegistryEntryDisabler.USER,
) )
entry3 = registry.async_get_or_create( entry3 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"EFGH", "EFGH",
@ -1166,32 +1187,33 @@ async def test_disable_config_entry_disables_entities(hass, registry):
) )
await hass.async_block_till_done() await hass.async_block_till_done()
entry1 = registry.async_get(entry1.entity_id) entry1 = entity_registry.async_get(entry1.entity_id)
assert entry1.disabled assert entry1.disabled
assert entry1.disabled_by is er.RegistryEntryDisabler.CONFIG_ENTRY assert entry1.disabled_by is er.RegistryEntryDisabler.CONFIG_ENTRY
entry2 = registry.async_get(entry2.entity_id) entry2 = entity_registry.async_get(entry2.entity_id)
assert entry2.disabled assert entry2.disabled
assert entry2.disabled_by is er.RegistryEntryDisabler.USER assert entry2.disabled_by is er.RegistryEntryDisabler.USER
entry3 = registry.async_get(entry3.entity_id) entry3 = entity_registry.async_get(entry3.entity_id)
assert entry3.disabled assert entry3.disabled
assert entry3.disabled_by is er.RegistryEntryDisabler.DEVICE assert entry3.disabled_by is er.RegistryEntryDisabler.DEVICE
await hass.config_entries.async_set_disabled_by(config_entry.entry_id, None) await hass.config_entries.async_set_disabled_by(config_entry.entry_id, None)
await hass.async_block_till_done() await hass.async_block_till_done()
entry1 = registry.async_get(entry1.entity_id) entry1 = entity_registry.async_get(entry1.entity_id)
assert not entry1.disabled assert not entry1.disabled
entry2 = registry.async_get(entry2.entity_id) entry2 = entity_registry.async_get(entry2.entity_id)
assert entry2.disabled assert entry2.disabled
assert entry2.disabled_by is er.RegistryEntryDisabler.USER assert entry2.disabled_by is er.RegistryEntryDisabler.USER
# The device was re-enabled, so entity disabled by the device will be re-enabled too # The device was re-enabled, so entity disabled by the device will be re-enabled too
entry3 = registry.async_get(entry3.entity_id) entry3 = entity_registry.async_get(entry3.entity_id)
assert not entry3.disabled_by assert not entry3.disabled_by
async def test_disabled_entities_excluded_from_entity_list(hass, registry): async def test_disabled_entities_excluded_from_entity_list(
hass, device_registry, entity_registry
):
"""Test that disabled entities are excluded from async_entries_for_device.""" """Test that disabled entities are excluded from async_entries_for_device."""
device_registry = mock_device_registry(hass)
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
device_entry = device_registry.async_get_or_create( device_entry = device_registry.async_get_or_create(
@ -1199,7 +1221,7 @@ async def test_disabled_entities_excluded_from_entity_list(hass, registry):
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
entry1 = registry.async_get_or_create( entry1 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"5678", "5678",
@ -1207,7 +1229,7 @@ async def test_disabled_entities_excluded_from_entity_list(hass, registry):
device_id=device_entry.id, device_id=device_entry.id,
) )
entry2 = registry.async_get_or_create( entry2 = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
"ABCD", "ABCD",
@ -1216,16 +1238,16 @@ async def test_disabled_entities_excluded_from_entity_list(hass, registry):
disabled_by=er.RegistryEntryDisabler.USER, disabled_by=er.RegistryEntryDisabler.USER,
) )
entries = er.async_entries_for_device(registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
assert entries == [entry1] assert entries == [entry1]
entries = er.async_entries_for_device( entries = er.async_entries_for_device(
registry, device_entry.id, include_disabled_entities=True entity_registry, device_entry.id, include_disabled_entities=True
) )
assert entries == [entry1, entry2] assert entries == [entry1, entry2]
async def test_entity_max_length_exceeded(hass, registry): async def test_entity_max_length_exceeded(entity_registry):
"""Test that an exception is raised when the max character length is exceeded.""" """Test that an exception is raised when the max character length is exceeded."""
long_domain_name = ( long_domain_name = (
@ -1236,7 +1258,7 @@ async def test_entity_max_length_exceeded(hass, registry):
) )
with pytest.raises(MaxLengthExceeded) as exc_info: with pytest.raises(MaxLengthExceeded) as exc_info:
registry.async_generate_entity_id(long_domain_name, "sensor") entity_registry.async_generate_entity_id(long_domain_name, "sensor")
assert exc_info.value.property_name == "domain" assert exc_info.value.property_name == "domain"
assert exc_info.value.max_length == 64 assert exc_info.value.max_length == 64
@ -1251,43 +1273,55 @@ async def test_entity_max_length_exceeded(hass, registry):
) )
known = [] known = []
new_id = registry.async_generate_entity_id("sensor", long_entity_id_name, known) new_id = entity_registry.async_generate_entity_id(
"sensor", long_entity_id_name, known
)
assert new_id == "sensor." + long_entity_id_name[: 255 - 7] assert new_id == "sensor." + long_entity_id_name[: 255 - 7]
known.append(new_id) known.append(new_id)
new_id = registry.async_generate_entity_id("sensor", long_entity_id_name, known) new_id = entity_registry.async_generate_entity_id(
"sensor", long_entity_id_name, known
)
assert new_id == "sensor." + long_entity_id_name[: 255 - 7 - 2] + "_2" assert new_id == "sensor." + long_entity_id_name[: 255 - 7 - 2] + "_2"
known.append(new_id) known.append(new_id)
new_id = registry.async_generate_entity_id("sensor", long_entity_id_name, known) new_id = entity_registry.async_generate_entity_id(
"sensor", long_entity_id_name, known
)
assert new_id == "sensor." + long_entity_id_name[: 255 - 7 - 2] + "_3" assert new_id == "sensor." + long_entity_id_name[: 255 - 7 - 2] + "_3"
async def test_resolve_entity_ids(hass, registry): async def test_resolve_entity_ids(entity_registry):
"""Test resolving entity IDs.""" """Test resolving entity IDs."""
entry1 = registry.async_get_or_create( entry1 = entity_registry.async_get_or_create(
"light", "hue", "1234", suggested_object_id="beer" "light", "hue", "1234", suggested_object_id="beer"
) )
assert entry1.entity_id == "light.beer" assert entry1.entity_id == "light.beer"
entry2 = registry.async_get_or_create( entry2 = entity_registry.async_get_or_create(
"light", "hue", "2345", suggested_object_id="milk" "light", "hue", "2345", suggested_object_id="milk"
) )
assert entry2.entity_id == "light.milk" assert entry2.entity_id == "light.milk"
expected = ["light.beer", "light.milk"] expected = ["light.beer", "light.milk"]
assert er.async_validate_entity_ids(registry, [entry1.id, entry2.id]) == expected assert (
er.async_validate_entity_ids(entity_registry, [entry1.id, entry2.id])
== expected
)
expected = ["light.beer", "light.milk"] expected = ["light.beer", "light.milk"]
assert er.async_validate_entity_ids(registry, ["light.beer", entry2.id]) == expected assert (
er.async_validate_entity_ids(entity_registry, ["light.beer", entry2.id])
== expected
)
with pytest.raises(vol.Invalid): with pytest.raises(vol.Invalid):
er.async_validate_entity_ids(registry, ["light.beer", "bad_uuid"]) er.async_validate_entity_ids(entity_registry, ["light.beer", "bad_uuid"])
expected = ["light.unknown"] expected = ["light.unknown"]
assert er.async_validate_entity_ids(registry, ["light.unknown"]) == expected assert er.async_validate_entity_ids(entity_registry, ["light.unknown"]) == expected
with pytest.raises(vol.Invalid): with pytest.raises(vol.Invalid):
er.async_validate_entity_ids(registry, ["unknown_uuid"]) er.async_validate_entity_ids(entity_registry, ["unknown_uuid"])
def test_entity_registry_items() -> None: def test_entity_registry_items() -> None:
@ -1364,12 +1398,12 @@ async def test_hidden_by_str_not_allowed(hass: HomeAssistant) -> None:
reg.async_update_entity(entity_id, hidden_by=er.RegistryEntryHider.USER.value) reg.async_update_entity(entity_id, hidden_by=er.RegistryEntryHider.USER.value)
def test_migrate_entity_to_new_platform(hass, registry): def test_migrate_entity_to_new_platform(hass, entity_registry):
"""Test migrate_entity_to_new_platform.""" """Test migrate_entity_to_new_platform."""
orig_config_entry = MockConfigEntry(domain="light") orig_config_entry = MockConfigEntry(domain="light")
orig_unique_id = "5678" orig_unique_id = "5678"
orig_entry = registry.async_get_or_create( orig_entry = entity_registry.async_get_or_create(
"light", "light",
"hue", "hue",
orig_unique_id, orig_unique_id,
@ -1381,8 +1415,8 @@ def test_migrate_entity_to_new_platform(hass, registry):
original_icon="initial-original_icon", original_icon="initial-original_icon",
original_name="initial-original_name", original_name="initial-original_name",
) )
assert registry.async_get("light.light") is orig_entry assert entity_registry.async_get("light.light") is orig_entry
registry.async_update_entity( entity_registry.async_update_entity(
"light.light", "light.light",
name="new_name", name="new_name",
icon="new_icon", icon="new_icon",
@ -1391,16 +1425,16 @@ def test_migrate_entity_to_new_platform(hass, registry):
new_config_entry = MockConfigEntry(domain="light") new_config_entry = MockConfigEntry(domain="light")
new_unique_id = "1234" new_unique_id = "1234"
assert registry.async_update_entity_platform( assert entity_registry.async_update_entity_platform(
"light.light", "light.light",
"hue2", "hue2",
new_unique_id=new_unique_id, new_unique_id=new_unique_id,
new_config_entry_id=new_config_entry.entry_id, new_config_entry_id=new_config_entry.entry_id,
) )
assert not registry.async_get_entity_id("light", "hue", orig_unique_id) assert not entity_registry.async_get_entity_id("light", "hue", orig_unique_id)
assert (new_entry := registry.async_get("light.light")) is not orig_entry assert (new_entry := entity_registry.async_get("light.light")) is not orig_entry
assert new_entry.config_entry_id == new_config_entry.entry_id assert new_entry.config_entry_id == new_config_entry.entry_id
assert new_entry.unique_id == new_unique_id assert new_entry.unique_id == new_unique_id
@ -1410,7 +1444,7 @@ def test_migrate_entity_to_new_platform(hass, registry):
# Test nonexisting entity # Test nonexisting entity
with pytest.raises(KeyError): with pytest.raises(KeyError):
registry.async_update_entity_platform( entity_registry.async_update_entity_platform(
"light.not_a_real_light", "light.not_a_real_light",
"hue2", "hue2",
new_unique_id=new_unique_id, new_unique_id=new_unique_id,
@ -1419,7 +1453,7 @@ def test_migrate_entity_to_new_platform(hass, registry):
# Test migrate entity without new config entry ID # Test migrate entity without new config entry ID
with pytest.raises(ValueError): with pytest.raises(ValueError):
registry.async_update_entity_platform( entity_registry.async_update_entity_platform(
"light.light", "light.light",
"hue3", "hue3",
) )
@ -1427,7 +1461,7 @@ def test_migrate_entity_to_new_platform(hass, registry):
# Test entity with a state # Test entity with a state
hass.states.async_set("light.light", "on") hass.states.async_set("light.light", "on")
with pytest.raises(ValueError): with pytest.raises(ValueError):
registry.async_update_entity_platform( entity_registry.async_update_entity_platform(
"light.light", "light.light",
"hue2", "hue2",
new_unique_id=new_unique_id, new_unique_id=new_unique_id,

View File

@ -28,7 +28,13 @@ from homeassistant.const import (
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import TemplateError from homeassistant.exceptions import TemplateError
from homeassistant.helpers import device_registry as dr, entity, template from homeassistant.helpers import (
area_registry as ar,
device_registry as dr,
entity,
entity_registry as er,
template,
)
from homeassistant.helpers.entity_platform import EntityPlatform from homeassistant.helpers.entity_platform import EntityPlatform
from homeassistant.helpers.json import json_dumps from homeassistant.helpers.json import json_dumps
from homeassistant.helpers.typing import TemplateVarsType from homeassistant.helpers.typing import TemplateVarsType
@ -36,12 +42,7 @@ from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
from homeassistant.util.unit_system import UnitSystem from homeassistant.util.unit_system import UnitSystem
from tests.common import ( from tests.common import MockConfigEntry
MockConfigEntry,
mock_area_registry,
mock_device_registry,
mock_registry,
)
def _set_up_units(hass: HomeAssistant) -> None: def _set_up_units(hass: HomeAssistant) -> None:
@ -2509,11 +2510,13 @@ async def test_expand(hass: HomeAssistant) -> None:
) )
async def test_device_entities(hass: HomeAssistant) -> None: async def test_device_entities(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test device_entities function.""" """Test device_entities function."""
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
# Test non existing device ids # Test non existing device ids
info = render_to_info(hass, "{{ device_entities('abc123') }}") info = render_to_info(hass, "{{ device_entities('abc123') }}")
@ -2591,10 +2594,10 @@ async def test_device_entities(hass: HomeAssistant) -> None:
assert info.rate_limit is None assert info.rate_limit is None
async def test_integration_entities(hass: HomeAssistant) -> None: async def test_integration_entities(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test integration_entities function.""" """Test integration_entities function."""
entity_registry = mock_registry(hass)
# test entities for given config entry title # test entities for given config entry title
config_entry = MockConfigEntry(domain="mock", title="Mock bridge 2") config_entry = MockConfigEntry(domain="mock", title="Mock bridge 2")
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -2629,11 +2632,12 @@ async def test_integration_entities(hass: HomeAssistant) -> None:
assert info.rate_limit is None assert info.rate_limit is None
async def test_config_entry_id(hass: HomeAssistant) -> None: async def test_config_entry_id(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test config_entry_id function.""" """Test config_entry_id function."""
config_entry = MockConfigEntry(domain="light", title="Some integration") config_entry = MockConfigEntry(domain="light", title="Some integration")
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
entity_registry = mock_registry(hass)
entity_entry = entity_registry.async_get_or_create( entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "test", suggested_object_id="test", config_entry=config_entry "sensor", "test", "test", suggested_object_id="test", config_entry=config_entry
) )
@ -2655,11 +2659,13 @@ async def test_config_entry_id(hass: HomeAssistant) -> None:
assert info.rate_limit is None assert info.rate_limit is None
async def test_device_id(hass: HomeAssistant) -> None: async def test_device_id(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test device_id function.""" """Test device_id function."""
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
device_entry = device_registry.async_get_or_create( device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
@ -2698,11 +2704,13 @@ async def test_device_id(hass: HomeAssistant) -> None:
assert info.rate_limit is None assert info.rate_limit is None
async def test_device_attr(hass: HomeAssistant) -> None: async def test_device_attr(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test device_attr and is_device_attr functions.""" """Test device_attr and is_device_attr functions."""
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
# Test non existing device ids (device_attr) # Test non existing device ids (device_attr)
info = render_to_info(hass, "{{ device_attr('abc123', 'id') }}") info = render_to_info(hass, "{{ device_attr('abc123', 'id') }}")
@ -2821,12 +2829,14 @@ async def test_device_attr(hass: HomeAssistant) -> None:
assert info.rate_limit is None assert info.rate_limit is None
async def test_area_id(hass: HomeAssistant) -> None: async def test_area_id(
hass: HomeAssistant,
area_registry: ar.AreaRegistry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test area_id function.""" """Test area_id function."""
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
area_registry = mock_area_registry(hass)
# Test non existing entity id # Test non existing entity id
info = render_to_info(hass, "{{ area_id('sensor.fake') }}") info = render_to_info(hass, "{{ area_id('sensor.fake') }}")
@ -2925,12 +2935,14 @@ async def test_area_id(hass: HomeAssistant) -> None:
assert info.rate_limit is None assert info.rate_limit is None
async def test_area_name(hass: HomeAssistant) -> None: async def test_area_name(
hass: HomeAssistant,
area_registry: ar.AreaRegistry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test area_name function.""" """Test area_name function."""
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
area_registry = mock_area_registry(hass)
# Test non existing entity id # Test non existing entity id
info = render_to_info(hass, "{{ area_name('sensor.fake') }}") info = render_to_info(hass, "{{ area_name('sensor.fake') }}")
@ -3004,12 +3016,14 @@ async def test_area_name(hass: HomeAssistant) -> None:
assert info.rate_limit is None assert info.rate_limit is None
async def test_area_entities(hass: HomeAssistant) -> None: async def test_area_entities(
hass: HomeAssistant,
area_registry: ar.AreaRegistry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test area_entities function.""" """Test area_entities function."""
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
area_registry = mock_area_registry(hass)
# Test non existing device id # Test non existing device id
info = render_to_info(hass, "{{ area_entities('deadbeef') }}") info = render_to_info(hass, "{{ area_entities('deadbeef') }}")
@ -3057,11 +3071,13 @@ async def test_area_entities(hass: HomeAssistant) -> None:
assert info.rate_limit is None assert info.rate_limit is None
async def test_area_devices(hass: HomeAssistant) -> None: async def test_area_devices(
hass: HomeAssistant,
area_registry: ar.AreaRegistry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test area_devices function.""" """Test area_devices function."""
config_entry = MockConfigEntry(domain="light") config_entry = MockConfigEntry(domain="light")
device_registry = mock_device_registry(hass)
area_registry = mock_area_registry(hass)
# Test non existing device id # Test non existing device id
info = render_to_info(hass, "{{ area_devices('deadbeef') }}") info = render_to_info(hass, "{{ area_devices('deadbeef') }}")

View File

@ -38,7 +38,6 @@ from .common import (
mock_coro, mock_coro,
mock_entity_platform, mock_entity_platform,
mock_integration, mock_integration,
mock_registry,
) )
@ -1443,15 +1442,14 @@ async def test_support_entry_unload(hass: HomeAssistant) -> None:
async def test_reload_entry_entity_registry_ignores_no_entry( async def test_reload_entry_entity_registry_ignores_no_entry(
hass: HomeAssistant, hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None: ) -> None:
"""Test reloading entry in entity registry skips if no config entry linked.""" """Test reloading entry in entity registry skips if no config entry linked."""
handler = config_entries.EntityRegistryDisabledHandler(hass) handler = config_entries.EntityRegistryDisabledHandler(hass)
registry = mock_registry(hass)
# Test we ignore entities without config entry # Test we ignore entities without config entry
entry = registry.async_get_or_create("light", "hue", "123") entry = entity_registry.async_get_or_create("light", "hue", "123")
registry.async_update_entity( entity_registry.async_update_entity(
entry.entity_id, disabled_by=er.RegistryEntryDisabler.USER entry.entity_id, disabled_by=er.RegistryEntryDisabler.USER
) )
await hass.async_block_till_done() await hass.async_block_till_done()
@ -1459,11 +1457,12 @@ async def test_reload_entry_entity_registry_ignores_no_entry(
assert handler._remove_call_later is None assert handler._remove_call_later is None
async def test_reload_entry_entity_registry_works(hass: HomeAssistant) -> None: async def test_reload_entry_entity_registry_works(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test we schedule an entry to be reloaded if disabled_by is updated.""" """Test we schedule an entry to be reloaded if disabled_by is updated."""
handler = config_entries.EntityRegistryDisabledHandler(hass) handler = config_entries.EntityRegistryDisabledHandler(hass)
handler.async_setup() handler.async_setup()
registry = mock_registry(hass)
config_entry = MockConfigEntry( config_entry = MockConfigEntry(
domain="comp", state=config_entries.ConfigEntryState.LOADED domain="comp", state=config_entries.ConfigEntryState.LOADED
@ -1483,16 +1482,16 @@ async def test_reload_entry_entity_registry_works(hass: HomeAssistant) -> None:
mock_entity_platform(hass, "config_flow.comp", None) mock_entity_platform(hass, "config_flow.comp", None)
# Only changing disabled_by should update trigger # Only changing disabled_by should update trigger
entity_entry = registry.async_get_or_create( entity_entry = entity_registry.async_get_or_create(
"light", "hue", "123", config_entry=config_entry "light", "hue", "123", config_entry=config_entry
) )
registry.async_update_entity(entity_entry.entity_id, name="yo") entity_registry.async_update_entity(entity_entry.entity_id, name="yo")
await hass.async_block_till_done() await hass.async_block_till_done()
assert not handler.changed assert not handler.changed
assert handler._remove_call_later is None assert handler._remove_call_later is None
# Disable entity, we should not do anything, only act when enabled. # Disable entity, we should not do anything, only act when enabled.
registry.async_update_entity( entity_registry.async_update_entity(
entity_entry.entity_id, disabled_by=er.RegistryEntryDisabler.USER entity_entry.entity_id, disabled_by=er.RegistryEntryDisabler.USER
) )
await hass.async_block_till_done() await hass.async_block_till_done()
@ -1500,7 +1499,7 @@ async def test_reload_entry_entity_registry_works(hass: HomeAssistant) -> None:
assert handler._remove_call_later is None assert handler._remove_call_later is None
# Enable entity, check we are reloading config entry. # Enable entity, check we are reloading config entry.
registry.async_update_entity(entity_entry.entity_id, disabled_by=None) entity_registry.async_update_entity(entity_entry.entity_id, disabled_by=None)
await hass.async_block_till_done() await hass.async_block_till_done()
assert handler.changed == {config_entry.entry_id} assert handler.changed == {config_entry.entry_id}
assert handler._remove_call_later is not None assert handler._remove_call_later is not None