init home-assistant

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

View File

@@ -0,0 +1 @@
"""Tests for the group component."""

View File

@@ -0,0 +1,85 @@
"""Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.group import (
ATTR_ADD_ENTITIES,
ATTR_ENTITIES,
ATTR_OBJECT_ID,
DOMAIN,
SERVICE_REMOVE,
SERVICE_SET,
)
from homeassistant.const import ATTR_ICON, ATTR_NAME, SERVICE_RELOAD
from homeassistant.core import HomeAssistant, callback
from homeassistant.loader import bind_hass
@bind_hass
def reload(hass: HomeAssistant) -> None:
"""Reload the automation from config."""
hass.add_job(async_reload, hass)
@callback
@bind_hass
def async_reload(hass: HomeAssistant) -> None:
"""Reload the automation from config."""
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_RELOAD))
@bind_hass
def set_group(
hass: HomeAssistant,
object_id: str,
name: str | None = None,
entity_ids: list[str] | None = None,
icon: str | None = None,
add: list[str] | None = None,
) -> None:
"""Create/Update a group."""
hass.add_job(
async_set_group,
hass,
object_id,
name,
entity_ids,
icon,
add,
)
@callback
@bind_hass
def async_set_group(
hass: HomeAssistant,
object_id: str,
name: str | None = None,
entity_ids: list[str] | None = None,
icon: str | None = None,
add: list[str] | None = None,
) -> None:
"""Create/Update a group."""
data = {
key: value
for key, value in (
(ATTR_OBJECT_ID, object_id),
(ATTR_NAME, name),
(ATTR_ENTITIES, entity_ids),
(ATTR_ICON, icon),
(ATTR_ADD_ENTITIES, add),
)
if value is not None
}
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_SET, data))
@callback
@bind_hass
def async_remove(hass: HomeAssistant, object_id: str) -> None:
"""Remove a user group."""
data = {ATTR_OBJECT_ID: object_id}
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_REMOVE, data))

View File

@@ -0,0 +1,14 @@
"""group conftest."""
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.components.light.conftest import mock_light_profiles # noqa: F401
@pytest.fixture(autouse=True)
async def setup_homeassistant(hass: HomeAssistant):
"""Set up the homeassistant integration."""
await async_setup_component(hass, "homeassistant", {})

View File

@@ -0,0 +1,42 @@
light:
- platform: group
name: Master Hall Lights G
entities:
- light.master_hall_lights
- light.master_hall_lights_2
- platform: group
name: Outside Patio Lights G
entities:
- light.outside_patio_lights
- light.outside_patio_lights_2
lock:
- platform: group
name: Inside Locks G
entities:
- lock.front_lock
- lock.back_lock
- platform: group
name: Outside Locks G
entities:
- lock.outside_lock
- lock.outside_lock_2
switch:
- platform: group
name: Master Switches G
entities:
- switch.master_switch
- switch.master_switch_2
- platform: group
name: Outside Switches G
entities:
- switch.outside_switch
- switch.outside_switch_2
notify:
- platform: group
name: new_group_notify
services:
- service: demo1
- service: demo2

View File

@@ -0,0 +1,13 @@
fan:
- platform: group
name: Upstairs Fans
entities:
- fan.living_room_fan
- fan.percentage_full_fan
notify:
- platform: group
name: new_group_notify
services:
- service: demo1
- service: demo2

View File

@@ -0,0 +1,7 @@
sensor:
- platform: group
entities:
- sensor.test_1
- sensor.test_2
name: second_test
type: mean

View File

@@ -0,0 +1,250 @@
"""The tests for the Group Binary Sensor platform."""
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
from homeassistant.components.group import DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
async def test_default_state(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test binary_sensor group default state."""
hass.states.async_set("binary_sensor.kitchen", "on")
hass.states.async_set("binary_sensor.bedroom", "on")
await async_setup_component(
hass,
BINARY_SENSOR_DOMAIN,
{
BINARY_SENSOR_DOMAIN: {
"platform": DOMAIN,
"entities": ["binary_sensor.kitchen", "binary_sensor.bedroom"],
"name": "Bedroom Group",
"unique_id": "unique_identifier",
"device_class": "presence",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.bedroom_group")
assert state is not None
assert state.state == STATE_ON
assert state.attributes.get(ATTR_ENTITY_ID) == [
"binary_sensor.kitchen",
"binary_sensor.bedroom",
]
entry = entity_registry.async_get("binary_sensor.bedroom_group")
assert entry
assert entry.unique_id == "unique_identifier"
assert entry.original_name == "Bedroom Group"
assert entry.original_device_class == "presence"
async def test_state_reporting_all(hass: HomeAssistant) -> None:
"""Test the state reporting in 'all' mode.
The group state is unavailable if all group members are unavailable.
Otherwise, the group state is unknown if at least one group member is unknown or unavailable.
Otherwise, the group state is off if at least one group member is off.
Otherwise, the group state is on.
"""
await async_setup_component(
hass,
BINARY_SENSOR_DOMAIN,
{
BINARY_SENSOR_DOMAIN: {
"platform": DOMAIN,
"entities": ["binary_sensor.test1", "binary_sensor.test2"],
"name": "Binary Sensor Group",
"device_class": "presence",
"all": "true",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
# Initial state with no group member in the state machine -> unavailable
assert (
hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNAVAILABLE
)
# All group members unavailable -> unavailable
hass.states.async_set("binary_sensor.test1", STATE_UNAVAILABLE)
hass.states.async_set("binary_sensor.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert (
hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNAVAILABLE
)
# At least one member unknown or unavailable -> group unknown
hass.states.async_set("binary_sensor.test1", STATE_ON)
hass.states.async_set("binary_sensor.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNKNOWN
hass.states.async_set("binary_sensor.test1", STATE_ON)
hass.states.async_set("binary_sensor.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNKNOWN
hass.states.async_set("binary_sensor.test1", STATE_UNKNOWN)
hass.states.async_set("binary_sensor.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNKNOWN
hass.states.async_set("binary_sensor.test1", STATE_OFF)
hass.states.async_set("binary_sensor.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNKNOWN
hass.states.async_set("binary_sensor.test1", STATE_OFF)
hass.states.async_set("binary_sensor.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNKNOWN
hass.states.async_set("binary_sensor.test1", STATE_UNKNOWN)
hass.states.async_set("binary_sensor.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNKNOWN
# At least one member off -> group off
hass.states.async_set("binary_sensor.test1", STATE_ON)
hass.states.async_set("binary_sensor.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_OFF
hass.states.async_set("binary_sensor.test1", STATE_OFF)
hass.states.async_set("binary_sensor.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_OFF
# Otherwise -> on
hass.states.async_set("binary_sensor.test1", STATE_ON)
hass.states.async_set("binary_sensor.test2", STATE_ON)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_ON
# All group members removed from the state machine -> unavailable
hass.states.async_remove("binary_sensor.test1")
hass.states.async_remove("binary_sensor.test2")
await hass.async_block_till_done()
assert (
hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNAVAILABLE
)
async def test_state_reporting_any(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test the state reporting in 'any' mode.
The group state is unavailable if all group members are unavailable.
Otherwise, the group state is unknown if all group members are unknown.
Otherwise, the group state is on if at least one group member is on.
Otherwise, the group state is off.
"""
await async_setup_component(
hass,
BINARY_SENSOR_DOMAIN,
{
BINARY_SENSOR_DOMAIN: {
"platform": DOMAIN,
"entities": ["binary_sensor.test1", "binary_sensor.test2"],
"name": "Binary Sensor Group",
"device_class": "presence",
"all": "false",
"unique_id": "unique_identifier",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
entry = entity_registry.async_get("binary_sensor.binary_sensor_group")
assert entry
assert entry.unique_id == "unique_identifier"
# Initial state with no group member in the state machine -> unavailable
assert (
hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNAVAILABLE
)
# All group members unavailable -> unavailable
hass.states.async_set("binary_sensor.test1", STATE_UNAVAILABLE)
hass.states.async_set("binary_sensor.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert (
hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNAVAILABLE
)
# All group members unknown -> unknown
hass.states.async_set("binary_sensor.test1", STATE_UNKNOWN)
hass.states.async_set("binary_sensor.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNKNOWN
# Group members unknown or unavailable -> unknown
hass.states.async_set("binary_sensor.test1", STATE_UNKNOWN)
hass.states.async_set("binary_sensor.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNKNOWN
# At least one member on -> group on
hass.states.async_set("binary_sensor.test1", STATE_ON)
hass.states.async_set("binary_sensor.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_ON
hass.states.async_set("binary_sensor.test1", STATE_ON)
hass.states.async_set("binary_sensor.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_ON
hass.states.async_set("binary_sensor.test1", STATE_ON)
hass.states.async_set("binary_sensor.test2", STATE_ON)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_ON
hass.states.async_set("binary_sensor.test1", STATE_ON)
hass.states.async_set("binary_sensor.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_ON
# Otherwise -> off
hass.states.async_set("binary_sensor.test1", STATE_OFF)
hass.states.async_set("binary_sensor.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_OFF
hass.states.async_set("binary_sensor.test1", STATE_UNKNOWN)
hass.states.async_set("binary_sensor.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_OFF
hass.states.async_set("binary_sensor.test1", STATE_UNAVAILABLE)
hass.states.async_set("binary_sensor.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.binary_sensor_group").state == STATE_OFF
# All group members removed from the state machine -> unavailable
hass.states.async_remove("binary_sensor.test1")
hass.states.async_remove("binary_sensor.test2")
await hass.async_block_till_done()
assert (
hass.states.get("binary_sensor.binary_sensor_group").state == STATE_UNAVAILABLE
)

View File

@@ -0,0 +1,122 @@
"""The tests for the group button platform."""
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.components.group import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
async def test_default_state(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test button group default state."""
hass.states.async_set("button.notify_light", "2021-01-01T23:59:59.123+00:00")
await async_setup_component(
hass,
BUTTON_DOMAIN,
{
BUTTON_DOMAIN: {
"platform": DOMAIN,
"entities": ["button.notify_light", "button.self_destruct"],
"name": "Button group",
"unique_id": "unique_identifier",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("button.button_group")
assert state is not None
assert state.state == STATE_UNKNOWN
assert state.attributes.get(ATTR_ENTITY_ID) == [
"button.notify_light",
"button.self_destruct",
]
entry = entity_registry.async_get("button.button_group")
assert entry
assert entry.unique_id == "unique_identifier"
async def test_state_reporting(hass: HomeAssistant) -> None:
"""Test the state reporting.
The group state is unavailable if all group members are unavailable.
Otherwise, the group state represents the last time the grouped button was pressed.
"""
await async_setup_component(
hass,
BUTTON_DOMAIN,
{
BUTTON_DOMAIN: {
"platform": DOMAIN,
"entities": ["button.test1", "button.test2"],
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
# Initial state with no group member in the state machine -> unavailable
assert hass.states.get("button.button_group").state == STATE_UNAVAILABLE
# All group members unavailable -> unavailable
hass.states.async_set("button.test1", STATE_UNAVAILABLE)
hass.states.async_set("button.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("button.button_group").state == STATE_UNAVAILABLE
# All group members available, but no group member pressed -> unknown
hass.states.async_set("button.test1", "2021-01-01T23:59:59.123+00:00")
hass.states.async_set("button.test2", "2022-02-02T23:59:59.123+00:00")
await hass.async_block_till_done()
assert hass.states.get("button.button_group").state == STATE_UNKNOWN
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_service_calls(
hass: HomeAssistant, freezer: FrozenDateTimeFactory
) -> None:
"""Test service calls."""
await async_setup_component(
hass,
BUTTON_DOMAIN,
{
BUTTON_DOMAIN: [
{"platform": "demo"},
{
"platform": DOMAIN,
"entities": [
"button.push",
"button.self_destruct",
],
},
]
},
)
await hass.async_block_till_done()
assert hass.states.get("button.button_group").state == STATE_UNKNOWN
assert hass.states.get("button.push").state == STATE_UNKNOWN
now = dt_util.parse_datetime("2021-01-09 12:00:00+00:00")
freezer.move_to(now)
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.button_group"},
blocking=True,
)
assert hass.states.get("button.button_group").state == now.isoformat()
assert hass.states.get("button.push").state == now.isoformat()

View File

@@ -0,0 +1,740 @@
"""Test the Switch config flow."""
from typing import Any
from unittest.mock import patch
import pytest
from homeassistant import config_entries
from homeassistant.components.group import DOMAIN, async_setup_entry
from homeassistant.const import STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry
from tests.typing import WebSocketGenerator
@pytest.mark.parametrize(
(
"group_type",
"group_state",
"member_state",
"member_attributes",
"extra_input",
"extra_options",
"extra_attrs",
),
[
("binary_sensor", "on", "on", {}, {}, {"all": False}, {}),
("binary_sensor", "on", "on", {}, {"all": True}, {"all": True}, {}),
("button", STATE_UNKNOWN, "2021-01-01T23:59:59.123+00:00", {}, {}, {}, {}),
("cover", "open", "open", {}, {}, {}, {}),
(
"event",
STATE_UNKNOWN,
"2021-01-01T23:59:59.123+00:00",
{
"event_type": "single_press",
"event_types": ["single_press", "double_press"],
},
{},
{},
{},
),
("fan", "on", "on", {}, {}, {}, {}),
("light", "on", "on", {}, {}, {}, {}),
("lock", "locked", "locked", {}, {}, {}, {}),
("notify", STATE_UNKNOWN, "2021-01-01T23:59:59.123+00:00", {}, {}, {}, {}),
("media_player", "on", "on", {}, {}, {}, {}),
(
"sensor",
"20.0",
"10",
{},
{"type": "sum"},
{"type": "sum"},
{},
),
("switch", "on", "on", {}, {}, {}, {}),
],
)
async def test_config_flow(
hass: HomeAssistant,
group_type,
group_state,
member_state,
member_attributes,
extra_input,
extra_options,
extra_attrs,
) -> None:
"""Test the config flow."""
members = [f"{group_type}.one", f"{group_type}.two"]
for member in members:
hass.states.async_set(member, member_state, member_attributes)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"next_step_id": group_type},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == group_type
with patch(
"homeassistant.components.group.async_setup_entry", wraps=async_setup_entry
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"name": "Living Room",
"entities": members,
**extra_input,
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Living Room"
assert result["data"] == {}
assert result["options"] == {
"entities": members,
"group_type": group_type,
"hide_members": False,
"name": "Living Room",
**extra_options,
}
assert len(mock_setup_entry.mock_calls) == 1
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
assert config_entry.data == {}
assert config_entry.options == {
"entities": members,
"group_type": group_type,
"hide_members": False,
"name": "Living Room",
**extra_options,
}
state = hass.states.get(f"{group_type}.living_room")
assert state.state == group_state
assert state.attributes["entity_id"] == members
for key in extra_attrs:
assert state.attributes[key] == extra_attrs[key]
@pytest.mark.parametrize(
("hide_members", "hidden_by"), [(False, None), (True, "integration")]
)
@pytest.mark.parametrize(
("group_type", "extra_input"),
[
("binary_sensor", {"all": False}),
("button", {}),
("cover", {}),
("event", {}),
("fan", {}),
("light", {}),
("lock", {}),
("notify", {}),
("media_player", {}),
("switch", {}),
],
)
async def test_config_flow_hides_members(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
group_type,
extra_input,
hide_members,
hidden_by,
) -> None:
"""Test the config flow hides members if requested."""
fake_uuid = "a266a680b608c32770e6c45bfe6b8411"
entry = entity_registry.async_get_or_create(
group_type, "test", "unique", suggested_object_id="one"
)
assert entry.entity_id == f"{group_type}.one"
assert entry.hidden_by is None
entry = entity_registry.async_get_or_create(
group_type, "test", "unique3", suggested_object_id="three"
)
assert entry.entity_id == f"{group_type}.three"
assert entry.hidden_by is None
members = [f"{group_type}.one", f"{group_type}.two", fake_uuid, entry.id]
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"next_step_id": group_type},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == group_type
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"name": "Living Room",
"entities": members,
"hide_members": hide_members,
**extra_input,
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert entity_registry.async_get(f"{group_type}.one").hidden_by == hidden_by
assert entity_registry.async_get(f"{group_type}.three").hidden_by == hidden_by
def get_suggested(schema, key):
"""Get suggested value for key in voluptuous schema."""
for k in schema:
if k == key:
if k.description is None or "suggested_value" not in k.description:
return None
return k.description["suggested_value"]
# Wanted key absent from schema
raise KeyError("Wanted key absent from schema")
@pytest.mark.parametrize(
("group_type", "member_state", "extra_options", "options_options"),
[
("binary_sensor", "on", {"all": False}, {}),
("button", "2021-01-01T23:59:59.123+00:00", {}, {}),
("cover", "open", {}, {}),
("event", "2021-01-01T23:59:59.123+00:00", {}, {}),
("fan", "on", {}, {}),
("light", "on", {"all": False}, {}),
("lock", "locked", {}, {}),
("notify", "2021-01-01T23:59:59.123+00:00", {}, {}),
("media_player", "on", {}, {}),
(
"sensor",
"10",
{"ignore_non_numeric": False, "type": "sum"},
{"ignore_non_numeric": False, "type": "sum"},
),
("switch", "on", {"all": False}, {}),
],
)
async def test_options(
hass: HomeAssistant, group_type, member_state, extra_options, options_options
) -> None:
"""Test reconfiguring."""
members1 = [f"{group_type}.one", f"{group_type}.two"]
members2 = [f"{group_type}.four", f"{group_type}.five"]
for member in members1:
hass.states.async_set(member, member_state, {})
for member in members2:
hass.states.async_set(member, member_state, {})
group_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"entities": members1,
"group_type": group_type,
"name": "Bed Room",
**extra_options,
},
title="Bed Room",
)
group_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(group_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(f"{group_type}.bed_room")
assert state.attributes["entity_id"] == members1
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == group_type
assert get_suggested(result["data_schema"].schema, "entities") == members1
assert "name" not in result["data_schema"].schema
assert result["data_schema"].schema["entities"].config["exclude_entities"] == [
f"{group_type}.bed_room"
]
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={"entities": members2, **options_options},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
"entities": members2,
"group_type": group_type,
"hide_members": False,
"name": "Bed Room",
**extra_options,
}
assert config_entry.data == {}
assert config_entry.options == {
"entities": members2,
"group_type": group_type,
"hide_members": False,
"name": "Bed Room",
**extra_options,
}
assert config_entry.title == "Bed Room"
# Check config entry is reloaded with new options
await hass.async_block_till_done()
state = hass.states.get(f"{group_type}.bed_room")
assert state.attributes["entity_id"] == members2
# Check we don't get suggestions from another entry
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"next_step_id": group_type},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == group_type
assert get_suggested(result["data_schema"].schema, "entities") is None
assert get_suggested(result["data_schema"].schema, "name") is None
@pytest.mark.parametrize(
("group_type", "extra_options", "extra_options_after", "advanced"),
[
("light", {"all": False}, {"all": False}, False),
("light", {"all": True}, {"all": True}, False),
("light", {"all": False}, {"all": False}, True),
("light", {"all": True}, {"all": False}, True),
("switch", {"all": False}, {"all": False}, False),
("switch", {"all": True}, {"all": True}, False),
("switch", {"all": False}, {"all": False}, True),
("switch", {"all": True}, {"all": False}, True),
],
)
async def test_all_options(
hass: HomeAssistant, group_type, extra_options, extra_options_after, advanced
) -> None:
"""Test reconfiguring."""
members1 = [f"{group_type}.one", f"{group_type}.two"]
members2 = [f"{group_type}.four", f"{group_type}.five"]
group_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"entities": members1,
"group_type": group_type,
"name": "Bed Room",
**extra_options,
},
title="Bed Room",
)
group_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(group_config_entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get(f"{group_type}.bed_room")
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
result = await hass.config_entries.options.async_init(
config_entry.entry_id, context={"show_advanced_options": advanced}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == group_type
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
"entities": members2,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
"entities": members2,
"group_type": group_type,
"hide_members": False,
"name": "Bed Room",
**extra_options_after,
}
assert config_entry.data == {}
assert config_entry.options == {
"entities": members2,
"group_type": group_type,
"hide_members": False,
"name": "Bed Room",
**extra_options_after,
}
assert config_entry.title == "Bed Room"
@pytest.mark.parametrize(
("hide_members", "hidden_by_initial", "hidden_by"),
[
(False, er.RegistryEntryHider.INTEGRATION, None),
(True, None, er.RegistryEntryHider.INTEGRATION),
],
)
@pytest.mark.parametrize(
("group_type", "extra_input"),
[
("binary_sensor", {"all": False}),
("button", {}),
("cover", {}),
("event", {}),
("fan", {}),
("light", {}),
("lock", {}),
("notify", {}),
("media_player", {}),
("switch", {}),
],
)
async def test_options_flow_hides_members(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
group_type,
extra_input,
hide_members,
hidden_by_initial,
hidden_by,
) -> None:
"""Test the options flow hides or unhides members if requested."""
fake_uuid = "a266a680b608c32770e6c45bfe6b8411"
entry = entity_registry.async_get_or_create(
group_type,
"test",
"unique1",
suggested_object_id="one",
hidden_by=hidden_by_initial,
)
assert entry.entity_id == f"{group_type}.one"
entry = entity_registry.async_get_or_create(
group_type,
"test",
"unique3",
suggested_object_id="three",
hidden_by=hidden_by_initial,
)
assert entry.entity_id == f"{group_type}.three"
members = [f"{group_type}.one", f"{group_type}.two", fake_uuid, entry.id]
group_config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"entities": members,
"group_type": group_type,
"hide_members": False,
"name": "Bed Room",
**extra_input,
},
title="Bed Room",
)
group_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(group_config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(group_config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
"entities": members,
"hide_members": hide_members,
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert entity_registry.async_get(f"{group_type}.one").hidden_by == hidden_by
assert entity_registry.async_get(f"{group_type}.three").hidden_by == hidden_by
COVER_ATTRS = [{"supported_features": 0}, {}]
EVENT_ATTRS = [{"event_types": []}, {"event_type": None}]
FAN_ATTRS = [{"supported_features": 0}, {}]
LIGHT_ATTRS = [
{
"icon": "mdi:lightbulb-group",
"supported_color_modes": ["onoff"],
"supported_features": 0,
},
{"color_mode": "unknown"},
]
LOCK_ATTRS = [{"supported_features": 1}, {}]
NOTIFY_ATTRS = [{"supported_features": 0}, {}]
MEDIA_PLAYER_ATTRS = [{"supported_features": 0}, {}]
SENSOR_ATTRS = [{"icon": "mdi:calculator"}, {"max_entity_id": "sensor.input_two"}]
@pytest.mark.parametrize(
("domain", "extra_user_input", "input_states", "group_state", "extra_attributes"),
[
("binary_sensor", {"all": True}, ["on", "off"], "off", [{}, {}]),
("button", {}, ["", ""], "unknown", [{}, {}]),
("cover", {}, ["open", "closed"], "open", COVER_ATTRS),
("event", {}, ["", ""], "unknown", EVENT_ATTRS),
("fan", {}, ["on", "off"], "on", FAN_ATTRS),
("light", {}, ["on", "off"], "on", LIGHT_ATTRS),
("lock", {}, ["unlocked", "locked"], "unlocked", LOCK_ATTRS),
("notify", {}, ["", ""], "unknown", NOTIFY_ATTRS),
("media_player", {}, ["on", "off"], "on", MEDIA_PLAYER_ATTRS),
("sensor", {"type": "max"}, ["10", "20"], "20.0", SENSOR_ATTRS),
("switch", {}, ["on", "off"], "on", [{}, {}]),
],
)
async def test_config_flow_preview(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
domain: str,
extra_user_input: dict[str, Any],
input_states: list[str],
group_state: str,
extra_attributes: list[dict[str, Any]],
) -> None:
"""Test the config flow preview."""
client = await hass_ws_client(hass)
input_entities = [f"{domain}.input_one", f"{domain}.input_two"]
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"next_step_id": domain},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == domain
assert result["errors"] is None
assert result["preview"] == "group"
await client.send_json_auto_id(
{
"type": "group/start_preview",
"flow_id": result["flow_id"],
"flow_type": "config_flow",
"user_input": {"name": "My group", "entities": input_entities}
| extra_user_input,
}
)
msg = await client.receive_json()
preview_subscribe_id = msg["id"]
assert msg["success"]
assert msg["result"] is None
msg = await client.receive_json()
assert msg["event"] == {
"attributes": {"friendly_name": "My group"} | extra_attributes[0],
"state": "unavailable",
}
await client.send_json_auto_id(
{
"type": "unsubscribe_events",
"subscription": preview_subscribe_id,
}
)
msg = await client.receive_json()
assert msg["success"]
hass.states.async_set(input_entities[0], input_states[0])
hass.states.async_set(input_entities[1], input_states[1])
await client.send_json_auto_id(
{
"type": "group/start_preview",
"flow_id": result["flow_id"],
"flow_type": "config_flow",
"user_input": {"name": "My group", "entities": input_entities}
| extra_user_input,
}
)
msg = await client.receive_json()
preview_subscribe_id = msg["id"]
assert msg["success"]
assert msg["result"] is None
msg = await client.receive_json()
assert msg["event"] == {
"attributes": {
"entity_id": input_entities,
"friendly_name": "My group",
}
| extra_attributes[0]
| extra_attributes[1],
"state": group_state,
}
assert len(hass.states.async_all()) == 2
@pytest.mark.parametrize(
(
"domain",
"extra_config_flow_data",
"extra_user_input",
"input_states",
"group_state",
"extra_attributes",
),
[
("binary_sensor", {"all": True}, {"all": False}, ["on", "off"], "on", [{}, {}]),
("button", {}, {}, ["", ""], "unknown", [{}, {}]),
("cover", {}, {}, ["open", "closed"], "open", COVER_ATTRS),
("event", {}, {}, ["", ""], "unknown", EVENT_ATTRS),
("fan", {}, {}, ["on", "off"], "on", FAN_ATTRS),
("light", {}, {}, ["on", "off"], "on", LIGHT_ATTRS),
("lock", {}, {}, ["unlocked", "locked"], "unlocked", LOCK_ATTRS),
("notify", {}, {}, ["", ""], "unknown", NOTIFY_ATTRS),
("media_player", {}, {}, ["on", "off"], "on", MEDIA_PLAYER_ATTRS),
(
"sensor",
{"type": "min"},
{"type": "max"},
["10", "20"],
"20.0",
SENSOR_ATTRS,
),
("switch", {}, {}, ["on", "off"], "on", [{}, {}]),
],
)
async def test_option_flow_preview(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
domain: str,
extra_config_flow_data: dict[str, Any],
extra_user_input: dict[str, Any],
input_states: list[str],
group_state: str,
extra_attributes: dict[str, Any],
) -> None:
"""Test the option flow preview."""
input_entities = [f"{domain}.input_one", f"{domain}.input_two"]
# Setup the config entry
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"entities": input_entities,
"group_type": domain,
"hide_members": False,
"name": "My group",
}
| extra_config_flow_data,
title="My group",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
client = await hass_ws_client(hass)
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
assert result["preview"] == "group"
hass.states.async_set(input_entities[0], input_states[0])
hass.states.async_set(input_entities[1], input_states[1])
await client.send_json_auto_id(
{
"type": "group/start_preview",
"flow_id": result["flow_id"],
"flow_type": "options_flow",
"user_input": {"entities": input_entities} | extra_user_input,
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] is None
msg = await client.receive_json()
assert msg["event"] == {
"attributes": {"entity_id": input_entities, "friendly_name": "My group"}
| extra_attributes[0]
| extra_attributes[1],
"state": group_state,
}
assert len(hass.states.async_all()) == 3
async def test_option_flow_sensor_preview_config_entry_removed(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test the option flow preview where the config entry is removed."""
client = await hass_ws_client(hass)
input_entities = ["sensor.input_one", "sensor.input_two"]
# Setup the config entry
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"entities": input_entities,
"group_type": "sensor",
"hide_members": False,
"name": "My sensor group",
"type": "min",
},
title="My min_max",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
assert result["preview"] == "group"
await hass.config_entries.async_remove(config_entry.entry_id)
await client.send_json_auto_id(
{
"type": "group/start_preview",
"flow_id": result["flow_id"],
"flow_type": "options_flow",
"user_input": {
"entities": input_entities,
"type": "min",
},
}
)
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"] == {"code": "home_assistant_error", "message": "Unknown error"}

View File

@@ -0,0 +1,908 @@
"""The tests for the group cover platform."""
import asyncio
from datetime import timedelta
from typing import Any
import pytest
from homeassistant.components.cover import (
ATTR_CURRENT_POSITION,
ATTR_CURRENT_TILT_POSITION,
ATTR_POSITION,
ATTR_TILT_POSITION,
DOMAIN as COVER_DOMAIN,
CoverState,
)
from homeassistant.components.group.cover import DEFAULT_NAME
from homeassistant.const import (
ATTR_ASSUMED_STATE,
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
ATTR_SUPPORTED_FEATURES,
CONF_ENTITIES,
CONF_UNIQUE_ID,
SERVICE_CLOSE_COVER,
SERVICE_CLOSE_COVER_TILT,
SERVICE_OPEN_COVER,
SERVICE_OPEN_COVER_TILT,
SERVICE_SET_COVER_POSITION,
SERVICE_SET_COVER_TILT_POSITION,
SERVICE_STOP_COVER,
SERVICE_STOP_COVER_TILT,
SERVICE_TOGGLE,
SERVICE_TOGGLE_COVER_TILT,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from tests.common import assert_setup_component, async_fire_time_changed
COVER_GROUP = "cover.cover_group"
DEMO_COVER = "cover.kitchen_window"
DEMO_COVER_POS = "cover.hall_window"
DEMO_COVER_TILT = "cover.living_room_window"
DEMO_TILT = "cover.tilt_demo"
CONFIG_ALL = {
COVER_DOMAIN: [
{"platform": "demo"},
{
"platform": "group",
CONF_ENTITIES: [DEMO_COVER, DEMO_COVER_POS, DEMO_COVER_TILT, DEMO_TILT],
},
]
}
CONFIG_POS = {
COVER_DOMAIN: [
{"platform": "demo"},
{
"platform": "group",
CONF_ENTITIES: [DEMO_COVER_POS, DEMO_COVER_TILT, DEMO_TILT],
},
]
}
CONFIG_TILT_ONLY = {
COVER_DOMAIN: [
{"platform": "demo"},
{
"platform": "group",
CONF_ENTITIES: [DEMO_COVER_TILT, DEMO_TILT],
},
]
}
CONFIG_ATTRIBUTES = {
COVER_DOMAIN: {
"platform": "group",
CONF_ENTITIES: [DEMO_COVER, DEMO_COVER_POS, DEMO_COVER_TILT, DEMO_TILT],
CONF_UNIQUE_ID: "unique_identifier",
}
}
@pytest.fixture
async def setup_comp(
hass: HomeAssistant, config_count: tuple[dict[str, Any], int]
) -> None:
"""Set up group cover component."""
config, count = config_count
with assert_setup_component(count, COVER_DOMAIN):
await async_setup_component(hass, COVER_DOMAIN, config)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
@pytest.mark.parametrize("config_count", [(CONFIG_ATTRIBUTES, 1)])
@pytest.mark.usefixtures("setup_comp")
async def test_state(hass: HomeAssistant) -> None:
"""Test handling of state.
The group state is unknown if all group members are unknown or unavailable.
Otherwise, the group state is opening if at least one group member is opening.
Otherwise, the group state is closing if at least one group member is closing.
Otherwise, the group state is open if at least one group member is open.
Otherwise, the group state is closed.
"""
state = hass.states.get(COVER_GROUP)
# No entity has a valid state -> group state unavailable
assert state.state == STATE_UNAVAILABLE
assert state.attributes[ATTR_FRIENDLY_NAME] == DEFAULT_NAME
assert ATTR_ENTITY_ID not in state.attributes
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
assert ATTR_CURRENT_POSITION not in state.attributes
assert ATTR_CURRENT_TILT_POSITION not in state.attributes
# Test group members exposed as attribute
hass.states.async_set(DEMO_COVER, STATE_UNKNOWN, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.attributes[ATTR_ENTITY_ID] == [
DEMO_COVER,
DEMO_COVER_POS,
DEMO_COVER_TILT,
DEMO_TILT,
]
# The group state is unavailable if all group members are unavailable.
hass.states.async_set(DEMO_COVER, STATE_UNAVAILABLE, {})
hass.states.async_set(DEMO_COVER_POS, STATE_UNAVAILABLE, {})
hass.states.async_set(DEMO_COVER_TILT, STATE_UNAVAILABLE, {})
hass.states.async_set(DEMO_TILT, STATE_UNAVAILABLE, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == STATE_UNAVAILABLE
# The group state is unknown if all group members are unknown or unavailable.
for state_1 in (STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_2 in (STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_3 in (STATE_UNAVAILABLE, STATE_UNKNOWN):
hass.states.async_set(DEMO_COVER, state_1, {})
hass.states.async_set(DEMO_COVER_POS, state_2, {})
hass.states.async_set(DEMO_COVER_TILT, state_3, {})
hass.states.async_set(DEMO_TILT, STATE_UNKNOWN, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == STATE_UNKNOWN
# At least one member opening -> group opening
for state_1 in (
CoverState.CLOSED,
CoverState.CLOSING,
CoverState.OPEN,
CoverState.OPENING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_2 in (
CoverState.CLOSED,
CoverState.CLOSING,
CoverState.OPEN,
CoverState.OPENING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_3 in (
CoverState.CLOSED,
CoverState.CLOSING,
CoverState.OPEN,
CoverState.OPENING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
hass.states.async_set(DEMO_COVER, state_1, {})
hass.states.async_set(DEMO_COVER_POS, state_2, {})
hass.states.async_set(DEMO_COVER_TILT, state_3, {})
hass.states.async_set(DEMO_TILT, CoverState.OPENING, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPENING
# At least one member closing -> group closing
for state_1 in (
CoverState.CLOSED,
CoverState.CLOSING,
CoverState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_2 in (
CoverState.CLOSED,
CoverState.CLOSING,
CoverState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_3 in (
CoverState.CLOSED,
CoverState.CLOSING,
CoverState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
hass.states.async_set(DEMO_COVER, state_1, {})
hass.states.async_set(DEMO_COVER_POS, state_2, {})
hass.states.async_set(DEMO_COVER_TILT, state_3, {})
hass.states.async_set(DEMO_TILT, CoverState.CLOSING, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.CLOSING
# At least one member open -> group open
for state_1 in (
CoverState.CLOSED,
CoverState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_2 in (
CoverState.CLOSED,
CoverState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_3 in (
CoverState.CLOSED,
CoverState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
hass.states.async_set(DEMO_COVER, state_1, {})
hass.states.async_set(DEMO_COVER_POS, state_2, {})
hass.states.async_set(DEMO_COVER_TILT, state_3, {})
hass.states.async_set(DEMO_TILT, CoverState.OPEN, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
# At least one member closed -> group closed
for state_1 in (CoverState.CLOSED, STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_2 in (CoverState.CLOSED, STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_3 in (CoverState.CLOSED, STATE_UNAVAILABLE, STATE_UNKNOWN):
hass.states.async_set(DEMO_COVER, state_1, {})
hass.states.async_set(DEMO_COVER_POS, state_2, {})
hass.states.async_set(DEMO_COVER_TILT, state_3, {})
hass.states.async_set(DEMO_TILT, CoverState.CLOSED, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.CLOSED
# All group members removed from the state machine -> unavailable
hass.states.async_remove(DEMO_COVER)
hass.states.async_remove(DEMO_COVER_POS)
hass.states.async_remove(DEMO_COVER_TILT)
hass.states.async_remove(DEMO_TILT)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == STATE_UNAVAILABLE
@pytest.mark.parametrize("config_count", [(CONFIG_ATTRIBUTES, 1)])
@pytest.mark.usefixtures("setup_comp")
async def test_attributes(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test handling of state attributes."""
state = hass.states.get(COVER_GROUP)
assert state.state == STATE_UNAVAILABLE
assert state.attributes[ATTR_FRIENDLY_NAME] == DEFAULT_NAME
assert ATTR_ENTITY_ID not in state.attributes
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
assert ATTR_CURRENT_POSITION not in state.attributes
assert ATTR_CURRENT_TILT_POSITION not in state.attributes
# Set entity as closed
hass.states.async_set(DEMO_COVER, CoverState.CLOSED, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.CLOSED
assert state.attributes[ATTR_ENTITY_ID] == [
DEMO_COVER,
DEMO_COVER_POS,
DEMO_COVER_TILT,
DEMO_TILT,
]
# Set entity as opening
hass.states.async_set(DEMO_COVER, CoverState.OPENING, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPENING
# Set entity as closing
hass.states.async_set(DEMO_COVER, CoverState.CLOSING, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.CLOSING
# Set entity as unknown again
hass.states.async_set(DEMO_COVER, STATE_UNKNOWN, {})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == STATE_UNKNOWN
# Add Entity that supports open / close / stop
hass.states.async_set(DEMO_COVER, CoverState.OPEN, {ATTR_SUPPORTED_FEATURES: 11})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 11
assert ATTR_CURRENT_POSITION not in state.attributes
assert ATTR_CURRENT_TILT_POSITION not in state.attributes
# Add Entity that supports set_cover_position
hass.states.async_set(
DEMO_COVER_POS,
CoverState.OPEN,
{ATTR_SUPPORTED_FEATURES: 4, ATTR_CURRENT_POSITION: 70},
)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 15
assert state.attributes[ATTR_CURRENT_POSITION] == 70
assert ATTR_CURRENT_TILT_POSITION not in state.attributes
# Add Entity that supports open tilt / close tilt / stop tilt
hass.states.async_set(DEMO_TILT, CoverState.OPEN, {ATTR_SUPPORTED_FEATURES: 112})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 127
assert state.attributes[ATTR_CURRENT_POSITION] == 70
assert ATTR_CURRENT_TILT_POSITION not in state.attributes
# Add Entity that supports set_tilt_position
hass.states.async_set(
DEMO_COVER_TILT,
CoverState.OPEN,
{ATTR_SUPPORTED_FEATURES: 128, ATTR_CURRENT_TILT_POSITION: 60},
)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 255
assert state.attributes[ATTR_CURRENT_POSITION] == 70
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 60
# ### Test state when group members have different states ###
# ##########################
# Covers
hass.states.async_set(
DEMO_COVER,
CoverState.OPEN,
{ATTR_SUPPORTED_FEATURES: 4, ATTR_CURRENT_POSITION: 100},
)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 244
assert state.attributes[ATTR_CURRENT_POSITION] == 85 # (70 + 100) / 2
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 60
hass.states.async_remove(DEMO_COVER)
hass.states.async_remove(DEMO_COVER_POS)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 240
assert ATTR_CURRENT_POSITION not in state.attributes
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 60
# Tilts
hass.states.async_set(
DEMO_TILT,
CoverState.OPEN,
{ATTR_SUPPORTED_FEATURES: 128, ATTR_CURRENT_TILT_POSITION: 100},
)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 128
assert ATTR_CURRENT_POSITION not in state.attributes
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 80 # (60 + 100) / 2
hass.states.async_remove(DEMO_COVER_TILT)
hass.states.async_set(DEMO_TILT, CoverState.CLOSED)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.CLOSED
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
assert ATTR_CURRENT_POSITION not in state.attributes
assert ATTR_CURRENT_TILT_POSITION not in state.attributes
# Group member has set assumed_state
hass.states.async_set(DEMO_TILT, CoverState.CLOSED, {ATTR_ASSUMED_STATE: True})
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert ATTR_ASSUMED_STATE not in state.attributes
# Test entity registry integration
entry = entity_registry.async_get(COVER_GROUP)
assert entry
assert entry.unique_id == "unique_identifier"
@pytest.mark.parametrize("config_count", [(CONFIG_TILT_ONLY, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_cover_that_only_supports_tilt_removed(hass: HomeAssistant) -> None:
"""Test removing a cover that support tilt."""
hass.states.async_set(
DEMO_COVER_TILT,
CoverState.OPEN,
{ATTR_SUPPORTED_FEATURES: 128, ATTR_CURRENT_TILT_POSITION: 60},
)
hass.states.async_set(
DEMO_TILT,
CoverState.OPEN,
{ATTR_SUPPORTED_FEATURES: 128, ATTR_CURRENT_TILT_POSITION: 60},
)
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_FRIENDLY_NAME] == DEFAULT_NAME
assert state.attributes[ATTR_ENTITY_ID] == [
DEMO_COVER_TILT,
DEMO_TILT,
]
assert ATTR_ASSUMED_STATE not in state.attributes
assert ATTR_CURRENT_TILT_POSITION in state.attributes
hass.states.async_remove(DEMO_COVER_TILT)
hass.states.async_set(DEMO_TILT, CoverState.CLOSED)
await hass.async_block_till_done()
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_open_covers(hass: HomeAssistant) -> None:
"""Test open cover function."""
await hass.services.async_call(
COVER_DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: COVER_GROUP}, blocking=True
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_CURRENT_POSITION] == 100
assert hass.states.get(DEMO_COVER).state == CoverState.OPEN
assert hass.states.get(DEMO_COVER_POS).attributes[ATTR_CURRENT_POSITION] == 100
assert hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_POSITION] == 100
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_close_covers(hass: HomeAssistant) -> None:
"""Test close cover function."""
await hass.services.async_call(
COVER_DOMAIN, SERVICE_CLOSE_COVER, {ATTR_ENTITY_ID: COVER_GROUP}, blocking=True
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.CLOSED
assert state.attributes[ATTR_CURRENT_POSITION] == 0
assert hass.states.get(DEMO_COVER).state == CoverState.CLOSED
assert hass.states.get(DEMO_COVER_POS).attributes[ATTR_CURRENT_POSITION] == 0
assert hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_POSITION] == 0
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_toggle_covers(hass: HomeAssistant) -> None:
"""Test toggle cover function."""
# Start covers in open state
await hass.services.async_call(
COVER_DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: COVER_GROUP}, blocking=True
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
# Toggle will close covers
await hass.services.async_call(
COVER_DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: COVER_GROUP}, blocking=True
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.CLOSED
assert state.attributes[ATTR_CURRENT_POSITION] == 0
assert hass.states.get(DEMO_COVER).state == CoverState.CLOSED
assert hass.states.get(DEMO_COVER_POS).attributes[ATTR_CURRENT_POSITION] == 0
assert hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_POSITION] == 0
# Toggle again will open covers
await hass.services.async_call(
COVER_DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: COVER_GROUP}, blocking=True
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_CURRENT_POSITION] == 100
assert hass.states.get(DEMO_COVER).state == CoverState.OPEN
assert hass.states.get(DEMO_COVER_POS).attributes[ATTR_CURRENT_POSITION] == 100
assert hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_POSITION] == 100
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_stop_covers(hass: HomeAssistant) -> None:
"""Test stop cover function."""
await hass.services.async_call(
COVER_DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: COVER_GROUP}, blocking=True
)
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
await hass.services.async_call(
COVER_DOMAIN, SERVICE_STOP_COVER, {ATTR_ENTITY_ID: COVER_GROUP}, blocking=True
)
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPENING
assert state.attributes[ATTR_CURRENT_POSITION] == 50 # (20 + 80) / 2
assert hass.states.get(DEMO_COVER).state == CoverState.OPEN
assert hass.states.get(DEMO_COVER_POS).attributes[ATTR_CURRENT_POSITION] == 20
assert hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_POSITION] == 80
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_set_cover_position(hass: HomeAssistant) -> None:
"""Test set cover position function."""
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_POSITION,
{ATTR_ENTITY_ID: COVER_GROUP, ATTR_POSITION: 50},
blocking=True,
)
for _ in range(4):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_CURRENT_POSITION] == 50
assert hass.states.get(DEMO_COVER).state == CoverState.CLOSED
assert hass.states.get(DEMO_COVER_POS).attributes[ATTR_CURRENT_POSITION] == 50
assert hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_POSITION] == 50
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_open_tilts(hass: HomeAssistant) -> None:
"""Test open tilt function."""
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER_TILT,
{ATTR_ENTITY_ID: COVER_GROUP},
blocking=True,
)
for _ in range(5):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 100
assert (
hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_TILT_POSITION] == 100
)
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_close_tilts(hass: HomeAssistant) -> None:
"""Test close tilt function."""
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER_TILT,
{ATTR_ENTITY_ID: COVER_GROUP},
blocking=True,
)
for _ in range(5):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 0
assert hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_TILT_POSITION] == 0
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_toggle_tilts(hass: HomeAssistant) -> None:
"""Test toggle tilt function."""
# Start tilted open
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER_TILT,
{ATTR_ENTITY_ID: COVER_GROUP},
blocking=True,
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 100
assert (
hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_TILT_POSITION] == 100
)
# Toggle will tilt closed
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_TOGGLE_COVER_TILT,
{ATTR_ENTITY_ID: COVER_GROUP},
blocking=True,
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 0
assert hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_TILT_POSITION] == 0
# Toggle again will tilt open
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_TOGGLE_COVER_TILT,
{ATTR_ENTITY_ID: COVER_GROUP},
blocking=True,
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 100
assert (
hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_TILT_POSITION] == 100
)
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_stop_tilts(hass: HomeAssistant) -> None:
"""Test stop tilts function."""
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER_TILT,
{ATTR_ENTITY_ID: COVER_GROUP},
blocking=True,
)
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_STOP_COVER_TILT,
{ATTR_ENTITY_ID: COVER_GROUP},
blocking=True,
)
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 60
assert hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_TILT_POSITION] == 60
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_set_tilt_positions(hass: HomeAssistant) -> None:
"""Test set tilt position function."""
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_TILT_POSITION,
{ATTR_ENTITY_ID: COVER_GROUP, ATTR_TILT_POSITION: 80},
blocking=True,
)
for _ in range(3):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(COVER_GROUP)
assert state.state == CoverState.OPEN
assert state.attributes[ATTR_CURRENT_TILT_POSITION] == 80
assert hass.states.get(DEMO_COVER_TILT).attributes[ATTR_CURRENT_TILT_POSITION] == 80
@pytest.mark.parametrize("config_count", [(CONFIG_POS, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_is_opening_closing(hass: HomeAssistant) -> None:
"""Test is_opening property."""
await hass.services.async_call(
COVER_DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: COVER_GROUP}, blocking=True
)
await hass.async_block_till_done()
# Both covers opening -> opening
assert hass.states.get(DEMO_COVER_POS).state == CoverState.OPENING
assert hass.states.get(DEMO_COVER_TILT).state == CoverState.OPENING
assert hass.states.get(COVER_GROUP).state == CoverState.OPENING
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
await hass.services.async_call(
COVER_DOMAIN, SERVICE_CLOSE_COVER, {ATTR_ENTITY_ID: COVER_GROUP}, blocking=True
)
# Both covers closing -> closing
assert hass.states.get(DEMO_COVER_POS).state == CoverState.CLOSING
assert hass.states.get(DEMO_COVER_TILT).state == CoverState.CLOSING
assert hass.states.get(COVER_GROUP).state == CoverState.CLOSING
hass.states.async_set(
DEMO_COVER_POS, CoverState.OPENING, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
# Closing + Opening -> Opening
assert hass.states.get(DEMO_COVER_TILT).state == CoverState.CLOSING
assert hass.states.get(DEMO_COVER_POS).state == CoverState.OPENING
assert hass.states.get(COVER_GROUP).state == CoverState.OPENING
hass.states.async_set(
DEMO_COVER_POS, CoverState.CLOSING, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
# Both covers closing -> closing
assert hass.states.get(DEMO_COVER_TILT).state == CoverState.CLOSING
assert hass.states.get(DEMO_COVER_POS).state == CoverState.CLOSING
assert hass.states.get(COVER_GROUP).state == CoverState.CLOSING
# Closed + Closing -> Closing
hass.states.async_set(
DEMO_COVER_POS, CoverState.CLOSED, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
assert hass.states.get(DEMO_COVER_TILT).state == CoverState.CLOSING
assert hass.states.get(DEMO_COVER_POS).state == CoverState.CLOSED
assert hass.states.get(COVER_GROUP).state == CoverState.CLOSING
# Open + Closing -> Closing
hass.states.async_set(
DEMO_COVER_POS, CoverState.OPEN, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
assert hass.states.get(DEMO_COVER_TILT).state == CoverState.CLOSING
assert hass.states.get(DEMO_COVER_POS).state == CoverState.OPEN
assert hass.states.get(COVER_GROUP).state == CoverState.CLOSING
# Closed + Opening -> Closing
hass.states.async_set(
DEMO_COVER_TILT, CoverState.OPENING, {ATTR_SUPPORTED_FEATURES: 11}
)
hass.states.async_set(
DEMO_COVER_POS, CoverState.CLOSED, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
assert hass.states.get(DEMO_COVER_TILT).state == CoverState.OPENING
assert hass.states.get(DEMO_COVER_POS).state == CoverState.CLOSED
assert hass.states.get(COVER_GROUP).state == CoverState.OPENING
# Open + Opening -> Closing
hass.states.async_set(
DEMO_COVER_POS, CoverState.OPEN, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
assert hass.states.get(DEMO_COVER_TILT).state == CoverState.OPENING
assert hass.states.get(DEMO_COVER_POS).state == CoverState.OPEN
assert hass.states.get(COVER_GROUP).state == CoverState.OPENING
async def test_nested_group(hass: HomeAssistant) -> None:
"""Test nested cover group."""
await async_setup_component(
hass,
COVER_DOMAIN,
{
COVER_DOMAIN: [
{"platform": "demo"},
{
"platform": "group",
"entities": ["cover.bedroom_group"],
"name": "Nested Group",
},
{
"platform": "group",
CONF_ENTITIES: [DEMO_COVER_POS, DEMO_COVER_TILT],
"name": "Bedroom Group",
},
]
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("cover.bedroom_group")
assert state is not None
assert state.state == CoverState.OPEN
assert state.attributes.get(ATTR_ENTITY_ID) == [DEMO_COVER_POS, DEMO_COVER_TILT]
state = hass.states.get("cover.nested_group")
assert state is not None
assert state.state == CoverState.OPEN
assert state.attributes.get(ATTR_ENTITY_ID) == ["cover.bedroom_group"]
# Test controlling the nested group
async with asyncio.timeout(0.5):
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{ATTR_ENTITY_ID: "cover.nested_group"},
blocking=True,
)
assert hass.states.get(DEMO_COVER_POS).state == CoverState.CLOSING
assert hass.states.get(DEMO_COVER_TILT).state == CoverState.CLOSING
assert hass.states.get("cover.bedroom_group").state == CoverState.CLOSING
assert hass.states.get("cover.nested_group").state == CoverState.CLOSING

View File

@@ -0,0 +1,142 @@
"""The tests for the group event platform."""
from pytest_unordered import unordered
from homeassistant.components.event import (
ATTR_EVENT_TYPE,
ATTR_EVENT_TYPES,
DOMAIN as EVENT_DOMAIN,
)
from homeassistant.components.group import DOMAIN
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_ENTITY_ID,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
async def test_default_state(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test event group default state."""
await async_setup_component(
hass,
EVENT_DOMAIN,
{
EVENT_DOMAIN: {
"platform": DOMAIN,
"entities": ["event.button_1", "event.button_2"],
"name": "Remote control",
"unique_id": "unique_identifier",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("event.remote_control")
assert state is not None
assert state.state == STATE_UNAVAILABLE
hass.states.async_set(
"event.button_1",
"2021-01-01T23:59:59.123+00:00",
{"event_type": "double_press", "event_types": ["single_press", "double_press"]},
)
await hass.async_block_till_done()
state = hass.states.get("event.remote_control")
assert state is not None
assert state.state == STATE_UNKNOWN
assert state.attributes.get(ATTR_ENTITY_ID) == ["event.button_1", "event.button_2"]
assert not state.attributes.get(ATTR_EVENT_TYPE)
assert state.attributes.get(ATTR_EVENT_TYPES) == unordered(
["single_press", "double_press"]
)
# State changed
hass.states.async_set(
"event.button_1",
"2021-01-01T23:59:59.123+00:00",
{"event_type": "single_press", "event_types": ["single_press", "double_press"]},
)
await hass.async_block_till_done()
state = hass.states.get("event.remote_control")
assert state is not None
assert state.state
assert state.attributes.get(ATTR_ENTITY_ID) == ["event.button_1", "event.button_2"]
assert state.attributes.get(ATTR_EVENT_TYPE) == "single_press"
assert state.attributes.get(ATTR_EVENT_TYPES) == unordered(
["single_press", "double_press"]
)
# State changed, second remote came online
hass.states.async_set(
"event.button_2",
"2021-01-01T23:59:59.123+00:00",
{"event_type": "double_press", "event_types": ["double_press", "triple_press"]},
)
await hass.async_block_till_done()
# State should be single_press, because button coming online is not an event
state = hass.states.get("event.remote_control")
assert state is not None
assert state.state
assert state.attributes.get(ATTR_ENTITY_ID) == ["event.button_1", "event.button_2"]
assert state.attributes.get(ATTR_EVENT_TYPE) == "single_press"
assert state.attributes.get(ATTR_EVENT_TYPES) == unordered(
["single_press", "double_press", "triple_press"]
)
# State changed, now it fires an event
hass.states.async_set(
"event.button_2",
"2021-01-01T23:59:59.123+00:00",
{
"event_type": "triple_press",
"event_types": ["double_press", "triple_press"],
"device_class": "doorbell",
},
)
await hass.async_block_till_done()
state = hass.states.get("event.remote_control")
assert state is not None
assert state.state
assert state.attributes.get(ATTR_ENTITY_ID) == ["event.button_1", "event.button_2"]
assert state.attributes.get(ATTR_EVENT_TYPE) == "triple_press"
assert state.attributes.get(ATTR_EVENT_TYPES) == unordered(
["single_press", "double_press", "triple_press"]
)
assert ATTR_DEVICE_CLASS not in state.attributes
# Mark button 1 unavailable
hass.states.async_set("event.button_1", STATE_UNAVAILABLE)
await hass.async_block_till_done()
state = hass.states.get("event.remote_control")
assert state is not None
assert state.state
assert state.attributes.get(ATTR_ENTITY_ID) == ["event.button_1", "event.button_2"]
assert state.attributes.get(ATTR_EVENT_TYPE) == "triple_press"
assert state.attributes.get(ATTR_EVENT_TYPES) == unordered(
["double_press", "triple_press"]
)
# Mark button 2 unavailable
hass.states.async_set("event.button_2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
state = hass.states.get("event.remote_control")
assert state is not None
assert state.state == STATE_UNAVAILABLE
entry = entity_registry.async_get("event.remote_control")
assert entry
assert entry.unique_id == "unique_identifier"

View File

@@ -0,0 +1,589 @@
"""The tests for the group fan platform."""
import asyncio
from typing import Any
from unittest.mock import patch
import pytest
from homeassistant import config as hass_config
from homeassistant.components.fan import (
ATTR_DIRECTION,
ATTR_OSCILLATING,
ATTR_PERCENTAGE,
ATTR_PERCENTAGE_STEP,
DIRECTION_FORWARD,
DIRECTION_REVERSE,
DOMAIN as FAN_DOMAIN,
SERVICE_OSCILLATE,
SERVICE_SET_DIRECTION,
SERVICE_SET_PERCENTAGE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
FanEntityFeature,
)
from homeassistant.components.group import SERVICE_RELOAD
from homeassistant.components.group.fan import DEFAULT_NAME
from homeassistant.const import (
ATTR_ASSUMED_STATE,
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
ATTR_SUPPORTED_FEATURES,
CONF_ENTITIES,
CONF_UNIQUE_ID,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import CoreState, HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import assert_setup_component, get_fixture_path
FAN_GROUP = "fan.fan_group"
MISSING_FAN_ENTITY_ID = "fan.missing"
LIVING_ROOM_FAN_ENTITY_ID = "fan.living_room_fan"
PERCENTAGE_FULL_FAN_ENTITY_ID = "fan.percentage_full_fan"
CEILING_FAN_ENTITY_ID = "fan.ceiling_fan"
PERCENTAGE_LIMITED_FAN_ENTITY_ID = "fan.percentage_limited_fan"
FULL_FAN_ENTITY_IDS = [LIVING_ROOM_FAN_ENTITY_ID, PERCENTAGE_FULL_FAN_ENTITY_ID]
LIMITED_FAN_ENTITY_IDS = [CEILING_FAN_ENTITY_ID, PERCENTAGE_LIMITED_FAN_ENTITY_ID]
FULL_SUPPORT_FEATURES = (
FanEntityFeature.SET_SPEED | FanEntityFeature.DIRECTION | FanEntityFeature.OSCILLATE
)
CONFIG_MISSING_FAN = {
FAN_DOMAIN: [
{"platform": "demo"},
{
"platform": "group",
CONF_ENTITIES: [
MISSING_FAN_ENTITY_ID,
*FULL_FAN_ENTITY_IDS,
*LIMITED_FAN_ENTITY_IDS,
],
},
]
}
CONFIG_FULL_SUPPORT = {
FAN_DOMAIN: [
{"platform": "demo"},
{
"platform": "group",
CONF_ENTITIES: [*FULL_FAN_ENTITY_IDS],
},
]
}
CONFIG_LIMITED_SUPPORT = {
FAN_DOMAIN: [
{
"platform": "group",
CONF_ENTITIES: [*LIMITED_FAN_ENTITY_IDS],
},
]
}
CONFIG_ATTRIBUTES = {
FAN_DOMAIN: {
"platform": "group",
CONF_ENTITIES: [*FULL_FAN_ENTITY_IDS, *LIMITED_FAN_ENTITY_IDS],
CONF_UNIQUE_ID: "unique_identifier",
}
}
@pytest.fixture
async def setup_comp(
hass: HomeAssistant, config_count: tuple[dict[str, Any], int]
) -> None:
"""Set up group fan component."""
config, count = config_count
with assert_setup_component(count, FAN_DOMAIN):
await async_setup_component(hass, FAN_DOMAIN, config)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
@pytest.mark.parametrize("config_count", [(CONFIG_ATTRIBUTES, 1)])
@pytest.mark.usefixtures("setup_comp")
async def test_state(hass: HomeAssistant, entity_registry: er.EntityRegistry) -> None:
"""Test handling of state.
The group state is on if at least one group member is on.
Otherwise, the group state is off.
"""
state = hass.states.get(FAN_GROUP)
# No entity has a valid state -> group state unavailable
assert state.state == STATE_UNAVAILABLE
assert state.attributes[ATTR_FRIENDLY_NAME] == DEFAULT_NAME
assert ATTR_ENTITY_ID not in state.attributes
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
# Test group members exposed as attribute
hass.states.async_set(CEILING_FAN_ENTITY_ID, STATE_UNKNOWN, {})
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.attributes[ATTR_ENTITY_ID] == [
*FULL_FAN_ENTITY_IDS,
*LIMITED_FAN_ENTITY_IDS,
]
# All group members unavailable -> unavailable
hass.states.async_set(CEILING_FAN_ENTITY_ID, STATE_UNAVAILABLE)
hass.states.async_set(LIVING_ROOM_FAN_ENTITY_ID, STATE_UNAVAILABLE)
hass.states.async_set(PERCENTAGE_FULL_FAN_ENTITY_ID, STATE_UNAVAILABLE)
hass.states.async_set(PERCENTAGE_LIMITED_FAN_ENTITY_ID, STATE_UNAVAILABLE)
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_UNAVAILABLE
# The group state is unknown if all group members are unknown or unavailable.
for state_1 in (STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_2 in (STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_3 in (STATE_UNAVAILABLE, STATE_UNKNOWN):
hass.states.async_set(CEILING_FAN_ENTITY_ID, state_1, {})
hass.states.async_set(LIVING_ROOM_FAN_ENTITY_ID, state_2, {})
hass.states.async_set(PERCENTAGE_FULL_FAN_ENTITY_ID, state_3, {})
hass.states.async_set(
PERCENTAGE_LIMITED_FAN_ENTITY_ID, STATE_UNKNOWN, {}
)
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_UNKNOWN
# The group state is off if all group members are off, unknown or unavailable.
for state_1 in (STATE_OFF, STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_2 in (STATE_OFF, STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_3 in (STATE_OFF, STATE_UNAVAILABLE, STATE_UNKNOWN):
hass.states.async_set(CEILING_FAN_ENTITY_ID, state_1, {})
hass.states.async_set(LIVING_ROOM_FAN_ENTITY_ID, state_2, {})
hass.states.async_set(PERCENTAGE_FULL_FAN_ENTITY_ID, state_3, {})
hass.states.async_set(PERCENTAGE_LIMITED_FAN_ENTITY_ID, STATE_OFF, {})
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_OFF
# At least one member on -> group on
for state_1 in (STATE_OFF, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_2 in (STATE_OFF, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_3 in (STATE_OFF, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN):
hass.states.async_set(CEILING_FAN_ENTITY_ID, state_1, {})
hass.states.async_set(LIVING_ROOM_FAN_ENTITY_ID, state_2, {})
hass.states.async_set(PERCENTAGE_FULL_FAN_ENTITY_ID, state_3, {})
hass.states.async_set(PERCENTAGE_LIMITED_FAN_ENTITY_ID, STATE_ON, {})
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_ON
# now remove an entity
hass.states.async_remove(PERCENTAGE_LIMITED_FAN_ENTITY_ID)
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_UNKNOWN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
# now remove all entities
hass.states.async_remove(CEILING_FAN_ENTITY_ID)
hass.states.async_remove(LIVING_ROOM_FAN_ENTITY_ID)
hass.states.async_remove(PERCENTAGE_FULL_FAN_ENTITY_ID)
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_UNAVAILABLE
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
# Test entity registry integration
entry = entity_registry.async_get(FAN_GROUP)
assert entry
assert entry.unique_id == "unique_identifier"
@pytest.mark.parametrize("config_count", [(CONFIG_ATTRIBUTES, 1)])
@pytest.mark.usefixtures("setup_comp")
async def test_attributes(hass: HomeAssistant) -> None:
"""Test handling of state attributes."""
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_UNAVAILABLE
assert state.attributes[ATTR_FRIENDLY_NAME] == DEFAULT_NAME
assert ATTR_ENTITY_ID not in state.attributes
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
hass.states.async_set(CEILING_FAN_ENTITY_ID, STATE_ON, {})
hass.states.async_set(LIVING_ROOM_FAN_ENTITY_ID, STATE_ON, {})
hass.states.async_set(PERCENTAGE_FULL_FAN_ENTITY_ID, STATE_ON, {})
hass.states.async_set(PERCENTAGE_LIMITED_FAN_ENTITY_ID, STATE_ON, {})
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_ON
assert state.attributes[ATTR_ENTITY_ID] == [
*FULL_FAN_ENTITY_IDS,
*LIMITED_FAN_ENTITY_IDS,
]
# Add Entity that supports speed
hass.states.async_set(
CEILING_FAN_ENTITY_ID,
STATE_ON,
{
ATTR_SUPPORTED_FEATURES: FanEntityFeature.SET_SPEED,
ATTR_PERCENTAGE: 50,
},
)
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_ON
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == FanEntityFeature.SET_SPEED
assert ATTR_PERCENTAGE in state.attributes
assert state.attributes[ATTR_PERCENTAGE] == 50
assert ATTR_ASSUMED_STATE not in state.attributes
# Add Entity with a different speed should not set assumed state
hass.states.async_set(
PERCENTAGE_LIMITED_FAN_ENTITY_ID,
STATE_ON,
{
ATTR_SUPPORTED_FEATURES: FanEntityFeature.SET_SPEED,
ATTR_PERCENTAGE: 75,
},
)
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_ON
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_PERCENTAGE] == int((50 + 75) / 2)
@pytest.mark.parametrize("config_count", [(CONFIG_FULL_SUPPORT, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_direction_oscillating(hass: HomeAssistant) -> None:
"""Test handling of direction and oscillating attributes."""
hass.states.async_set(
LIVING_ROOM_FAN_ENTITY_ID,
STATE_ON,
{
ATTR_SUPPORTED_FEATURES: FULL_SUPPORT_FEATURES,
ATTR_OSCILLATING: True,
ATTR_DIRECTION: DIRECTION_FORWARD,
ATTR_PERCENTAGE: 50,
},
)
hass.states.async_set(
PERCENTAGE_FULL_FAN_ENTITY_ID,
STATE_ON,
{
ATTR_SUPPORTED_FEATURES: FULL_SUPPORT_FEATURES,
ATTR_OSCILLATING: True,
ATTR_DIRECTION: DIRECTION_FORWARD,
ATTR_PERCENTAGE: 50,
},
)
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_ON
assert state.attributes[ATTR_FRIENDLY_NAME] == DEFAULT_NAME
assert state.attributes[ATTR_ENTITY_ID] == [*FULL_FAN_ENTITY_IDS]
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == FULL_SUPPORT_FEATURES
assert ATTR_PERCENTAGE in state.attributes
assert state.attributes[ATTR_PERCENTAGE] == 50
assert state.attributes[ATTR_OSCILLATING] is True
assert state.attributes[ATTR_DIRECTION] == DIRECTION_FORWARD
assert ATTR_ASSUMED_STATE not in state.attributes
# Add Entity with a different direction should not set assumed state
hass.states.async_set(
PERCENTAGE_FULL_FAN_ENTITY_ID,
STATE_ON,
{
ATTR_SUPPORTED_FEATURES: FULL_SUPPORT_FEATURES,
ATTR_OSCILLATING: True,
ATTR_DIRECTION: DIRECTION_REVERSE,
ATTR_PERCENTAGE: 50,
},
)
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_ON
assert ATTR_ASSUMED_STATE not in state.attributes
assert ATTR_PERCENTAGE in state.attributes
assert state.attributes[ATTR_PERCENTAGE] == 50
assert state.attributes[ATTR_OSCILLATING] is True
# Now that everything is the same, no longer assumed state
hass.states.async_set(
LIVING_ROOM_FAN_ENTITY_ID,
STATE_ON,
{
ATTR_SUPPORTED_FEATURES: FULL_SUPPORT_FEATURES,
ATTR_OSCILLATING: True,
ATTR_DIRECTION: DIRECTION_REVERSE,
ATTR_PERCENTAGE: 50,
},
)
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_ON
assert ATTR_PERCENTAGE in state.attributes
assert state.attributes[ATTR_PERCENTAGE] == 50
assert state.attributes[ATTR_OSCILLATING] is True
assert state.attributes[ATTR_DIRECTION] == DIRECTION_REVERSE
assert ATTR_ASSUMED_STATE not in state.attributes
hass.states.async_set(
LIVING_ROOM_FAN_ENTITY_ID,
STATE_ON,
{
ATTR_SUPPORTED_FEATURES: FULL_SUPPORT_FEATURES,
ATTR_OSCILLATING: False,
ATTR_DIRECTION: DIRECTION_FORWARD,
ATTR_PERCENTAGE: 50,
},
)
hass.states.async_set(
PERCENTAGE_FULL_FAN_ENTITY_ID,
STATE_ON,
{
ATTR_SUPPORTED_FEATURES: FULL_SUPPORT_FEATURES,
ATTR_OSCILLATING: False,
ATTR_DIRECTION: DIRECTION_FORWARD,
ATTR_PERCENTAGE: 50,
},
)
await hass.async_block_till_done()
state = hass.states.get(FAN_GROUP)
assert state.state == STATE_ON
assert ATTR_PERCENTAGE in state.attributes
assert state.attributes[ATTR_PERCENTAGE] == 50
assert state.attributes[ATTR_OSCILLATING] is False
assert state.attributes[ATTR_DIRECTION] == DIRECTION_FORWARD
assert ATTR_ASSUMED_STATE not in state.attributes
@pytest.mark.parametrize("config_count", [(CONFIG_MISSING_FAN, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_state_missing_entity_id(hass: HomeAssistant) -> None:
"""Test we can still setup with a missing entity id."""
state = hass.states.get(FAN_GROUP)
await hass.async_block_till_done()
assert state.state == STATE_OFF
async def test_setup_before_started(hass: HomeAssistant) -> None:
"""Test we can setup before starting."""
hass.set_state(CoreState.stopped)
assert await async_setup_component(hass, FAN_DOMAIN, CONFIG_MISSING_FAN)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.get(FAN_GROUP).state == STATE_OFF
@pytest.mark.parametrize("config_count", [(CONFIG_MISSING_FAN, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_reload(hass: HomeAssistant) -> None:
"""Test the ability to reload fans."""
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.get(FAN_GROUP).state == STATE_OFF
yaml_path = get_fixture_path("fan_configuration.yaml", "group")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
"group",
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get(FAN_GROUP) is None
assert hass.states.get("fan.upstairs_fans") is not None
@pytest.mark.parametrize("config_count", [(CONFIG_FULL_SUPPORT, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_service_calls(hass: HomeAssistant) -> None:
"""Test calling services."""
await hass.services.async_call(
FAN_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: FAN_GROUP}, blocking=True
)
assert hass.states.get(LIVING_ROOM_FAN_ENTITY_ID).state == STATE_ON
assert hass.states.get(PERCENTAGE_FULL_FAN_ENTITY_ID).state == STATE_ON
assert hass.states.get(FAN_GROUP).state == STATE_ON
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: FAN_GROUP, ATTR_PERCENTAGE: 66},
blocking=True,
)
living_room_fan_state = hass.states.get(LIVING_ROOM_FAN_ENTITY_ID)
assert living_room_fan_state.attributes[ATTR_PERCENTAGE] == 66
percentage_full_fan_state = hass.states.get(PERCENTAGE_FULL_FAN_ENTITY_ID)
assert percentage_full_fan_state.attributes[ATTR_PERCENTAGE] == 66
fan_group_state = hass.states.get(FAN_GROUP)
assert fan_group_state.attributes[ATTR_PERCENTAGE] == 66
assert fan_group_state.attributes[ATTR_PERCENTAGE_STEP] == 100 / 3
await hass.services.async_call(
FAN_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: FAN_GROUP}, blocking=True
)
assert hass.states.get(LIVING_ROOM_FAN_ENTITY_ID).state == STATE_OFF
assert hass.states.get(PERCENTAGE_FULL_FAN_ENTITY_ID).state == STATE_OFF
assert hass.states.get(FAN_GROUP).state == STATE_OFF
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_PERCENTAGE,
{ATTR_ENTITY_ID: FAN_GROUP, ATTR_PERCENTAGE: 100},
blocking=True,
)
living_room_fan_state = hass.states.get(LIVING_ROOM_FAN_ENTITY_ID)
assert living_room_fan_state.attributes[ATTR_PERCENTAGE] == 100
percentage_full_fan_state = hass.states.get(PERCENTAGE_FULL_FAN_ENTITY_ID)
assert percentage_full_fan_state.attributes[ATTR_PERCENTAGE] == 100
fan_group_state = hass.states.get(FAN_GROUP)
assert fan_group_state.attributes[ATTR_PERCENTAGE] == 100
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: FAN_GROUP, ATTR_PERCENTAGE: 0},
blocking=True,
)
assert hass.states.get(LIVING_ROOM_FAN_ENTITY_ID).state == STATE_OFF
assert hass.states.get(PERCENTAGE_FULL_FAN_ENTITY_ID).state == STATE_OFF
assert hass.states.get(FAN_GROUP).state == STATE_OFF
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_OSCILLATE,
{ATTR_ENTITY_ID: FAN_GROUP, ATTR_OSCILLATING: True},
blocking=True,
)
living_room_fan_state = hass.states.get(LIVING_ROOM_FAN_ENTITY_ID)
assert living_room_fan_state.attributes[ATTR_OSCILLATING] is True
percentage_full_fan_state = hass.states.get(PERCENTAGE_FULL_FAN_ENTITY_ID)
assert percentage_full_fan_state.attributes[ATTR_OSCILLATING] is True
fan_group_state = hass.states.get(FAN_GROUP)
assert fan_group_state.attributes[ATTR_OSCILLATING] is True
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_OSCILLATE,
{ATTR_ENTITY_ID: FAN_GROUP, ATTR_OSCILLATING: False},
blocking=True,
)
living_room_fan_state = hass.states.get(LIVING_ROOM_FAN_ENTITY_ID)
assert living_room_fan_state.attributes[ATTR_OSCILLATING] is False
percentage_full_fan_state = hass.states.get(PERCENTAGE_FULL_FAN_ENTITY_ID)
assert percentage_full_fan_state.attributes[ATTR_OSCILLATING] is False
fan_group_state = hass.states.get(FAN_GROUP)
assert fan_group_state.attributes[ATTR_OSCILLATING] is False
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_DIRECTION,
{ATTR_ENTITY_ID: FAN_GROUP, ATTR_DIRECTION: DIRECTION_FORWARD},
blocking=True,
)
living_room_fan_state = hass.states.get(LIVING_ROOM_FAN_ENTITY_ID)
assert living_room_fan_state.attributes[ATTR_DIRECTION] == DIRECTION_FORWARD
percentage_full_fan_state = hass.states.get(PERCENTAGE_FULL_FAN_ENTITY_ID)
assert percentage_full_fan_state.attributes[ATTR_DIRECTION] == DIRECTION_FORWARD
fan_group_state = hass.states.get(FAN_GROUP)
assert fan_group_state.attributes[ATTR_DIRECTION] == DIRECTION_FORWARD
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_DIRECTION,
{ATTR_ENTITY_ID: FAN_GROUP, ATTR_DIRECTION: DIRECTION_REVERSE},
blocking=True,
)
living_room_fan_state = hass.states.get(LIVING_ROOM_FAN_ENTITY_ID)
assert living_room_fan_state.attributes[ATTR_DIRECTION] == DIRECTION_REVERSE
percentage_full_fan_state = hass.states.get(PERCENTAGE_FULL_FAN_ENTITY_ID)
assert percentage_full_fan_state.attributes[ATTR_DIRECTION] == DIRECTION_REVERSE
fan_group_state = hass.states.get(FAN_GROUP)
assert fan_group_state.attributes[ATTR_DIRECTION] == DIRECTION_REVERSE
async def test_nested_group(hass: HomeAssistant) -> None:
"""Test nested fan group."""
await async_setup_component(
hass,
FAN_DOMAIN,
{
FAN_DOMAIN: [
{"platform": "demo"},
{
"platform": "group",
"entities": ["fan.bedroom_group"],
"name": "Nested Group",
},
{
"platform": "group",
CONF_ENTITIES: [
LIVING_ROOM_FAN_ENTITY_ID,
PERCENTAGE_FULL_FAN_ENTITY_ID,
],
"name": "Bedroom Group",
},
]
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("fan.bedroom_group")
assert state is not None
assert state.state == STATE_OFF
assert state.attributes.get(ATTR_ENTITY_ID) == [
LIVING_ROOM_FAN_ENTITY_ID,
PERCENTAGE_FULL_FAN_ENTITY_ID,
]
state = hass.states.get("fan.nested_group")
assert state is not None
assert state.state == STATE_OFF
assert state.attributes.get(ATTR_ENTITY_ID) == ["fan.bedroom_group"]
# Test controlling the nested group
async with asyncio.timeout(0.5):
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "fan.nested_group"},
blocking=True,
)
assert hass.states.get(LIVING_ROOM_FAN_ENTITY_ID).state == STATE_ON
assert hass.states.get(PERCENTAGE_FULL_FAN_ENTITY_ID).state == STATE_ON
assert hass.states.get("fan.bedroom_group").state == STATE_ON
assert hass.states.get("fan.nested_group").state == STATE_ON

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,441 @@
"""The tests for the Group Lock platform."""
from unittest.mock import patch
import pytest
from homeassistant import config as hass_config
from homeassistant.components.demo import lock as demo_lock
from homeassistant.components.group import DOMAIN, SERVICE_RELOAD
from homeassistant.components.lock import (
DOMAIN as LOCK_DOMAIN,
SERVICE_LOCK,
SERVICE_OPEN,
SERVICE_UNLOCK,
LockState,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import get_fixture_path
async def test_default_state(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test lock group default state."""
hass.states.async_set("lock.front", "locked")
await async_setup_component(
hass,
LOCK_DOMAIN,
{
LOCK_DOMAIN: {
"platform": DOMAIN,
"entities": ["lock.front", "lock.back"],
"name": "Door Group",
"unique_id": "unique_identifier",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("lock.door_group")
assert state is not None
assert state.state == LockState.LOCKED
assert state.attributes.get(ATTR_ENTITY_ID) == ["lock.front", "lock.back"]
entry = entity_registry.async_get("lock.door_group")
assert entry
assert entry.unique_id == "unique_identifier"
async def test_state_reporting(hass: HomeAssistant) -> None:
"""Test the state reporting.
The group state is unavailable if all group members are unavailable.
Otherwise, the group state is unknown if at least one group member is unknown or unavailable.
Otherwise, the group state is jammed if at least one group member is jammed.
Otherwise, the group state is locking if at least one group member is locking.
Otherwise, the group state is unlocking if at least one group member is unlocking.
Otherwise, the group state is unlocked if at least one group member is unlocked.
Otherwise, the group state is locked.
"""
await async_setup_component(
hass,
LOCK_DOMAIN,
{
LOCK_DOMAIN: {
"platform": DOMAIN,
"entities": ["lock.test1", "lock.test2"],
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
# Initial state with no group member in the state machine -> unavailable
assert hass.states.get("lock.lock_group").state == STATE_UNAVAILABLE
# All group members unavailable -> unavailable
hass.states.async_set("lock.test1", STATE_UNAVAILABLE)
hass.states.async_set("lock.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group").state == STATE_UNAVAILABLE
# The group state is unknown if all group members are unknown or unavailable.
for state_1 in (
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
hass.states.async_set("lock.test1", state_1)
hass.states.async_set("lock.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group").state == STATE_UNKNOWN
# At least one member jammed -> group jammed
for state_1 in (
LockState.JAMMED,
LockState.LOCKED,
LockState.LOCKING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
LockState.UNLOCKED,
LockState.UNLOCKING,
):
hass.states.async_set("lock.test1", state_1)
hass.states.async_set("lock.test2", LockState.JAMMED)
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group").state == LockState.JAMMED
# At least one member locking -> group unlocking
for state_1 in (
LockState.LOCKED,
LockState.LOCKING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
LockState.UNLOCKED,
LockState.UNLOCKING,
):
hass.states.async_set("lock.test1", state_1)
hass.states.async_set("lock.test2", LockState.LOCKING)
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group").state == LockState.LOCKING
# At least one member unlocking -> group unlocking
for state_1 in (
LockState.LOCKED,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
LockState.UNLOCKED,
LockState.UNLOCKING,
):
hass.states.async_set("lock.test1", state_1)
hass.states.async_set("lock.test2", LockState.UNLOCKING)
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group").state == LockState.UNLOCKING
# At least one member unlocked -> group unlocked
for state_1 in (
LockState.LOCKED,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
LockState.UNLOCKED,
):
hass.states.async_set("lock.test1", state_1)
hass.states.async_set("lock.test2", LockState.UNLOCKED)
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group").state == LockState.UNLOCKED
# Otherwise -> locked
hass.states.async_set("lock.test1", LockState.LOCKED)
hass.states.async_set("lock.test2", LockState.LOCKED)
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group").state == LockState.LOCKED
# All group members removed from the state machine -> unavailable
hass.states.async_remove("lock.test1")
hass.states.async_remove("lock.test2")
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group").state == STATE_UNAVAILABLE
async def test_service_calls_openable(hass: HomeAssistant) -> None:
"""Test service calls with open support."""
await async_setup_component(
hass,
LOCK_DOMAIN,
{
LOCK_DOMAIN: [
{"platform": "kitchen_sink"},
{
"platform": DOMAIN,
"entities": [
"lock.openable_lock",
"lock.another_openable_lock",
],
},
]
},
)
await hass.async_block_till_done()
group_state = hass.states.get("lock.lock_group")
assert group_state.state == LockState.UNLOCKED
assert hass.states.get("lock.openable_lock").state == LockState.LOCKED
assert hass.states.get("lock.another_openable_lock").state == LockState.UNLOCKED
await hass.services.async_call(
LOCK_DOMAIN,
SERVICE_OPEN,
{ATTR_ENTITY_ID: "lock.lock_group"},
blocking=True,
)
assert hass.states.get("lock.openable_lock").state == LockState.OPEN
assert hass.states.get("lock.another_openable_lock").state == LockState.OPEN
await hass.services.async_call(
LOCK_DOMAIN,
SERVICE_LOCK,
{ATTR_ENTITY_ID: "lock.lock_group"},
blocking=True,
)
assert hass.states.get("lock.openable_lock").state == LockState.LOCKED
assert hass.states.get("lock.another_openable_lock").state == LockState.LOCKED
await hass.services.async_call(
LOCK_DOMAIN,
SERVICE_UNLOCK,
{ATTR_ENTITY_ID: "lock.lock_group"},
blocking=True,
)
assert hass.states.get("lock.openable_lock").state == LockState.UNLOCKED
assert hass.states.get("lock.another_openable_lock").state == LockState.UNLOCKED
async def test_service_calls_basic(hass: HomeAssistant) -> None:
"""Test service calls without open support."""
await async_setup_component(
hass,
LOCK_DOMAIN,
{
LOCK_DOMAIN: [
{"platform": "kitchen_sink"},
{
"platform": DOMAIN,
"entities": [
"lock.basic_lock",
"lock.another_basic_lock",
],
},
]
},
)
await hass.async_block_till_done()
group_state = hass.states.get("lock.lock_group")
assert group_state.state == LockState.UNLOCKED
assert hass.states.get("lock.basic_lock").state == LockState.LOCKED
assert hass.states.get("lock.another_basic_lock").state == LockState.UNLOCKED
await hass.services.async_call(
LOCK_DOMAIN,
SERVICE_LOCK,
{ATTR_ENTITY_ID: "lock.lock_group"},
blocking=True,
)
assert hass.states.get("lock.basic_lock").state == LockState.LOCKED
assert hass.states.get("lock.another_basic_lock").state == LockState.LOCKED
await hass.services.async_call(
LOCK_DOMAIN,
SERVICE_UNLOCK,
{ATTR_ENTITY_ID: "lock.lock_group"},
blocking=True,
)
assert hass.states.get("lock.basic_lock").state == LockState.UNLOCKED
assert hass.states.get("lock.another_basic_lock").state == LockState.UNLOCKED
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
LOCK_DOMAIN,
SERVICE_OPEN,
{ATTR_ENTITY_ID: "lock.lock_group"},
blocking=True,
)
async def test_reload(hass: HomeAssistant) -> None:
"""Test the ability to reload locks."""
await async_setup_component(
hass,
LOCK_DOMAIN,
{
LOCK_DOMAIN: [
{"platform": "demo"},
{
"platform": DOMAIN,
"entities": [
"lock.front_door",
"lock.kitchen_door",
],
},
]
},
)
await hass.async_block_till_done()
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group").state == LockState.UNLOCKED
yaml_path = get_fixture_path("configuration.yaml", "group")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group") is None
assert hass.states.get("lock.inside_locks_g") is not None
assert hass.states.get("lock.outside_locks_g") is not None
async def test_reload_with_platform_not_setup(hass: HomeAssistant) -> None:
"""Test the ability to reload locks."""
hass.states.async_set("lock.something", LockState.UNLOCKED)
await async_setup_component(
hass,
LOCK_DOMAIN,
{
LOCK_DOMAIN: [
{"platform": "demo"},
]
},
)
assert await async_setup_component(
hass,
"group",
{
"group": {
"group_zero": {"entities": "lock.something", "icon": "mdi:work"},
}
},
)
await hass.async_block_till_done()
yaml_path = get_fixture_path("configuration.yaml", "group")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group") is None
assert hass.states.get("lock.inside_locks_g") is not None
assert hass.states.get("lock.outside_locks_g") is not None
async def test_reload_with_base_integration_platform_not_setup(
hass: HomeAssistant,
) -> None:
"""Test the ability to reload locks."""
assert await async_setup_component(
hass,
"group",
{
"group": {
"group_zero": {"entities": "lock.something", "icon": "mdi:work"},
}
},
)
await hass.async_block_till_done()
hass.states.async_set("lock.front_lock", LockState.LOCKED)
hass.states.async_set("lock.back_lock", LockState.UNLOCKED)
hass.states.async_set("lock.outside_lock", LockState.LOCKED)
hass.states.async_set("lock.outside_lock_2", LockState.LOCKED)
yaml_path = get_fixture_path("configuration.yaml", "group")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("lock.lock_group") is None
assert hass.states.get("lock.inside_locks_g") is not None
assert hass.states.get("lock.outside_locks_g") is not None
assert hass.states.get("lock.inside_locks_g").state == LockState.UNLOCKED
assert hass.states.get("lock.outside_locks_g").state == LockState.LOCKED
@patch.object(demo_lock, "LOCK_UNLOCK_DELAY", 0)
async def test_nested_group(hass: HomeAssistant) -> None:
"""Test nested lock group."""
await async_setup_component(
hass,
LOCK_DOMAIN,
{
LOCK_DOMAIN: [
{"platform": "demo"},
{
"platform": DOMAIN,
"entities": ["lock.some_group"],
"name": "Nested Group",
},
{
"platform": DOMAIN,
"entities": [
"lock.front_door",
"lock.kitchen_door",
],
"name": "Some Group",
},
]
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("lock.some_group")
assert state is not None
assert state.state == LockState.UNLOCKED
assert state.attributes.get(ATTR_ENTITY_ID) == [
"lock.front_door",
"lock.kitchen_door",
]
state = hass.states.get("lock.nested_group")
assert state is not None
assert state.state == LockState.UNLOCKED
assert state.attributes.get(ATTR_ENTITY_ID) == ["lock.some_group"]
# Test controlling the nested group
await hass.services.async_call(
LOCK_DOMAIN,
SERVICE_LOCK,
{ATTR_ENTITY_ID: "lock.nested_group"},
blocking=True,
)
assert hass.states.get("lock.front_door").state == LockState.LOCKED
assert hass.states.get("lock.kitchen_door").state == LockState.LOCKED
assert hass.states.get("lock.some_group").state == LockState.LOCKED
assert hass.states.get("lock.nested_group").state == LockState.LOCKED

View File

@@ -0,0 +1,658 @@
"""The tests for the Media group platform."""
import asyncio
from unittest.mock import MagicMock, Mock, patch
import pytest
from homeassistant.components.group import DOMAIN
from homeassistant.components.media_player import (
ATTR_MEDIA_ANNOUNCE,
ATTR_MEDIA_CONTENT_ID,
ATTR_MEDIA_CONTENT_TYPE,
ATTR_MEDIA_EXTRA,
ATTR_MEDIA_SEEK_POSITION,
ATTR_MEDIA_SHUFFLE,
ATTR_MEDIA_TRACK,
ATTR_MEDIA_VOLUME_LEVEL,
ATTR_MEDIA_VOLUME_MUTED,
DOMAIN as MEDIA_DOMAIN,
SERVICE_CLEAR_PLAYLIST,
SERVICE_MEDIA_PAUSE,
SERVICE_MEDIA_SEEK,
SERVICE_PLAY_MEDIA,
SERVICE_SHUFFLE_SET,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
SERVICE_VOLUME_SET,
MediaPlayerEntityFeature,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_SUPPORTED_FEATURES,
SERVICE_MEDIA_NEXT_TRACK,
SERVICE_MEDIA_PLAY,
SERVICE_MEDIA_PREVIOUS_TRACK,
SERVICE_MEDIA_STOP,
SERVICE_VOLUME_DOWN,
SERVICE_VOLUME_MUTE,
SERVICE_VOLUME_UP,
STATE_BUFFERING,
STATE_IDLE,
STATE_OFF,
STATE_ON,
STATE_PAUSED,
STATE_PLAYING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_platform, entity_registry as er
from homeassistant.setup import async_setup_component
@pytest.fixture(name="mock_media_seek")
def media_player_media_seek_fixture():
"""Mock demo YouTube player media seek."""
with patch(
"homeassistant.components.demo.media_player.DemoYoutubePlayer.media_seek",
autospec=True,
) as seek:
yield seek
async def test_default_state(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test media group default state."""
hass.states.async_set("media_player.player_1", "on")
await async_setup_component(
hass,
MEDIA_DOMAIN,
{
MEDIA_DOMAIN: {
"platform": DOMAIN,
"entities": ["media_player.player_1", "media_player.player_2"],
"name": "Media group",
"unique_id": "unique_identifier",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("media_player.media_group")
assert state is not None
assert state.state == STATE_ON
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
assert state.attributes.get(ATTR_ENTITY_ID) == [
"media_player.player_1",
"media_player.player_2",
]
entry = entity_registry.async_get("media_player.media_group")
assert entry
assert entry.unique_id == "unique_identifier"
async def test_state_reporting(hass: HomeAssistant) -> None:
"""Test the state reporting.
The group state is unavailable if all group members are unavailable.
Otherwise, the group state is unknown if all group members are unknown.
Otherwise, the group state is buffering if all group members are buffering.
Otherwise, the group state is idle if all group members are idle.
Otherwise, the group state is paused if all group members are paused.
Otherwise, the group state is playing if all group members are playing.
Otherwise, the group state is on if at least one group member is not off, unavailable or unknown.
Otherwise, the group state is off.
"""
await async_setup_component(
hass,
MEDIA_DOMAIN,
{
MEDIA_DOMAIN: {
"platform": DOMAIN,
"entities": ["media_player.player_1", "media_player.player_2"],
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
# Initial state with no group member in the state machine -> unavailable
assert hass.states.get("media_player.media_group").state == STATE_UNAVAILABLE
# All group members unavailable -> unavailable
hass.states.async_set("media_player.player_1", STATE_UNAVAILABLE)
hass.states.async_set("media_player.player_2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("media_player.media_group").state == STATE_UNAVAILABLE
# The group state is unknown if all group members are unknown or unavailable.
for state_1 in (
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
hass.states.async_set("media_player.player_1", state_1)
hass.states.async_set("media_player.player_2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("media_player.media_group").state == STATE_UNKNOWN
# All group members buffering -> buffering
# All group members idle -> idle
# All group members paused -> paused
# All group members playing -> playing
# All group members unavailable -> unavailable
# All group members unknown -> unknown
for state in (
STATE_BUFFERING,
STATE_IDLE,
STATE_PAUSED,
STATE_PLAYING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
hass.states.async_set("media_player.player_1", state)
hass.states.async_set("media_player.player_2", state)
await hass.async_block_till_done()
assert hass.states.get("media_player.media_group").state == state
# At least one member not off, unavailable or unknown -> on
for state_1 in (STATE_BUFFERING, STATE_IDLE, STATE_ON, STATE_PAUSED, STATE_PLAYING):
for state_2 in (STATE_OFF, STATE_UNAVAILABLE, STATE_UNKNOWN):
hass.states.async_set("media_player.player_1", state_1)
hass.states.async_set("media_player.player_2", state_2)
await hass.async_block_till_done()
assert hass.states.get("media_player.media_group").state == STATE_ON
# Otherwise off
for state_1 in (STATE_OFF, STATE_UNAVAILABLE, STATE_UNKNOWN):
hass.states.async_set("media_player.player_1", state_1)
hass.states.async_set("media_player.player_2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("media_player.media_group").state == STATE_OFF
# All group members in same invalid state -> unknown
hass.states.async_set("media_player.player_1", "invalid_state")
hass.states.async_set("media_player.player_2", "invalid_state")
await hass.async_block_till_done()
assert hass.states.get("media_player.media_group").state == STATE_UNKNOWN
# All group members removed from the state machine -> unavailable
hass.states.async_remove("media_player.player_1")
hass.states.async_remove("media_player.player_2")
await hass.async_block_till_done()
assert hass.states.get("media_player.media_group").state == STATE_UNAVAILABLE
async def test_supported_features(hass: HomeAssistant) -> None:
"""Test supported features reporting."""
pause_play_stop = (
MediaPlayerEntityFeature.PAUSE
| MediaPlayerEntityFeature.PLAY
| MediaPlayerEntityFeature.STOP
)
play_media = (
MediaPlayerEntityFeature.PLAY_MEDIA
| MediaPlayerEntityFeature.MEDIA_ANNOUNCE
| MediaPlayerEntityFeature.MEDIA_ENQUEUE
)
volume = (
MediaPlayerEntityFeature.VOLUME_MUTE
| MediaPlayerEntityFeature.VOLUME_SET
| MediaPlayerEntityFeature.VOLUME_STEP
)
await async_setup_component(
hass,
MEDIA_DOMAIN,
{
MEDIA_DOMAIN: {
"platform": DOMAIN,
"entities": ["media_player.player_1", "media_player.player_2"],
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set(
"media_player.player_1", STATE_ON, {ATTR_SUPPORTED_FEATURES: 0}
)
await hass.async_block_till_done()
state = hass.states.get("media_player.media_group")
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
hass.states.async_set(
"media_player.player_1",
STATE_ON,
{ATTR_SUPPORTED_FEATURES: pause_play_stop},
)
await hass.async_block_till_done()
state = hass.states.get("media_player.media_group")
assert state.attributes[ATTR_SUPPORTED_FEATURES] == pause_play_stop
hass.states.async_set(
"media_player.player_2",
STATE_OFF,
{ATTR_SUPPORTED_FEATURES: play_media | volume},
)
await hass.async_block_till_done()
state = hass.states.get("media_player.media_group")
assert (
state.attributes[ATTR_SUPPORTED_FEATURES]
== pause_play_stop | play_media | volume
)
hass.states.async_set(
"media_player.player_2", STATE_OFF, {ATTR_SUPPORTED_FEATURES: play_media}
)
await hass.async_block_till_done()
state = hass.states.get("media_player.media_group")
assert state.attributes[ATTR_SUPPORTED_FEATURES] == pause_play_stop | play_media
async def test_service_calls(hass: HomeAssistant, mock_media_seek: Mock) -> None:
"""Test service calls."""
await async_setup_component(
hass,
MEDIA_DOMAIN,
{
MEDIA_DOMAIN: [
{"platform": "demo"},
{
"platform": DOMAIN,
"entities": [
"media_player.bedroom",
"media_player.kitchen",
"media_player.living_room",
],
},
]
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.get("media_player.media_group").state == STATE_PLAYING
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "media_player.media_group"},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("media_player.bedroom").state == STATE_OFF
assert hass.states.get("media_player.kitchen").state == STATE_OFF
assert hass.states.get("media_player.living_room").state == STATE_OFF
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "media_player.media_group"},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("media_player.bedroom").state == STATE_PLAYING
assert hass.states.get("media_player.kitchen").state == STATE_PLAYING
assert hass.states.get("media_player.living_room").state == STATE_PLAYING
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_MEDIA_PAUSE,
{ATTR_ENTITY_ID: "media_player.media_group"},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("media_player.bedroom").state == STATE_PAUSED
assert hass.states.get("media_player.kitchen").state == STATE_PAUSED
assert hass.states.get("media_player.living_room").state == STATE_PAUSED
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_MEDIA_PLAY,
{ATTR_ENTITY_ID: "media_player.media_group"},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("media_player.bedroom").state == STATE_PLAYING
assert hass.states.get("media_player.kitchen").state == STATE_PLAYING
assert hass.states.get("media_player.living_room").state == STATE_PLAYING
# ATTR_MEDIA_TRACK is not supported by bedroom and living_room players
assert hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_TRACK] == 1
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_MEDIA_NEXT_TRACK,
{ATTR_ENTITY_ID: "media_player.media_group"},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_TRACK] == 2
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_MEDIA_PREVIOUS_TRACK,
{ATTR_ENTITY_ID: "media_player.media_group"},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_TRACK] == 1
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: "media_player.media_group",
ATTR_MEDIA_CONTENT_TYPE: "some_type",
ATTR_MEDIA_CONTENT_ID: "some_id",
},
)
await hass.async_block_till_done()
assert (
hass.states.get("media_player.bedroom").attributes[ATTR_MEDIA_CONTENT_ID]
== "some_id"
)
# media_player.kitchen is skipped because it always returns "bounzz-1"
assert (
hass.states.get("media_player.living_room").attributes[ATTR_MEDIA_CONTENT_ID]
== "some_id"
)
state = hass.states.get("media_player.media_group")
assert state.attributes[ATTR_SUPPORTED_FEATURES] & MediaPlayerEntityFeature.SEEK
assert not mock_media_seek.called
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_MEDIA_SEEK,
{
ATTR_ENTITY_ID: "media_player.media_group",
ATTR_MEDIA_SEEK_POSITION: 100,
},
)
await hass.async_block_till_done()
assert mock_media_seek.called
assert (
hass.states.get("media_player.bedroom").attributes[ATTR_MEDIA_VOLUME_LEVEL] == 1
)
assert (
hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_VOLUME_LEVEL] == 1
)
assert (
hass.states.get("media_player.living_room").attributes[ATTR_MEDIA_VOLUME_LEVEL]
== 1
)
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_VOLUME_SET,
{
ATTR_ENTITY_ID: "media_player.media_group",
ATTR_MEDIA_VOLUME_LEVEL: 0.5,
},
blocking=True,
)
await hass.async_block_till_done()
assert (
hass.states.get("media_player.bedroom").attributes[ATTR_MEDIA_VOLUME_LEVEL]
== 0.5
)
assert (
hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_VOLUME_LEVEL]
== 0.5
)
assert (
hass.states.get("media_player.living_room").attributes[ATTR_MEDIA_VOLUME_LEVEL]
== 0.5
)
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_VOLUME_UP,
{ATTR_ENTITY_ID: "media_player.media_group"},
blocking=True,
)
await hass.async_block_till_done()
assert (
hass.states.get("media_player.bedroom").attributes[ATTR_MEDIA_VOLUME_LEVEL]
== 0.6
)
assert (
hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_VOLUME_LEVEL]
== 0.6
)
assert (
hass.states.get("media_player.living_room").attributes[ATTR_MEDIA_VOLUME_LEVEL]
== 0.6
)
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_VOLUME_DOWN,
{ATTR_ENTITY_ID: "media_player.media_group"},
blocking=True,
)
await hass.async_block_till_done()
assert (
hass.states.get("media_player.bedroom").attributes[ATTR_MEDIA_VOLUME_LEVEL]
== 0.5
)
assert (
hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_VOLUME_LEVEL]
== 0.5
)
assert (
hass.states.get("media_player.living_room").attributes[ATTR_MEDIA_VOLUME_LEVEL]
== 0.5
)
assert (
hass.states.get("media_player.bedroom").attributes[ATTR_MEDIA_VOLUME_MUTED]
is False
)
assert (
hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_VOLUME_MUTED]
is False
)
assert (
hass.states.get("media_player.living_room").attributes[ATTR_MEDIA_VOLUME_MUTED]
is False
)
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_VOLUME_MUTE,
{ATTR_ENTITY_ID: "media_player.media_group", ATTR_MEDIA_VOLUME_MUTED: True},
blocking=True,
)
await hass.async_block_till_done()
assert (
hass.states.get("media_player.bedroom").attributes[ATTR_MEDIA_VOLUME_MUTED]
is True
)
assert (
hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_VOLUME_MUTED]
is True
)
assert (
hass.states.get("media_player.living_room").attributes[ATTR_MEDIA_VOLUME_MUTED]
is True
)
assert (
hass.states.get("media_player.bedroom").attributes[ATTR_MEDIA_SHUFFLE] is False
)
assert (
hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_SHUFFLE] is False
)
assert (
hass.states.get("media_player.living_room").attributes[ATTR_MEDIA_SHUFFLE]
is False
)
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_SHUFFLE_SET,
{ATTR_ENTITY_ID: "media_player.media_group", ATTR_MEDIA_SHUFFLE: True},
blocking=True,
)
await hass.async_block_till_done()
assert (
hass.states.get("media_player.bedroom").attributes[ATTR_MEDIA_SHUFFLE] is True
)
assert (
hass.states.get("media_player.kitchen").attributes[ATTR_MEDIA_SHUFFLE] is True
)
assert (
hass.states.get("media_player.living_room").attributes[ATTR_MEDIA_SHUFFLE]
is True
)
assert hass.states.get("media_player.bedroom").state == STATE_PLAYING
assert hass.states.get("media_player.kitchen").state == STATE_PLAYING
assert hass.states.get("media_player.living_room").state == STATE_PLAYING
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_CLEAR_PLAYLIST,
{ATTR_ENTITY_ID: "media_player.media_group"},
blocking=True,
)
await hass.async_block_till_done()
# SERVICE_CLEAR_PLAYLIST is not supported by bedroom and living_room players
assert hass.states.get("media_player.kitchen").state == STATE_OFF
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_MEDIA_PLAY,
{ATTR_ENTITY_ID: "media_player.kitchen"},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("media_player.bedroom").state == STATE_PLAYING
assert hass.states.get("media_player.kitchen").state == STATE_PLAYING
assert hass.states.get("media_player.living_room").state == STATE_PLAYING
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_MEDIA_STOP,
{ATTR_ENTITY_ID: "media_player.media_group"},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("media_player.bedroom").state == STATE_OFF
assert hass.states.get("media_player.kitchen").state == STATE_OFF
assert hass.states.get("media_player.living_room").state == STATE_OFF
async def test_nested_group(hass: HomeAssistant) -> None:
"""Test nested media group."""
await async_setup_component(
hass,
MEDIA_DOMAIN,
{
MEDIA_DOMAIN: [
{"platform": "demo"},
{
"platform": DOMAIN,
"entities": ["media_player.group_1"],
"name": "Nested Group",
},
{
"platform": DOMAIN,
"entities": ["media_player.bedroom", "media_player.kitchen"],
"name": "Group 1",
},
]
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("media_player.group_1")
assert state is not None
assert state.state == STATE_PLAYING
assert state.attributes.get(ATTR_ENTITY_ID) == [
"media_player.bedroom",
"media_player.kitchen",
]
state = hass.states.get("media_player.nested_group")
assert state is not None
assert state.state == STATE_PLAYING
assert state.attributes.get(ATTR_ENTITY_ID) == ["media_player.group_1"]
# Test controlling the nested group
async with asyncio.timeout(0.5):
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "media_player.group_1"},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("media_player.bedroom").state == STATE_OFF
assert hass.states.get("media_player.kitchen").state == STATE_OFF
assert hass.states.get("media_player.group_1").state == STATE_OFF
assert hass.states.get("media_player.nested_group").state == STATE_OFF
async def test_service_play_media_kwargs(hass: HomeAssistant) -> None:
"""Test that kwargs get passed through on play_media service call."""
await async_setup_component(
hass,
MEDIA_DOMAIN,
{
MEDIA_DOMAIN: [
{"platform": "demo"},
{
"platform": DOMAIN,
"entities": [
"media_player.bedroom",
"media_player.living_room",
],
},
]
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
platform = entity_platform.async_get_platforms(hass, "media_player")[0]
mp_bedroom = platform.domain_entities["media_player.bedroom"]
mp_bedroom.play_media = MagicMock()
mp_living_room = platform.domain_entities["media_player.living_room"]
mp_living_room.play_media = MagicMock()
await hass.services.async_call(
MEDIA_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: "media_player.media_group",
ATTR_MEDIA_CONTENT_TYPE: "some_type",
ATTR_MEDIA_CONTENT_ID: "some_id",
ATTR_MEDIA_ANNOUNCE: "true",
ATTR_MEDIA_EXTRA: {
"volume": 20,
},
},
)
await hass.async_block_till_done()
assert mp_bedroom.play_media.call_count == 1
mp_bedroom.play_media.assert_called_with(
"some_type", "some_id", announce=True, extra={"volume": 20}
)
assert mp_living_room.play_media.call_count == 1
mp_living_room.play_media.assert_called_with(
"some_type", "some_id", announce=True, extra={"volume": 20}
)

View File

@@ -0,0 +1,422 @@
"""The tests for the notify.group platform."""
from collections.abc import Generator, Mapping
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock, call, patch
import pytest
from homeassistant import config as hass_config
from homeassistant.components import notify
from homeassistant.components.group import DOMAIN, SERVICE_RELOAD
from homeassistant.components.notify import (
ATTR_MESSAGE,
ATTR_TITLE,
DOMAIN as NOTIFY_DOMAIN,
SERVICE_SEND_MESSAGE,
NotifyEntity,
)
from homeassistant.config_entries import ConfigEntry, ConfigFlow
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.setup import async_setup_component
from tests.common import (
MockConfigEntry,
MockEntity,
MockModule,
MockPlatform,
get_fixture_path,
mock_config_flow,
mock_integration,
mock_platform,
setup_test_component_platform,
)
class MockNotifyPlatform(MockPlatform):
"""Help to set up a legacy test notify platform."""
def __init__(self, async_get_service: Any) -> None:
"""Initialize platform."""
super().__init__()
self.async_get_service = async_get_service
def mock_notify_platform(
hass: HomeAssistant,
tmp_path: Path,
async_get_service: Any = None,
):
"""Specialize the mock platform for legacy notify service."""
loaded_platform = MockNotifyPlatform(async_get_service)
mock_platform(hass, "test.notify", loaded_platform)
return loaded_platform
async def help_setup_notify(
hass: HomeAssistant,
tmp_path: Path,
targets: dict[str, None] | None = None,
group_setup: list[dict[str, None]] | None = None,
) -> MagicMock:
"""Help set up a platform notify service."""
send_message_mock = MagicMock()
class _TestNotifyService(notify.BaseNotificationService):
def __init__(self, targets: dict[str, None] | None) -> None:
"""Initialize service."""
self._targets = targets
super().__init__()
@property
def targets(self) -> Mapping[str, Any] | None:
"""Return a dictionary of registered targets."""
return self._targets
def send_message(self, message: str, **kwargs: Any) -> None:
"""Send a message."""
send_message_mock(message, kwargs)
async def async_get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> notify.BaseNotificationService:
"""Get notify service for mocked platform."""
return _TestNotifyService(targets)
# Mock platform with service
mock_notify_platform(hass, tmp_path, async_get_service=async_get_service)
# Setup the platform
items: list[dict[str, Any]] = [{"platform": "test"}]
items.extend(group_setup or [])
await async_setup_component(hass, "notify", {"notify": items})
await hass.async_block_till_done()
# Return mock for assertion service calls
return send_message_mock
async def test_send_message_with_data(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test sending a message with to a notify group."""
assert await async_setup_component(
hass,
"group",
{},
)
await hass.async_block_till_done()
group_setup = [
{
"platform": "group",
"name": "My notification group",
"services": [
{"service": "test_service1"},
{
"action": "test_service2",
"data": {
"target": "unnamed device",
"data": {"test": "message", "default": "default"},
},
},
],
}
]
send_message_mock = await help_setup_notify(
hass, tmp_path, {"service1": 1, "service2": 2}, group_setup
)
assert hass.services.has_service("notify", "my_notification_group")
# Test sending a message to a notify group.
await hass.services.async_call(
"notify",
"my_notification_group",
{"message": "Hello", "title": "Test notification", "data": {"hello": "world"}},
blocking=True,
)
send_message_mock.assert_has_calls(
[
call(
"Hello",
{
"title": "Test notification",
"target": [1],
"data": {"hello": "world"},
},
),
call(
"Hello",
{
"title": "Test notification",
"target": [2],
"data": {"hello": "world", "test": "message", "default": "default"},
},
),
],
any_order=True,
)
send_message_mock.reset_mock()
# Test sending a message which overrides service defaults to a notify group
await hass.services.async_call(
"notify",
"my_notification_group",
{
"message": "Hello",
"title": "Test notification",
"data": {"hello": "world", "default": "override"},
},
blocking=True,
)
send_message_mock.assert_has_calls(
[
call(
"Hello",
{
"title": "Test notification",
"target": [1],
"data": {"hello": "world", "default": "override"},
},
),
call(
"Hello",
{
"title": "Test notification",
"target": [2],
"data": {
"hello": "world",
"test": "message",
"default": "override",
},
},
),
]
)
async def test_invalid_configuration(
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test failing to set up group with an invalid configuration."""
assert await async_setup_component(
hass,
"group",
{},
)
await hass.async_block_till_done()
group_setup = [
{
"platform": "group",
"name": "My invalid notification group",
"services": [
{
"service": "test_service1",
"action": "test_service2",
"data": {
"target": "unnamed device",
"data": {"test": "message", "default": "default"},
},
},
],
}
]
await help_setup_notify(hass, tmp_path, {"service1": 1, "service2": 2}, group_setup)
assert not hass.services.has_service("notify", "my_invalid_notification_group")
assert (
"Invalid config for 'notify' from integration 'group':"
" Cannot specify both 'service' and 'action'." in caplog.text
)
async def test_reload_notify(hass: HomeAssistant, tmp_path: Path) -> None:
"""Verify we can reload the notify service."""
assert await async_setup_component(
hass,
"group",
{},
)
await hass.async_block_till_done()
await help_setup_notify(
hass,
tmp_path,
{"service1": 1, "service2": 2},
[
{
"name": "group_notify",
"platform": "group",
"services": [{"action": "test_service1"}],
}
],
)
assert hass.services.has_service(notify.DOMAIN, "test_service1")
assert hass.services.has_service(notify.DOMAIN, "test_service2")
assert hass.services.has_service(notify.DOMAIN, "group_notify")
yaml_path = get_fixture_path("configuration.yaml", "group")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
"group",
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
assert hass.services.has_service(notify.DOMAIN, "test_service1")
assert hass.services.has_service(notify.DOMAIN, "test_service2")
assert not hass.services.has_service(notify.DOMAIN, "group_notify")
assert hass.services.has_service(notify.DOMAIN, "new_group_notify")
class MockFlow(ConfigFlow):
"""Test flow."""
@pytest.fixture
def config_flow_fixture(hass: HomeAssistant) -> Generator[None]:
"""Mock config flow."""
mock_platform(hass, "test.config_flow")
with mock_config_flow("test", MockFlow):
yield
class MockNotifyEntity(MockEntity, NotifyEntity):
"""Mock Email notifier entity to use in tests."""
def __init__(self, **values: Any) -> None:
"""Initialize the mock entity."""
super().__init__(**values)
self.send_message_mock_calls = MagicMock()
async def async_send_message(self, message: str, title: str | None = None) -> None:
"""Send a notification message."""
self.send_message_mock_calls(message, title=title)
async def help_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, [Platform.NOTIFY]
)
return True
async def help_async_unload_entry(
hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Unload test config entry."""
return await hass.config_entries.async_unload_platforms(
config_entry, [Platform.NOTIFY]
)
@pytest.fixture
async def mock_notifiers(
hass: HomeAssistant, config_flow_fixture: None
) -> list[NotifyEntity]:
"""Set up the notify entities."""
entity = MockNotifyEntity(name="test", entity_id="notify.test")
entity2 = MockNotifyEntity(name="test2", entity_id="notify.test2")
entities = [entity, entity2]
test_entry = MockConfigEntry(domain="test")
test_entry.add_to_hass(hass)
mock_integration(
hass,
MockModule(
"test",
async_setup_entry=help_async_setup_entry_init,
async_unload_entry=help_async_unload_entry,
),
)
setup_test_component_platform(hass, NOTIFY_DOMAIN, entities, from_config_entry=True)
assert await hass.config_entries.async_setup(test_entry.entry_id)
await hass.async_block_till_done()
return entities
async def test_notify_entity_group(
hass: HomeAssistant, mock_notifiers: list[NotifyEntity]
) -> None:
"""Test sending a message to a notify group."""
entity, entity2 = mock_notifiers
assert entity.send_message_mock_calls.call_count == 0
assert entity2.send_message_mock_calls.call_count == 0
config_entry = MockConfigEntry(
domain=DOMAIN,
options={
"group_type": "notify",
"name": "Test Group",
"entities": ["notify.test", "notify.test2"],
"hide_members": True,
},
title="Test Group",
)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
NOTIFY_DOMAIN,
SERVICE_SEND_MESSAGE,
{
ATTR_MESSAGE: "Hello",
ATTR_TITLE: "Test notification",
ATTR_ENTITY_ID: "notify.test_group",
},
blocking=True,
)
assert entity.send_message_mock_calls.call_count == 1
assert entity.send_message_mock_calls.call_args == call(
"Hello", title="Test notification"
)
assert entity2.send_message_mock_calls.call_count == 1
assert entity2.send_message_mock_calls.call_args == call(
"Hello", title="Test notification"
)
async def test_state_reporting(hass: HomeAssistant) -> None:
"""Test sending a message to a notify group."""
config_entry = MockConfigEntry(
domain=DOMAIN,
options={
"group_type": "notify",
"name": "Test Group",
"entities": ["notify.test", "notify.test2"],
"hide_members": True,
},
title="Test Group",
)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get("notify.test_group").state == STATE_UNAVAILABLE
hass.states.async_set("notify.test", STATE_UNAVAILABLE)
hass.states.async_set("notify.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("notify.test_group").state == STATE_UNAVAILABLE
hass.states.async_set("notify.test", "2021-01-01T23:59:59.123+00:00")
hass.states.async_set("notify.test2", "2021-01-01T23:59:59.123+00:00")
await hass.async_block_till_done()
assert hass.states.get("notify.test_group").state == STATE_UNKNOWN

View File

@@ -0,0 +1,59 @@
"""The tests for group recorder."""
from __future__ import annotations
from datetime import timedelta
import pytest
from homeassistant.components import group
from homeassistant.components.group import ATTR_AUTO, ATTR_ENTITY_ID, ATTR_ORDER
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.history import get_significant_states
from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_ON
from homeassistant.core import HomeAssistant, split_entity_id
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.common import async_fire_time_changed
from tests.components.recorder.common import async_wait_recording_done
@pytest.fixture(autouse=True)
async def setup_homeassistant():
"""Override the fixture in group.conftest."""
async def test_exclude_attributes(recorder_mock: Recorder, hass: HomeAssistant) -> None:
"""Test number registered attributes to be excluded."""
now = dt_util.utcnow()
hass.states.async_set("light.bowl", STATE_ON)
assert await async_setup_component(hass, "light", {})
assert await async_setup_component(
hass,
group.DOMAIN,
{
group.DOMAIN: {
"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()
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=5))
await hass.async_block_till_done()
await async_wait_recording_done(hass)
states = await hass.async_add_executor_job(
get_significant_states, hass, now, None, hass.states.async_entity_ids()
)
assert len(states) > 1
for entity_states in states.values():
for state in entity_states:
if split_entity_id(state.entity_id)[0] == group.DOMAIN:
assert ATTR_AUTO not in state.attributes
assert ATTR_ENTITY_ID not in state.attributes
assert ATTR_ORDER not in state.attributes
assert ATTR_FRIENDLY_NAME in state.attributes

View File

@@ -0,0 +1,54 @@
"""The tests for reproduction of state."""
from asyncio import Future
from unittest.mock import ANY, patch
from homeassistant.components.group.reproduce_state import async_reproduce_states
from homeassistant.core import Context, HomeAssistant, State
async def test_reproduce_group(hass: HomeAssistant) -> None:
"""Test reproduce_state with group."""
context = Context()
def clone_state(state, entity_id):
"""Return a cloned state with different entity_id."""
return State(
entity_id,
state.state,
state.attributes,
last_changed=state.last_changed,
last_updated=state.last_updated,
context=state.context,
)
with patch(
"homeassistant.components.group.reproduce_state.async_reproduce_state"
) as fun:
fun.return_value = Future()
fun.return_value.set_result(None)
hass.states.async_set(
"group.test",
"off",
{"entity_id": ["light.test1", "light.test2", "switch.test1"]},
)
hass.states.async_set("light.test1", "off")
hass.states.async_set("light.test2", "off")
hass.states.async_set("switch.test1", "off")
state = State("group.test", "on")
await async_reproduce_states(hass, [state], context=context)
fun.assert_called_once_with(
hass,
ANY,
context=context,
reproduce_options=None,
)
entities = fun.call_args[0][1]
assert entities[0].entity_id == "light.test1"
assert entities[1].entity_id == "light.test2"
assert entities[2].entity_id == "switch.test1"

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,460 @@
"""The tests for the Group Switch platform."""
import asyncio
from unittest.mock import patch
import pytest
from homeassistant import config as hass_config
from homeassistant.components.group import DOMAIN, SERVICE_RELOAD
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SERVICE_TOGGLE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import get_fixture_path
async def test_default_state(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test switch group default state."""
hass.states.async_set("switch.tv", "on")
await async_setup_component(
hass,
SWITCH_DOMAIN,
{
SWITCH_DOMAIN: {
"platform": DOMAIN,
"entities": ["switch.tv", "switch.soundbar"],
"name": "Multimedia Group",
"unique_id": "unique_identifier",
"all": "false",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("switch.multimedia_group")
assert state is not None
assert state.state == STATE_ON
assert state.attributes.get(ATTR_ENTITY_ID) == ["switch.tv", "switch.soundbar"]
entry = entity_registry.async_get("switch.multimedia_group")
assert entry
assert entry.unique_id == "unique_identifier"
async def test_state_reporting(hass: HomeAssistant) -> None:
"""Test the state reporting in 'any' mode.
The group state is unavailable if all group members are unavailable.
Otherwise, the group state is unknown if all group members are unknown.
Otherwise, the group state is on if at least one group member is on.
Otherwise, the group state is off.
"""
await async_setup_component(
hass,
SWITCH_DOMAIN,
{
SWITCH_DOMAIN: {
"platform": DOMAIN,
"entities": ["switch.test1", "switch.test2"],
"all": "false",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
# Initial state with no group member in the state machine -> unavailable
assert hass.states.get("switch.switch_group").state == STATE_UNAVAILABLE
# All group members unavailable -> unavailable
hass.states.async_set("switch.test1", STATE_UNAVAILABLE)
hass.states.async_set("switch.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNAVAILABLE
# All group members unknown -> unknown
hass.states.async_set("switch.test1", STATE_UNKNOWN)
hass.states.async_set("switch.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNKNOWN
# Group members unknown or unavailable -> unknown
hass.states.async_set("switch.test1", STATE_UNKNOWN)
hass.states.async_set("switch.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNKNOWN
# At least one member on -> group on
hass.states.async_set("switch.test1", STATE_ON)
hass.states.async_set("switch.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_ON
hass.states.async_set("switch.test1", STATE_ON)
hass.states.async_set("switch.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_ON
hass.states.async_set("switch.test1", STATE_ON)
hass.states.async_set("switch.test2", STATE_ON)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_ON
hass.states.async_set("switch.test1", STATE_ON)
hass.states.async_set("switch.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_ON
# Otherwise -> off
hass.states.async_set("switch.test1", STATE_OFF)
hass.states.async_set("switch.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_OFF
hass.states.async_set("switch.test1", STATE_UNKNOWN)
hass.states.async_set("switch.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_OFF
hass.states.async_set("switch.test1", STATE_UNAVAILABLE)
hass.states.async_set("switch.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_OFF
# All group members removed from the state machine -> unavailable
hass.states.async_remove("switch.test1")
hass.states.async_remove("switch.test2")
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNAVAILABLE
async def test_state_reporting_all(hass: HomeAssistant) -> None:
"""Test the state reporting in 'all' mode.
The group state is unavailable if all group members are unavailable.
Otherwise, the group state is unknown if at least one group member is unknown or unavailable.
Otherwise, the group state is off if at least one group member is off.
Otherwise, the group state is on.
"""
await async_setup_component(
hass,
SWITCH_DOMAIN,
{
SWITCH_DOMAIN: {
"platform": DOMAIN,
"entities": ["switch.test1", "switch.test2"],
"all": "true",
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
# Initial state with no group member in the state machine -> unavailable
assert hass.states.get("switch.switch_group").state == STATE_UNAVAILABLE
# All group members unavailable -> unavailable
hass.states.async_set("switch.test1", STATE_UNAVAILABLE)
hass.states.async_set("switch.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNAVAILABLE
# At least one member unknown or unavailable -> group unknown
hass.states.async_set("switch.test1", STATE_ON)
hass.states.async_set("switch.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNKNOWN
hass.states.async_set("switch.test1", STATE_ON)
hass.states.async_set("switch.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNKNOWN
hass.states.async_set("switch.test1", STATE_UNKNOWN)
hass.states.async_set("switch.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNKNOWN
hass.states.async_set("switch.test1", STATE_OFF)
hass.states.async_set("switch.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNKNOWN
hass.states.async_set("switch.test1", STATE_OFF)
hass.states.async_set("switch.test2", STATE_UNKNOWN)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNKNOWN
hass.states.async_set("switch.test1", STATE_UNKNOWN)
hass.states.async_set("switch.test2", STATE_UNAVAILABLE)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNKNOWN
# At least one member off -> group off
hass.states.async_set("switch.test1", STATE_ON)
hass.states.async_set("switch.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_OFF
hass.states.async_set("switch.test1", STATE_OFF)
hass.states.async_set("switch.test2", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_OFF
# Otherwise -> on
hass.states.async_set("switch.test1", STATE_ON)
hass.states.async_set("switch.test2", STATE_ON)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_ON
# All group members removed from the state machine -> unavailable
hass.states.async_remove("switch.test1")
hass.states.async_remove("switch.test2")
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_UNAVAILABLE
@pytest.mark.usefixtures("enable_custom_integrations")
async def test_service_calls(hass: HomeAssistant) -> None:
"""Test service calls."""
await async_setup_component(
hass,
SWITCH_DOMAIN,
{
SWITCH_DOMAIN: [
{"platform": "demo"},
{
"platform": DOMAIN,
"entities": [
"switch.ac",
"switch.decorative_lights",
],
"all": "false",
},
]
},
)
await hass.async_block_till_done()
group_state = hass.states.get("switch.switch_group")
assert group_state.state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TOGGLE,
{ATTR_ENTITY_ID: "switch.switch_group"},
blocking=True,
)
assert hass.states.get("switch.ac").state == STATE_OFF
assert hass.states.get("switch.decorative_lights").state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.switch_group"},
blocking=True,
)
assert hass.states.get("switch.ac").state == STATE_ON
assert hass.states.get("switch.decorative_lights").state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.switch_group"},
blocking=True,
)
assert hass.states.get("switch.ac").state == STATE_OFF
assert hass.states.get("switch.decorative_lights").state == STATE_OFF
async def test_reload(hass: HomeAssistant) -> None:
"""Test the ability to reload switches."""
await async_setup_component(
hass,
SWITCH_DOMAIN,
{
SWITCH_DOMAIN: [
{"platform": "demo"},
{
"platform": DOMAIN,
"entities": [
"switch.ac",
"switch.decorative_lights",
],
"all": "false",
},
]
},
)
await hass.async_block_till_done()
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group").state == STATE_ON
yaml_path = get_fixture_path("configuration.yaml", "group")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group") is None
assert hass.states.get("switch.master_switches_g") is not None
assert hass.states.get("switch.outside_switches_g") is not None
async def test_reload_with_platform_not_setup(hass: HomeAssistant) -> None:
"""Test the ability to reload switches."""
hass.states.async_set("switch.something", STATE_ON)
await async_setup_component(
hass,
SWITCH_DOMAIN,
{
SWITCH_DOMAIN: [
{"platform": "demo"},
]
},
)
assert await async_setup_component(
hass,
"group",
{
"group": {
"group_zero": {"entities": "switch.something", "icon": "mdi:work"},
}
},
)
await hass.async_block_till_done()
yaml_path = get_fixture_path("configuration.yaml", "group")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group") is None
assert hass.states.get("switch.master_switches_g") is not None
assert hass.states.get("switch.outside_switches_g") is not None
async def test_reload_with_base_integration_platform_not_setup(
hass: HomeAssistant,
) -> None:
"""Test the ability to reload switches."""
assert await async_setup_component(
hass,
"group",
{
"group": {
"group_zero": {"entities": "switch.something", "icon": "mdi:work"},
}
},
)
await hass.async_block_till_done()
hass.states.async_set("switch.master_switch", STATE_ON)
hass.states.async_set("switch.master_switch_2", STATE_OFF)
hass.states.async_set("switch.outside_switch", STATE_OFF)
hass.states.async_set("switch.outside_switch_2", STATE_OFF)
yaml_path = get_fixture_path("configuration.yaml", "group")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("switch.switch_group") is None
assert hass.states.get("switch.master_switches_g") is not None
assert hass.states.get("switch.outside_switches_g") is not None
assert hass.states.get("switch.master_switches_g").state == STATE_ON
assert hass.states.get("switch.outside_switches_g").state == STATE_OFF
async def test_nested_group(hass: HomeAssistant) -> None:
"""Test nested switch group."""
await async_setup_component(
hass,
SWITCH_DOMAIN,
{
SWITCH_DOMAIN: [
{"platform": "demo"},
{
"platform": DOMAIN,
"entities": ["switch.some_group"],
"name": "Nested Group",
"all": "false",
},
{
"platform": DOMAIN,
"entities": ["switch.ac", "switch.decorative_lights"],
"name": "Some Group",
"all": "false",
},
]
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("switch.some_group")
assert state is not None
assert state.state == STATE_ON
assert state.attributes.get(ATTR_ENTITY_ID) == [
"switch.ac",
"switch.decorative_lights",
]
state = hass.states.get("switch.nested_group")
assert state is not None
assert state.state == STATE_ON
assert state.attributes.get(ATTR_ENTITY_ID) == ["switch.some_group"]
# Test controlling the nested group
async with asyncio.timeout(0.5):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TOGGLE,
{ATTR_ENTITY_ID: "switch.nested_group"},
blocking=True,
)
assert hass.states.get("switch.ac").state == STATE_OFF
assert hass.states.get("switch.decorative_lights").state == STATE_OFF
assert hass.states.get("switch.some_group").state == STATE_OFF
assert hass.states.get("switch.nested_group").state == STATE_OFF