From 4a5a09a0e928a4ce9780940c71e3aae5abd1f674 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 21 Jul 2020 14:29:57 -1000 Subject: [PATCH] Speed up group setup (#38048) --- homeassistant/components/group/__init__.py | 10 +++++++++- tests/components/group/test_init.py | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/group/__init__.py b/homeassistant/components/group/__init__.py index 5a2c11dc481..11c78a9b271 100644 --- a/homeassistant/components/group/__init__.py +++ b/homeassistant/components/group/__init__.py @@ -39,6 +39,7 @@ from homeassistant.loader import bind_hass # mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs DOMAIN = "group" +GROUP_ORDER = "group_order" ENTITY_ID_FORMAT = DOMAIN + ".{}" @@ -407,16 +408,23 @@ class Group(Entity): This method must be run in the event loop. """ + hass.data.setdefault(GROUP_ORDER, 0) + group = Group( hass, name, - order=len(hass.states.async_entity_ids(DOMAIN)), + order=hass.data[GROUP_ORDER], icon=icon, user_defined=user_defined, entity_ids=entity_ids, mode=mode, ) + # Keep track of the group order without iterating + # every state in the state machine every time + # we setup a new group + hass.data[GROUP_ORDER] += 1 + group.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, object_id or name, hass=hass ) diff --git a/tests/components/group/test_init.py b/tests/components/group/test_init.py index 921b810fe39..3709c4856a2 100644 --- a/tests/components/group/test_init.py +++ b/tests/components/group/test_init.py @@ -490,3 +490,25 @@ async def test_service_group_set_group_remove_group(hass): group_state = hass.states.get("group.user_test_group") assert group_state is None + + +async def test_group_order(hass): + """Test that order gets incremented when creating a new group.""" + hass.states.async_set("light.bowl", STATE_ON) + + assert await async_setup_component( + hass, + "group", + { + "group": { + "group_zero": {"entities": "light.Bowl", "icon": "mdi:work"}, + "group_one": {"entities": "light.Bowl", "icon": "mdi:work"}, + "group_two": {"entities": "light.Bowl", "icon": "mdi:work"}, + } + }, + ) + await hass.async_block_till_done() + + assert hass.states.get("group.group_zero").attributes["order"] == 0 + assert hass.states.get("group.group_one").attributes["order"] == 1 + assert hass.states.get("group.group_two").attributes["order"] == 2