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,199 @@
"""Tests for the Hyperion component."""
from __future__ import annotations
from types import TracebackType
from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from hyperion import const
from homeassistant.components.hyperion import get_hyperion_unique_id
from homeassistant.components.hyperion.const import CONF_PRIORITY, DOMAIN
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry
TEST_HOST = "test"
TEST_PORT = const.DEFAULT_PORT_JSON + 1
TEST_PORT_UI = const.DEFAULT_PORT_UI + 1
TEST_INSTANCE = 1
TEST_ID = "default"
TEST_SYSINFO_ID = "f9aab089-f85a-55cf-b7c1-222a72faebe9"
TEST_SYSINFO_VERSION = "2.0.0-alpha.9"
TEST_PRIORITY = 180
TEST_ENTITY_ID_1 = "light.test_instance_1"
TEST_ENTITY_ID_2 = "light.test_instance_2"
TEST_ENTITY_ID_3 = "light.test_instance_3"
TEST_TITLE = f"{TEST_HOST}:{TEST_PORT}"
TEST_TOKEN = "sekr1t"
TEST_CONFIG_ENTRY_ID = "74565ad414754616000674c87bdc876c"
TEST_CONFIG_ENTRY_OPTIONS: dict[str, Any] = {CONF_PRIORITY: TEST_PRIORITY}
TEST_INSTANCE_1: dict[str, Any] = {
"friendly_name": "Test instance 1",
"instance": 1,
"running": True,
}
TEST_INSTANCE_2: dict[str, Any] = {
"friendly_name": "Test instance 2",
"instance": 2,
"running": True,
}
TEST_INSTANCE_3: dict[str, Any] = {
"friendly_name": "Test instance 3",
"instance": 3,
"running": True,
}
TEST_AUTH_REQUIRED_RESP: dict[str, Any] = {
"command": "authorize-tokenRequired",
"info": {
"required": True,
},
"success": True,
"tan": 1,
}
TEST_AUTH_NOT_REQUIRED_RESP = {
**TEST_AUTH_REQUIRED_RESP,
"info": {"required": False},
}
class AsyncContextManagerMock(Mock):
"""An async context manager mock for Hyperion."""
async def __aenter__(self) -> AsyncContextManagerMock | None:
"""Enter context manager and connect the client."""
result = await self.async_client_connect()
return self if result else None
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
traceback: TracebackType | None,
) -> None:
"""Leave context manager and disconnect the client."""
await self.async_client_disconnect()
def create_mock_client() -> Mock:
"""Create a mock Hyperion client."""
mock_client = AsyncContextManagerMock()
# pylint: disable=attribute-defined-outside-init
mock_client.async_client_connect = AsyncMock(return_value=True)
mock_client.async_client_disconnect = AsyncMock(return_value=True)
mock_client.async_is_auth_required = AsyncMock(
return_value=TEST_AUTH_NOT_REQUIRED_RESP
)
mock_client.async_login = AsyncMock(
return_value={"command": "authorize-login", "success": True, "tan": 0}
)
mock_client.async_sysinfo_id = AsyncMock(return_value=TEST_SYSINFO_ID)
mock_client.async_sysinfo_version = AsyncMock(return_value=TEST_SYSINFO_VERSION)
mock_client.async_client_switch_instance = AsyncMock(return_value=True)
mock_client.async_client_login = AsyncMock(return_value=True)
mock_client.async_get_serverinfo = AsyncMock(
return_value={
"command": "serverinfo",
"success": True,
"tan": 0,
"info": {"fake": "data"},
}
)
mock_client.priorities = []
mock_client.adjustment = None
mock_client.effects = None
mock_client.instances = [
{"friendly_name": "Test instance 1", "instance": 0, "running": True}
]
mock_client.remote_url = f"http://{TEST_HOST}:{TEST_PORT_UI}"
return mock_client
def add_test_config_entry(
hass: HomeAssistant,
data: dict[str, Any] | None = None,
options: dict[str, Any] | None = None,
) -> MockConfigEntry:
"""Add a test config entry."""
config_entry = MockConfigEntry(
entry_id=TEST_CONFIG_ENTRY_ID,
domain=DOMAIN,
data=data
or {
CONF_HOST: TEST_HOST,
CONF_PORT: TEST_PORT,
},
title=f"Hyperion {TEST_SYSINFO_ID}",
unique_id=TEST_SYSINFO_ID,
options=options or TEST_CONFIG_ENTRY_OPTIONS,
)
config_entry.add_to_hass(hass)
return config_entry
async def setup_test_config_entry(
hass: HomeAssistant,
config_entry: ConfigEntry | None = None,
hyperion_client: Mock | None = None,
options: dict[str, Any] | None = None,
) -> ConfigEntry:
"""Add a test Hyperion entity to hass."""
config_entry = config_entry or add_test_config_entry(hass, options=options)
hyperion_client = hyperion_client or create_mock_client()
# pylint: disable-next=attribute-defined-outside-init
hyperion_client.instances = [TEST_INSTANCE_1]
with patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=hyperion_client,
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return config_entry
def call_registered_callback(
client: AsyncMock, key: str, *args: Any, **kwargs: Any
) -> None:
"""Call Hyperion entity callbacks that were registered with the client."""
for call in client.add_callbacks.call_args_list:
if key in call[0][0]:
call[0][0][key](*args, **kwargs)
def register_test_entity(
hass: HomeAssistant, domain: str, type_name: str, entity_id: str
) -> None:
"""Register a test entity."""
unique_id = get_hyperion_unique_id(TEST_SYSINFO_ID, TEST_INSTANCE, type_name)
entity_id = entity_id.split(".")[1]
entity_registry = er.async_get(hass)
entity_registry.async_get_or_create(
domain,
DOMAIN,
unique_id,
suggested_object_id=entity_id,
disabled_by=None,
)
async def async_call_registered_callback(
client: AsyncMock, key: str, *args: Any, **kwargs: Any
) -> None:
"""Call Hyperion entity callbacks that were registered with the client."""
for call in client.add_callbacks.call_args_list:
if key in call[0][0]:
await call[0][0][key](*args, **kwargs)

View File

@@ -0,0 +1,3 @@
"""hyperion conftest."""
from tests.components.light.conftest import mock_light_profiles # noqa: F401

View File

@@ -0,0 +1,211 @@
"""Tests for the Hyperion integration."""
from __future__ import annotations
import asyncio
import base64
from collections.abc import Awaitable, Callable
from unittest.mock import AsyncMock, Mock, patch
from aiohttp import web
import pytest
from homeassistant.components.camera import (
DEFAULT_CONTENT_TYPE,
DOMAIN as CAMERA_DOMAIN,
async_get_image,
async_get_mjpeg_stream,
)
from homeassistant.components.hyperion import get_hyperion_device_id
from homeassistant.components.hyperion.const import (
DOMAIN,
HYPERION_MANUFACTURER_NAME,
HYPERION_MODEL_NAME,
TYPE_HYPERION_CAMERA,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import (
TEST_CONFIG_ENTRY_ID,
TEST_INSTANCE,
TEST_INSTANCE_1,
TEST_SYSINFO_ID,
async_call_registered_callback,
create_mock_client,
register_test_entity,
setup_test_config_entry,
)
TEST_CAMERA_ENTITY_ID = "camera.test_instance_1"
TEST_IMAGE_DATA = "TEST DATA"
TEST_IMAGE_UPDATE = {
"command": "ledcolors-imagestream-update",
"result": {
"image": "data:image/jpg;base64,"
+ base64.b64encode(TEST_IMAGE_DATA.encode()).decode("ascii"),
},
"success": True,
}
async def test_camera_setup(hass: HomeAssistant) -> None:
"""Test turning the light on."""
client = create_mock_client()
await setup_test_config_entry(hass, hyperion_client=client)
# Verify switch is on (as per TEST_COMPONENTS above).
entity_state = hass.states.get(TEST_CAMERA_ENTITY_ID)
assert entity_state
assert entity_state.state == "idle"
async def test_camera_image(hass: HomeAssistant) -> None:
"""Test retrieving a single camera image."""
client = create_mock_client()
client.async_send_image_stream_start = AsyncMock(return_value=True)
client.async_send_image_stream_stop = AsyncMock(return_value=True)
await setup_test_config_entry(hass, hyperion_client=client)
get_image_coro = async_get_image(hass, TEST_CAMERA_ENTITY_ID)
image_stream_update_coro = async_call_registered_callback(
client, "ledcolors-imagestream-update", TEST_IMAGE_UPDATE
)
result = await asyncio.gather(get_image_coro, image_stream_update_coro)
assert client.async_send_image_stream_start.called
assert client.async_send_image_stream_stop.called
assert result[0].content == TEST_IMAGE_DATA.encode()
async def test_camera_invalid_image(hass: HomeAssistant) -> None:
"""Test retrieving a single invalid camera image."""
client = create_mock_client()
client.async_send_image_stream_start = AsyncMock(return_value=True)
client.async_send_image_stream_stop = AsyncMock(return_value=True)
await setup_test_config_entry(hass, hyperion_client=client)
get_image_coro = async_get_image(hass, TEST_CAMERA_ENTITY_ID, timeout=0)
image_stream_update_coro = async_call_registered_callback(
client, "ledcolors-imagestream-update", None
)
with pytest.raises(HomeAssistantError):
await asyncio.gather(get_image_coro, image_stream_update_coro)
get_image_coro = async_get_image(hass, TEST_CAMERA_ENTITY_ID, timeout=0)
image_stream_update_coro = async_call_registered_callback(
client, "ledcolors-imagestream-update", {"garbage": 1}
)
with pytest.raises(HomeAssistantError):
await asyncio.gather(get_image_coro, image_stream_update_coro)
get_image_coro = async_get_image(hass, TEST_CAMERA_ENTITY_ID, timeout=0)
image_stream_update_coro = async_call_registered_callback(
client,
"ledcolors-imagestream-update",
{"result": {"image": "data:image/jpg;base64,FOO"}},
)
with pytest.raises(HomeAssistantError):
await asyncio.gather(get_image_coro, image_stream_update_coro)
async def test_camera_image_failed_start_stream_call(hass: HomeAssistant) -> None:
"""Test retrieving a single camera image with failed start stream call."""
client = create_mock_client()
client.async_send_image_stream_start = AsyncMock(return_value=False)
await setup_test_config_entry(hass, hyperion_client=client)
with pytest.raises(HomeAssistantError):
await async_get_image(hass, TEST_CAMERA_ENTITY_ID, timeout=0.01)
assert client.async_send_image_stream_start.called
assert not client.async_send_image_stream_stop.called
async def test_camera_stream(hass: HomeAssistant) -> None:
"""Test retrieving a camera stream."""
client = create_mock_client()
client.async_send_image_stream_start = AsyncMock(return_value=True)
client.async_send_image_stream_stop = AsyncMock(return_value=True)
request = Mock()
async def fake_get_still_stream(
in_request: web.Request,
callback: Callable[[], Awaitable[bytes | None]],
content_type: str,
interval: float,
) -> bytes | None:
assert request == in_request
assert content_type == DEFAULT_CONTENT_TYPE
assert interval == 0.0
return await callback()
await setup_test_config_entry(hass, hyperion_client=client)
with patch(
"homeassistant.components.hyperion.camera.async_get_still_stream",
) as fake:
fake.side_effect = fake_get_still_stream
get_stream_coro = async_get_mjpeg_stream(hass, request, TEST_CAMERA_ENTITY_ID)
image_stream_update_coro = async_call_registered_callback(
client, "ledcolors-imagestream-update", TEST_IMAGE_UPDATE
)
result = await asyncio.gather(get_stream_coro, image_stream_update_coro)
assert client.async_send_image_stream_start.called
assert client.async_send_image_stream_stop.called
assert result[0] == TEST_IMAGE_DATA.encode()
async def test_camera_stream_failed_start_stream_call(hass: HomeAssistant) -> None:
"""Test retrieving a camera stream with failed start stream call."""
client = create_mock_client()
client.async_send_image_stream_start = AsyncMock(return_value=False)
await setup_test_config_entry(hass, hyperion_client=client)
request = Mock()
assert not await async_get_mjpeg_stream(hass, request, TEST_CAMERA_ENTITY_ID)
assert client.async_send_image_stream_start.called
assert not client.async_send_image_stream_stop.called
async def test_device_info(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Verify device information includes expected details."""
client = create_mock_client()
register_test_entity(
hass,
CAMERA_DOMAIN,
TYPE_HYPERION_CAMERA,
TEST_CAMERA_ENTITY_ID,
)
await setup_test_config_entry(hass, hyperion_client=client)
device_id = get_hyperion_device_id(TEST_SYSINFO_ID, TEST_INSTANCE)
device = device_registry.async_get_device(identifiers={(DOMAIN, device_id)})
assert device
assert device.config_entries == {TEST_CONFIG_ENTRY_ID}
assert device.identifiers == {(DOMAIN, device_id)}
assert device.manufacturer == HYPERION_MANUFACTURER_NAME
assert device.model == HYPERION_MODEL_NAME
assert device.name == TEST_INSTANCE_1["friendly_name"]
entities_from_device = [
entry.entity_id
for entry in er.async_entries_for_device(entity_registry, device.id)
]
assert TEST_CAMERA_ENTITY_ID in entities_from_device

View File

@@ -0,0 +1,893 @@
"""Tests for the Hyperion config flow."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable
import dataclasses
from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from hyperion import const
from homeassistant.components import ssdp
from homeassistant.components.hyperion.const import (
CONF_AUTH_ID,
CONF_CREATE_TOKEN,
CONF_EFFECT_HIDE_LIST,
CONF_EFFECT_SHOW_LIST,
CONF_PRIORITY,
DOMAIN,
)
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.config_entries import SOURCE_SSDP, SOURCE_USER
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_HOST,
CONF_PORT,
CONF_TOKEN,
SERVICE_TURN_ON,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult, FlowResultType
from . import (
TEST_AUTH_REQUIRED_RESP,
TEST_CONFIG_ENTRY_ID,
TEST_ENTITY_ID_1,
TEST_HOST,
TEST_INSTANCE,
TEST_PORT,
TEST_PORT_UI,
TEST_SYSINFO_ID,
TEST_TITLE,
TEST_TOKEN,
add_test_config_entry,
create_mock_client,
)
from tests.common import MockConfigEntry
TEST_IP_ADDRESS = "192.168.0.1"
TEST_HOST_PORT: dict[str, Any] = {
CONF_HOST: TEST_HOST,
CONF_PORT: TEST_PORT,
}
TEST_AUTH_ID = "ABCDE"
TEST_REQUEST_TOKEN_SUCCESS = {
"command": "authorize-requestToken",
"success": True,
"info": {"comment": const.DEFAULT_ORIGIN, "id": TEST_AUTH_ID, "token": TEST_TOKEN},
}
TEST_REQUEST_TOKEN_FAIL = {
"command": "authorize-requestToken",
"success": False,
"error": "Token request timeout or denied",
}
TEST_SSDP_SERVICE_INFO = ssdp.SsdpServiceInfo(
ssdp_st="upnp:rootdevice",
ssdp_location=f"http://{TEST_HOST}:{TEST_PORT_UI}/description.xml",
ssdp_usn=f"uuid:{TEST_SYSINFO_ID}",
ssdp_ext="",
ssdp_server="Raspbian GNU/Linux 10 (buster)/10 UPnP/1.0 Hyperion/2.0.0-alpha.8",
upnp={
"deviceType": "urn:schemas-upnp-org:device:Basic:1",
"friendlyName": f"Hyperion ({TEST_HOST})",
"manufacturer": "Hyperion Open Source Ambient Lighting",
"manufacturerURL": "https://www.hyperion-project.org",
"modelDescription": "Hyperion Open Source Ambient Light",
"modelName": "Hyperion",
"modelNumber": "2.0.0-alpha.8",
"modelURL": "https://www.hyperion-project.org",
"serialNumber": f"{TEST_SYSINFO_ID}",
"UDN": f"uuid:{TEST_SYSINFO_ID}",
"ports": {
"jsonServer": f"{TEST_PORT}",
"sslServer": "8092",
"protoBuffer": "19445",
"flatBuffer": "19400",
},
"presentationURL": "index.html",
"iconList": {
"icon": {
"mimetype": "image/png",
"height": "100",
"width": "100",
"depth": "32",
"url": "img/hyperion/ssdp_icon.png",
}
},
},
)
async def _create_mock_entry(hass: HomeAssistant) -> MockConfigEntry:
"""Add a test Hyperion entity to hass."""
entry: MockConfigEntry = MockConfigEntry(
entry_id=TEST_CONFIG_ENTRY_ID,
domain=DOMAIN,
unique_id=TEST_SYSINFO_ID,
title=TEST_TITLE,
data={
"host": TEST_HOST,
"port": TEST_PORT,
"instance": TEST_INSTANCE,
},
)
entry.add_to_hass(hass)
# Setup
client = create_mock_client()
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
return entry
async def _init_flow(
hass: HomeAssistant,
source: str = SOURCE_USER,
data: dict[str, Any] | None = None,
) -> Any:
"""Initialize a flow."""
data = data or {}
return await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}, data=data
)
async def _configure_flow(
hass: HomeAssistant, result: FlowResult, user_input: dict[str, Any] | None = None
) -> Any:
"""Provide input to a flow."""
user_input = user_input or {}
with patch(
"homeassistant.components.hyperion.async_setup_entry",
return_value=True,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=user_input
)
await hass.async_block_till_done()
return result
async def test_user_if_no_configuration(hass: HomeAssistant) -> None:
"""Check flow behavior when no configuration is present."""
result = await _init_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["handler"] == DOMAIN
async def test_user_existing_id_abort(hass: HomeAssistant) -> None:
"""Verify a duplicate ID results in an abort."""
result = await _init_flow(hass)
await _create_mock_entry(hass)
client = create_mock_client()
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_user_client_errors(hass: HomeAssistant) -> None:
"""Verify correct behaviour with client errors."""
result = await _init_flow(hass)
client = create_mock_client()
# Fail the connection.
client.async_client_connect = AsyncMock(return_value=False)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "cannot_connect"
# Fail the auth check call.
client.async_client_connect = AsyncMock(return_value=True)
client.async_is_auth_required = AsyncMock(return_value={"success": False})
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "auth_required_error"
async def test_user_confirm_cannot_connect(hass: HomeAssistant) -> None:
"""Test a failure to connect during confirmation."""
result = await _init_flow(hass)
good_client = create_mock_client()
bad_client = create_mock_client()
bad_client.async_client_connect = AsyncMock(return_value=False)
# Confirmation sync_client_connect fails.
with patch(
"homeassistant.components.hyperion.client.HyperionClient",
side_effect=[good_client, bad_client],
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_user_confirm_id_error(hass: HomeAssistant) -> None:
"""Test a failure fetching the server id during confirmation."""
result = await _init_flow(hass)
client = create_mock_client()
client.async_sysinfo_id = AsyncMock(return_value=None)
# Confirmation sync_client_connect fails.
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_id"
async def test_user_noauth_flow_success(hass: HomeAssistant) -> None:
"""Check a full flow without auth."""
result = await _init_flow(hass)
client = create_mock_client()
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["handler"] == DOMAIN
assert result["title"] == TEST_TITLE
assert result["data"] == {
**TEST_HOST_PORT,
}
async def test_user_auth_required(hass: HomeAssistant) -> None:
"""Verify correct behaviour when auth is required."""
result = await _init_flow(hass)
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
async def test_auth_static_token_auth_required_fail(hass: HomeAssistant) -> None:
"""Verify correct behaviour with a failed auth required call."""
result = await _init_flow(hass)
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=None)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "auth_required_error"
async def test_auth_static_token_success(hass: HomeAssistant) -> None:
"""Test a successful flow with a static token."""
result = await _init_flow(hass)
assert result["step_id"] == "user"
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: False, CONF_TOKEN: TEST_TOKEN}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["handler"] == DOMAIN
assert result["title"] == TEST_TITLE
assert result["data"] == {
**TEST_HOST_PORT,
CONF_TOKEN: TEST_TOKEN,
}
async def test_auth_static_token_login_connect_fail(hass: HomeAssistant) -> None:
"""Test correct behavior with a static token that cannot connect."""
result = await _init_flow(hass)
assert result["step_id"] == "user"
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
client.async_client_connect = AsyncMock(return_value=False)
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: False, CONF_TOKEN: TEST_TOKEN}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_auth_static_token_login_fail(hass: HomeAssistant) -> None:
"""Test correct behavior with a static token that cannot login."""
result = await _init_flow(hass)
assert result["step_id"] == "user"
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
client.async_login = AsyncMock(
return_value={"command": "authorize-login", "success": False, "tan": 0}
)
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: False, CONF_TOKEN: TEST_TOKEN}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "invalid_access_token"
async def test_auth_create_token_approval_declined(hass: HomeAssistant) -> None:
"""Verify correct behaviour when a token request is declined."""
result = await _init_flow(hass)
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_FAIL)
with (
patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=client,
),
patch(
"homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
return_value=TEST_AUTH_ID,
),
):
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "create_token"
assert result["description_placeholders"] == {
CONF_AUTH_ID: TEST_AUTH_ID,
}
result = await _configure_flow(hass, result)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.EXTERNAL_STEP
assert result["step_id"] == "create_token_external"
# The flow will be automatically advanced by the auth token response.
result = await _configure_flow(hass, result)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "auth_new_token_not_granted_error"
async def test_auth_create_token_approval_declined_task_canceled(
hass: HomeAssistant,
) -> None:
"""Verify correct behaviour when a token request is declined."""
result = await _init_flow(hass)
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_FAIL)
class CanceledAwaitableMock(AsyncMock):
"""A canceled awaitable mock."""
def __init__(self) -> None:
super().__init__()
self.done = Mock(return_value=False)
self.cancel = Mock()
def __await__(self) -> None:
raise asyncio.CancelledError
mock_task = CanceledAwaitableMock()
task_coro: Awaitable | None = None
def create_task(arg: Any, **kwargs: Any) -> CanceledAwaitableMock:
nonlocal task_coro
task_coro = arg
return mock_task
with (
patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=client,
),
patch(
"homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
return_value=TEST_AUTH_ID,
),
):
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
)
assert result["step_id"] == "create_token"
# Tests should not patch the async_create_task function
with patch.object(hass, "async_create_task", side_effect=create_task):
result = await _configure_flow(hass, result)
assert result["step_id"] == "create_token_external"
result = await _configure_flow(hass, result)
# This await will advance to the next step.
assert task_coro
await task_coro
# Assert that cancel is called on the task.
assert mock_task.cancel.called
async def test_auth_create_token_when_issued_token_fails(
hass: HomeAssistant,
) -> None:
"""Verify correct behaviour when a token is granted by fails to authenticate."""
result = await _init_flow(hass)
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_SUCCESS)
with (
patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=client,
),
patch(
"homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
return_value=TEST_AUTH_ID,
),
):
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "create_token"
assert result["description_placeholders"] == {
CONF_AUTH_ID: TEST_AUTH_ID,
}
result = await _configure_flow(hass, result)
assert result["type"] is FlowResultType.EXTERNAL_STEP
assert result["step_id"] == "create_token_external"
# The flow will be automatically advanced by the auth token response.
# Make the last verification fail.
client.async_client_connect = AsyncMock(return_value=False)
result = await _configure_flow(hass, result)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_auth_create_token_success(hass: HomeAssistant) -> None:
"""Verify correct behaviour when a token is successfully created."""
result = await _init_flow(hass)
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_SUCCESS)
with (
patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=client,
),
patch(
"homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
return_value=TEST_AUTH_ID,
),
):
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "create_token"
assert result["description_placeholders"] == {
CONF_AUTH_ID: TEST_AUTH_ID,
}
result = await _configure_flow(hass, result)
assert result["type"] is FlowResultType.EXTERNAL_STEP
assert result["step_id"] == "create_token_external"
# The flow will be automatically advanced by the auth token response.
result = await _configure_flow(hass, result)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["handler"] == DOMAIN
assert result["title"] == TEST_TITLE
assert result["data"] == {
**TEST_HOST_PORT,
CONF_TOKEN: TEST_TOKEN,
}
async def test_auth_create_token_success_but_login_fail(
hass: HomeAssistant,
) -> None:
"""Verify correct behaviour when a token is successfully created but the login fails."""
result = await _init_flow(hass)
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_SUCCESS)
with (
patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=client,
),
patch(
"homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
return_value=TEST_AUTH_ID,
),
):
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
)
assert result["step_id"] == "create_token"
result = await _configure_flow(hass, result)
assert result["step_id"] == "create_token_external"
client.async_login = AsyncMock(
return_value={"command": "authorize-login", "success": False, "tan": 0}
)
# The flow will be automatically advanced by the auth token response.
result = await _configure_flow(hass, result)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "auth_new_token_not_work_error"
async def test_ssdp_success(hass: HomeAssistant) -> None:
"""Check an SSDP flow."""
client = create_mock_client()
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _init_flow(hass, source=SOURCE_SSDP, data=TEST_SSDP_SERVICE_INFO)
await hass.async_block_till_done()
# Accept the confirmation.
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _configure_flow(hass, result)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["handler"] == DOMAIN
assert result["title"] == TEST_TITLE
assert result["data"] == {
CONF_HOST: TEST_HOST,
CONF_PORT: TEST_PORT,
}
async def test_ssdp_cannot_connect(hass: HomeAssistant) -> None:
"""Check an SSDP flow that cannot connect."""
client = create_mock_client()
client.async_client_connect = AsyncMock(return_value=False)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _init_flow(hass, source=SOURCE_SSDP, data=TEST_SSDP_SERVICE_INFO)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_ssdp_missing_serial(hass: HomeAssistant) -> None:
"""Check an SSDP flow where no id is provided."""
client = create_mock_client()
bad_data = dataclasses.replace(TEST_SSDP_SERVICE_INFO)
bad_data.upnp = bad_data.upnp.copy()
del bad_data.upnp["serialNumber"]
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _init_flow(hass, source=SOURCE_SSDP, data=bad_data)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_id"
async def test_ssdp_failure_bad_port_json(hass: HomeAssistant) -> None:
"""Check an SSDP flow with bad json port."""
client = create_mock_client()
bad_data = dataclasses.replace(TEST_SSDP_SERVICE_INFO)
bad_data.upnp = bad_data.upnp.copy()
bad_data.upnp["ports"]["jsonServer"] = "not_a_port"
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await _init_flow(hass, source=SOURCE_SSDP, data=bad_data)
result = await _configure_flow(hass, result)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"][CONF_PORT] == const.DEFAULT_PORT_JSON
async def test_ssdp_failure_bad_port_ui(hass: HomeAssistant) -> None:
"""Check an SSDP flow with bad ui port."""
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
bad_data = dataclasses.replace(TEST_SSDP_SERVICE_INFO)
bad_data.ssdp_location = f"http://{TEST_HOST}:not_a_port/description.xml"
with (
patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=client,
),
patch(
"homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
return_value=TEST_AUTH_ID,
),
):
result = await _init_flow(hass, source=SOURCE_SSDP, data=bad_data)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_FAIL)
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "create_token"
# Verify a working URL is used despite the bad port number
assert result["description_placeholders"] == {
CONF_AUTH_ID: TEST_AUTH_ID,
}
async def test_ssdp_abort_duplicates(hass: HomeAssistant) -> None:
"""Check an SSDP flow where no id is provided."""
client = create_mock_client()
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result_1 = await _init_flow(
hass, source=SOURCE_SSDP, data=TEST_SSDP_SERVICE_INFO
)
result_2 = await _init_flow(
hass, source=SOURCE_SSDP, data=TEST_SSDP_SERVICE_INFO
)
await hass.async_block_till_done()
assert result_1["type"] is FlowResultType.FORM
assert result_2["type"] is FlowResultType.ABORT
assert result_2["reason"] == "already_in_progress"
async def test_options_priority(hass: HomeAssistant) -> None:
"""Check an options flow priority option."""
config_entry = add_test_config_entry(hass)
client = create_mock_client()
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get(TEST_ENTITY_ID_1) is not None
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
new_priority = 1
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={CONF_PRIORITY: new_priority},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"][CONF_PRIORITY] == new_priority
# Turn the light on and ensure the new priority is used.
client.async_send_set_color = AsyncMock(return_value=True)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1},
blocking=True,
)
assert client.async_send_set_color.call_args[1][CONF_PRIORITY] == new_priority
async def test_options_effect_show_list(hass: HomeAssistant) -> None:
"""Check an options flow effect show list."""
config_entry = add_test_config_entry(hass)
client = create_mock_client()
client.effects = [
{const.KEY_NAME: "effect1"},
{const.KEY_NAME: "effect2"},
{const.KEY_NAME: "effect3"},
]
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
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
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={CONF_EFFECT_SHOW_LIST: ["effect1", "effect3"]},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
# effect1 and effect3 only, so effect2 is hidden.
assert result["data"][CONF_EFFECT_HIDE_LIST] == ["effect2"]
async def test_options_effect_hide_list_cannot_connect(hass: HomeAssistant) -> None:
"""Check an options flow effect hide list with a failed connection."""
config_entry = add_test_config_entry(hass)
client = create_mock_client()
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
client.async_client_connect = AsyncMock(return_value=False)
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_reauth_success(hass: HomeAssistant) -> None:
"""Check a reauth flow that succeeds."""
config_data = {
CONF_HOST: TEST_HOST,
CONF_PORT: TEST_PORT,
}
config_entry = add_test_config_entry(hass, data=config_data)
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with (
patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=client,
),
patch("homeassistant.components.hyperion.async_setup_entry", return_value=True),
):
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: False, CONF_TOKEN: TEST_TOKEN}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert CONF_TOKEN in config_entry.data
async def test_reauth_cannot_connect(hass: HomeAssistant) -> None:
"""Check a reauth flow that fails to connect."""
config_data = {
CONF_HOST: TEST_HOST,
CONF_PORT: TEST_PORT,
}
config_entry = add_test_config_entry(hass, data=config_data)
client = create_mock_client()
client.async_client_connect = AsyncMock(return_value=False)
with patch(
"homeassistant.components.hyperion.client.HyperionClient", return_value=client
):
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"

View File

@@ -0,0 +1,816 @@
"""Tests for the Hyperion integration."""
from __future__ import annotations
from unittest.mock import AsyncMock, Mock, call, patch
from hyperion import const
import pytest
from homeassistant.components.hyperion import (
get_hyperion_device_id,
light as hyperion_light,
)
from homeassistant.components.hyperion.const import (
CONF_EFFECT_HIDE_LIST,
DEFAULT_ORIGIN,
DOMAIN,
HYPERION_MANUFACTURER_NAME,
HYPERION_MODEL_NAME,
)
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_EFFECT,
ATTR_HS_COLOR,
DOMAIN as LIGHT_DOMAIN,
ColorMode,
LightEntityFeature,
)
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntry, ConfigEntryState
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_HOST,
CONF_PORT,
CONF_SOURCE,
CONF_TOKEN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import (
TEST_AUTH_NOT_REQUIRED_RESP,
TEST_AUTH_REQUIRED_RESP,
TEST_CONFIG_ENTRY_ID,
TEST_ENTITY_ID_1,
TEST_ENTITY_ID_2,
TEST_ENTITY_ID_3,
TEST_HOST,
TEST_ID,
TEST_INSTANCE,
TEST_INSTANCE_1,
TEST_INSTANCE_2,
TEST_INSTANCE_3,
TEST_PORT,
TEST_PRIORITY,
TEST_SYSINFO_ID,
add_test_config_entry,
call_registered_callback,
create_mock_client,
setup_test_config_entry,
)
def _get_config_entry_from_unique_id(
hass: HomeAssistant, unique_id: str
) -> ConfigEntry | None:
for entry in hass.config_entries.async_entries(domain=DOMAIN):
if entry.unique_id == TEST_SYSINFO_ID:
return entry
return None
async def test_setup_config_entry(hass: HomeAssistant) -> None:
"""Test setting up the component via config entries."""
await setup_test_config_entry(hass, hyperion_client=create_mock_client())
assert hass.states.get(TEST_ENTITY_ID_1) is not None
async def test_setup_config_entry_not_ready_connect_fail(
hass: HomeAssistant,
) -> None:
"""Test the component not being ready."""
client = create_mock_client()
client.async_client_connect = AsyncMock(return_value=False)
await setup_test_config_entry(hass, hyperion_client=client)
assert hass.states.get(TEST_ENTITY_ID_1) is None
async def test_setup_config_entry_not_ready_switch_instance_fail(
hass: HomeAssistant,
) -> None:
"""Test the component not being ready."""
client = create_mock_client()
client.async_client_switch_instance = AsyncMock(return_value=False)
await setup_test_config_entry(hass, hyperion_client=client)
assert client.async_client_disconnect.called
assert hass.states.get(TEST_ENTITY_ID_1) is None
async def test_setup_config_entry_not_ready_load_state_fail(
hass: HomeAssistant,
) -> None:
"""Test the component not being ready."""
client = create_mock_client()
client.async_get_serverinfo = AsyncMock(
return_value={
"command": "serverinfo",
"success": False,
}
)
await setup_test_config_entry(hass, hyperion_client=client)
assert client.async_client_disconnect.called
assert hass.states.get(TEST_ENTITY_ID_1) is None
async def test_setup_config_entry_dynamic_instances(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
) -> None:
"""Test dynamic changes in the instance configuration."""
config_entry = add_test_config_entry(hass)
master_client = create_mock_client()
master_client.instances = [TEST_INSTANCE_1, TEST_INSTANCE_2]
entity_client = create_mock_client()
entity_client.instances = master_client.instances
with patch(
"homeassistant.components.hyperion.client.HyperionClient",
side_effect=[master_client, entity_client, entity_client],
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get(TEST_ENTITY_ID_1) is not None
assert hass.states.get(TEST_ENTITY_ID_2) is not None
assert master_client.set_callbacks.called
# == Inject a new instances update (stop instance 1, add instance 3)
instance_callback = master_client.set_callbacks.call_args[0][0][
f"{const.KEY_INSTANCE}-{const.KEY_UPDATE}"
]
with patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=entity_client,
):
await instance_callback(
{
const.KEY_SUCCESS: True,
const.KEY_DATA: [
{**TEST_INSTANCE_1, "running": False},
TEST_INSTANCE_2,
TEST_INSTANCE_3,
],
}
)
await hass.async_block_till_done()
assert hass.states.get(TEST_ENTITY_ID_1) is None
assert hass.states.get(TEST_ENTITY_ID_2) is not None
assert hass.states.get(TEST_ENTITY_ID_3) is not None
# Instance 1 is stopped, it should still be registered.
assert entity_registry.async_is_registered(TEST_ENTITY_ID_1)
# == Inject a new instances update (remove instance 1)
assert master_client.set_callbacks.called
instance_callback = master_client.set_callbacks.call_args[0][0][
f"{const.KEY_INSTANCE}-{const.KEY_UPDATE}"
]
with patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=entity_client,
):
await instance_callback(
{
const.KEY_SUCCESS: True,
const.KEY_DATA: [TEST_INSTANCE_2, TEST_INSTANCE_3],
}
)
await hass.async_block_till_done()
assert hass.states.get(TEST_ENTITY_ID_1) is None
assert hass.states.get(TEST_ENTITY_ID_2) is not None
assert hass.states.get(TEST_ENTITY_ID_3) is not None
# Instance 1 is removed, it should not still be registered.
assert not entity_registry.async_is_registered(TEST_ENTITY_ID_1)
# == Inject a new instances update (re-add instance 1, but not running)
with patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=entity_client,
):
await instance_callback(
{
const.KEY_SUCCESS: True,
const.KEY_DATA: [
{**TEST_INSTANCE_1, "running": False},
TEST_INSTANCE_2,
TEST_INSTANCE_3,
],
}
)
await hass.async_block_till_done()
assert hass.states.get(TEST_ENTITY_ID_1) is None
assert hass.states.get(TEST_ENTITY_ID_2) is not None
assert hass.states.get(TEST_ENTITY_ID_3) is not None
# == Inject a new instances update (re-add instance 1, running)
with patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=entity_client,
):
await instance_callback(
{
const.KEY_SUCCESS: True,
const.KEY_DATA: [TEST_INSTANCE_1, TEST_INSTANCE_2, TEST_INSTANCE_3],
}
)
await hass.async_block_till_done()
assert hass.states.get(TEST_ENTITY_ID_1) is not None
assert hass.states.get(TEST_ENTITY_ID_2) is not None
assert hass.states.get(TEST_ENTITY_ID_3) is not None
async def test_light_basic_properties(hass: HomeAssistant) -> None:
"""Test the basic properties."""
client = create_mock_client()
client.priorities = [{const.KEY_PRIORITY: TEST_PRIORITY}]
await setup_test_config_entry(hass, hyperion_client=client)
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.state == "on"
assert entity_state.attributes["brightness"] == 255
assert entity_state.attributes["hs_color"] == (0.0, 0.0)
assert entity_state.attributes["icon"] == hyperion_light.ICON_LIGHTBULB
assert entity_state.attributes["effect"] == hyperion_light.KEY_EFFECT_SOLID
# By default the effect list contains only 'Solid'.
assert len(entity_state.attributes["effect_list"]) == 1
assert entity_state.attributes["color_mode"] == ColorMode.HS
assert entity_state.attributes["supported_color_modes"] == [ColorMode.HS]
assert entity_state.attributes["supported_features"] == LightEntityFeature.EFFECT
async def test_light_async_turn_on(hass: HomeAssistant) -> None:
"""Test turning the light on."""
client = create_mock_client()
client.priorities = [{const.KEY_PRIORITY: TEST_PRIORITY}]
await setup_test_config_entry(hass, hyperion_client=client)
# On (=), 100% (=), solid (=), [255,255,255] (=)
client.async_send_set_color = AsyncMock(return_value=True)
await hass.services.async_call(
LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: TEST_ENTITY_ID_1}, blocking=True
)
assert client.async_send_set_color.call_args == call(
**{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COLOR: [255, 255, 255],
const.KEY_ORIGIN: DEFAULT_ORIGIN,
}
)
# On (=), 50% (!), solid (=), [255,255,255] (=)
# ===
brightness = 128
client.async_send_set_color = AsyncMock(return_value=True)
client.async_send_set_adjustment = AsyncMock(return_value=True)
client.adjustment = [{const.KEY_ID: TEST_ID}]
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1, ATTR_BRIGHTNESS: brightness},
blocking=True,
)
assert client.async_send_set_adjustment.call_args == call(
**{const.KEY_ADJUSTMENT: {const.KEY_BRIGHTNESS: 50, const.KEY_ID: TEST_ID}}
)
assert client.async_send_set_color.call_args == call(
**{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COLOR: [255, 255, 255],
const.KEY_ORIGIN: DEFAULT_ORIGIN,
}
)
# Simulate a false return of async_send_set_adjustment
client.async_send_set_adjustment = AsyncMock(return_value=False)
client.adjustment = [{const.KEY_ID: TEST_ID}]
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1, ATTR_BRIGHTNESS: brightness},
blocking=True,
)
# Simulate a state callback from Hyperion.
client.adjustment = [{const.KEY_BRIGHTNESS: 50}]
call_registered_callback(client, "adjustment-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.state == "on"
assert entity_state.attributes["brightness"] == brightness
# On (=), 50% (=), solid (=), [0,255,255] (!)
hs_color = (180.0, 100.0)
client.async_send_set_color = AsyncMock(return_value=True)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1, ATTR_HS_COLOR: hs_color},
blocking=True,
)
assert client.async_send_set_color.call_args == call(
**{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COLOR: (0, 255, 255),
const.KEY_ORIGIN: DEFAULT_ORIGIN,
}
)
# Simulate a state callback from Hyperion.
client.priorities = [
{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COMPONENTID: const.KEY_COMPONENTID_COLOR,
const.KEY_VALUE: {const.KEY_RGB: (0, 255, 255)},
const.KEY_OWNER: "System",
}
]
call_registered_callback(client, "priorities-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.attributes["hs_color"] == hs_color
assert entity_state.attributes["icon"] == hyperion_light.ICON_LIGHTBULB
# On (=), 100% (!), solid, [0,255,255] (=)
brightness = 255
client.async_send_set_color = AsyncMock(return_value=True)
client.async_send_set_adjustment = AsyncMock(return_value=True)
client.adjustment = [{const.KEY_ID: TEST_ID}]
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1, ATTR_BRIGHTNESS: brightness},
blocking=True,
)
assert client.async_send_set_adjustment.call_args == call(
**{const.KEY_ADJUSTMENT: {const.KEY_BRIGHTNESS: 100, const.KEY_ID: TEST_ID}}
)
assert client.async_send_set_color.call_args == call(
**{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COLOR: (0, 255, 255),
const.KEY_ORIGIN: DEFAULT_ORIGIN,
}
)
client.adjustment = [{const.KEY_BRIGHTNESS: 100}]
call_registered_callback(client, "adjustment-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.attributes["brightness"] == brightness
# On (=), 100% (=), "Warm Blobs" (!), [0,255,255] (=)
effect = "Warm Blobs"
client.async_send_clear = AsyncMock(return_value=True)
client.async_send_set_effect = AsyncMock(return_value=True)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1, ATTR_EFFECT: effect},
blocking=True,
)
assert client.async_send_set_effect.call_args == call(
**{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_EFFECT: {const.KEY_NAME: effect},
const.KEY_ORIGIN: DEFAULT_ORIGIN,
}
)
client.priorities = [
{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COMPONENTID: const.KEY_COMPONENTID_EFFECT,
const.KEY_OWNER: effect,
}
]
call_registered_callback(client, "priorities-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.attributes["icon"] == hyperion_light.ICON_EFFECT
assert entity_state.attributes["effect"] == effect
# On (=), 100% (=), [0,0,255] (!)
# Ensure changing the color will move the effect to 'Solid' automatically.
hs_color = (240.0, 100.0)
client.async_send_set_color = AsyncMock(return_value=True)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1, ATTR_HS_COLOR: hs_color},
blocking=True,
)
assert client.async_send_set_color.call_args == call(
**{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COLOR: (0, 0, 255),
const.KEY_ORIGIN: DEFAULT_ORIGIN,
}
)
# Simulate a state callback from Hyperion.
client.priorities = [
{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COMPONENTID: const.KEY_COMPONENTID_COLOR,
const.KEY_VALUE: {const.KEY_RGB: (0, 0, 255)},
const.KEY_OWNER: "System",
}
]
call_registered_callback(client, "priorities-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.attributes["hs_color"] == hs_color
assert entity_state.attributes["icon"] == hyperion_light.ICON_LIGHTBULB
assert entity_state.attributes["effect"] == hyperion_light.KEY_EFFECT_SOLID
# No calls if disconnected.
client.has_loaded_state = False
call_registered_callback(client, "client-update", {"loaded-state": False})
client.async_send_clear = AsyncMock(return_value=True)
client.async_send_set_effect = AsyncMock(return_value=True)
await hass.services.async_call(
LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: TEST_ENTITY_ID_1}, blocking=True
)
assert not client.async_send_clear.called
assert not client.async_send_set_effect.called
async def test_light_async_turn_on_fail_async_send_set_effect(
hass: HomeAssistant,
) -> None:
"""Test async_send_set_effect failure when turning on the light."""
client = create_mock_client()
client.is_on = Mock(return_value=True)
client.async_send_clear = AsyncMock(return_value=True)
client.async_send_set_effect = AsyncMock(return_value=False)
await setup_test_config_entry(hass, hyperion_client=client)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1, ATTR_EFFECT: "Warm Mood Blobs"},
blocking=True,
)
assert client.method_calls[-1] == call.async_send_set_effect(
priority=180, effect={"name": "Warm Mood Blobs"}, origin="Home Assistant"
)
async def test_light_async_turn_on_fail_async_send_set_color(
hass: HomeAssistant,
) -> None:
"""Test async_send_set_color failure when turning on the light."""
client = create_mock_client()
client.is_on = Mock(return_value=True)
client.async_send_clear = AsyncMock(return_value=True)
client.async_send_set_color = AsyncMock(return_value=False)
await setup_test_config_entry(hass, hyperion_client=client)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1, ATTR_HS_COLOR: (240.0, 100.0)},
blocking=True,
)
assert client.method_calls[-1] == call.async_send_set_color(
priority=180, color=(0, 0, 255), origin="Home Assistant"
)
async def test_light_async_turn_off_fail_async_send_send_clear(
hass: HomeAssistant,
) -> None:
"""Test async_send_clear failure when turning off the light."""
client = create_mock_client()
client.async_send_clear = AsyncMock(return_value=False)
await setup_test_config_entry(hass, hyperion_client=client)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1},
blocking=True,
)
assert client.method_calls[-1] == call.async_send_clear(priority=TEST_PRIORITY)
async def test_light_async_turn_off(hass: HomeAssistant) -> None:
"""Test turning the light off."""
client = create_mock_client()
await setup_test_config_entry(hass, hyperion_client=client)
client.async_send_clear = AsyncMock(return_value=True)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1},
blocking=True,
)
assert client.async_send_clear.called
assert client.async_send_clear.call_args == call(
**{const.KEY_PRIORITY: TEST_PRIORITY}
)
async def test_light_async_updates_from_hyperion_client(
hass: HomeAssistant,
) -> None:
"""Test receiving a variety of Hyperion client callbacks."""
client = create_mock_client()
client.priorities = [{const.KEY_PRIORITY: TEST_PRIORITY}]
await setup_test_config_entry(hass, hyperion_client=client)
# Bright change gets accepted.
brightness = 10
client.adjustment = [{const.KEY_BRIGHTNESS: brightness}]
call_registered_callback(client, "adjustment-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.state == "on"
assert entity_state.attributes["brightness"] == round(255 * (brightness / 100.0))
# Broken brightness value is ignored.
bad_brightness = -200
client.adjustment = [{const.KEY_BRIGHTNESS: bad_brightness}]
call_registered_callback(client, "adjustment-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.state == "on"
assert entity_state.attributes["brightness"] == round(255 * (brightness / 100.0))
# Update priorities (Effect)
effect = "foo"
client.priorities = [
{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COMPONENTID: const.KEY_COMPONENTID_EFFECT,
const.KEY_OWNER: effect,
const.KEY_VISIBLE: True,
const.KEY_ORIGIN: "System",
}
]
call_registered_callback(client, "priorities-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.attributes["effect"] == effect
assert entity_state.attributes["icon"] == hyperion_light.ICON_EFFECT
assert entity_state.attributes["hs_color"] == (0.0, 0.0)
# Update priorities (Color)
rgb = (0, 100, 100)
client.priorities = [
{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COMPONENTID: const.KEY_COMPONENTID_COLOR,
const.KEY_VALUE: {const.KEY_RGB: rgb},
const.KEY_VISIBLE: True,
const.KEY_ORIGIN: "System",
const.KEY_OWNER: "System",
}
]
call_registered_callback(client, "priorities-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.attributes["effect"] == hyperion_light.KEY_EFFECT_SOLID
assert entity_state.attributes["icon"] == hyperion_light.ICON_LIGHTBULB
assert entity_state.attributes["hs_color"] == (180.0, 100.0)
# Update priorities (None)
client.priorities = []
call_registered_callback(client, "priorities-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.state == "off"
# Update effect list
effects = [{const.KEY_NAME: "One"}, {const.KEY_NAME: "Two"}]
client.effects = effects
call_registered_callback(client, "effects-update")
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.attributes["effect_list"] == [
hyperion_light.KEY_EFFECT_SOLID
] + [effect[const.KEY_NAME] for effect in effects]
# Update connection status (e.g. disconnection).
# Turn on late, check state, disconnect, ensure it cannot be turned off.
client.has_loaded_state = False
call_registered_callback(client, "client-update", {"loaded-state": False})
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.state == "unavailable"
# Update connection status (e.g. re-connection)
client.has_loaded_state = True
client.priorities = [
{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COMPONENTID: const.KEY_COMPONENTID_COLOR,
const.KEY_VALUE: {const.KEY_RGB: rgb},
const.KEY_VISIBLE: True,
const.KEY_ORIGIN: "System",
const.KEY_OWNER: "System",
}
]
call_registered_callback(client, "client-update", {"loaded-state": True})
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.state == "on"
async def test_full_state_loaded_on_start(hass: HomeAssistant) -> None:
"""Test receiving a variety of Hyperion client callbacks."""
client = create_mock_client()
# Update full state (should call all update methods).
brightness = 25
client.adjustment = [{const.KEY_BRIGHTNESS: brightness}]
client.priorities = [
{
const.KEY_PRIORITY: TEST_PRIORITY,
const.KEY_COMPONENTID: const.KEY_COMPONENTID_COLOR,
const.KEY_VALUE: {const.KEY_RGB: (0, 100, 100)},
const.KEY_OWNER: "System",
}
]
client.effects = [{const.KEY_NAME: "One"}, {const.KEY_NAME: "Two"}]
await setup_test_config_entry(hass, hyperion_client=client)
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.attributes["brightness"] == round(255 * (brightness / 100.0))
assert entity_state.attributes["effect"] == hyperion_light.KEY_EFFECT_SOLID
assert entity_state.attributes["icon"] == hyperion_light.ICON_LIGHTBULB
assert entity_state.attributes["hs_color"] == (180.0, 100.0)
async def test_unload_entry(hass: HomeAssistant) -> None:
"""Test unload."""
client = create_mock_client()
await setup_test_config_entry(hass, hyperion_client=client)
assert hass.states.get(TEST_ENTITY_ID_1) is not None
assert client.async_client_connect.call_count == 2
assert not client.async_client_disconnect.called
entry = _get_config_entry_from_unique_id(hass, TEST_SYSINFO_ID)
assert entry
await hass.config_entries.async_unload(entry.entry_id)
assert client.async_client_disconnect.call_count == 2
async def test_version_log_warning(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant
) -> None:
"""Test warning on old version."""
client = create_mock_client()
client.async_sysinfo_version = AsyncMock(return_value="2.0.0-alpha.7")
await setup_test_config_entry(hass, hyperion_client=client)
assert hass.states.get(TEST_ENTITY_ID_1) is not None
assert "Please consider upgrading" in caplog.text
async def test_version_no_log_warning(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant
) -> None:
"""Test no warning on acceptable version."""
client = create_mock_client()
client.async_sysinfo_version = AsyncMock(return_value="2.0.0-alpha.9")
await setup_test_config_entry(hass, hyperion_client=client)
assert hass.states.get(TEST_ENTITY_ID_1) is not None
assert "Please consider upgrading" not in caplog.text
async def test_setup_entry_no_token_reauth(hass: HomeAssistant) -> None:
"""Verify a reauth flow when auth is required but no token provided."""
client = create_mock_client()
config_entry = add_test_config_entry(hass)
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with (
patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=client,
),
patch.object(hass.config_entries.flow, "async_init") as mock_flow_init,
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert client.async_client_disconnect.called
mock_flow_init.assert_called_once_with(
DOMAIN,
context={
CONF_SOURCE: SOURCE_REAUTH,
"entry_id": config_entry.entry_id,
"unique_id": config_entry.unique_id,
"title_placeholders": {"name": config_entry.title},
},
data=config_entry.data,
)
assert config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_setup_entry_bad_token_reauth(hass: HomeAssistant) -> None:
"""Verify a reauth flow when a bad token is provided."""
client = create_mock_client()
config_entry = add_test_config_entry(
hass,
data={CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_TOKEN: "expired_token"},
)
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_NOT_REQUIRED_RESP)
# Fail to log in.
client.async_client_login = AsyncMock(return_value=False)
with (
patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=client,
),
patch.object(hass.config_entries.flow, "async_init") as mock_flow_init,
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert client.async_client_disconnect.called
mock_flow_init.assert_called_once_with(
DOMAIN,
context={
CONF_SOURCE: SOURCE_REAUTH,
"entry_id": config_entry.entry_id,
"unique_id": config_entry.unique_id,
"title_placeholders": {"name": config_entry.title},
},
data=config_entry.data,
)
assert config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_light_option_effect_hide_list(hass: HomeAssistant) -> None:
"""Test the effect_hide_list option."""
client = create_mock_client()
client.effects = [{const.KEY_NAME: "One"}, {const.KEY_NAME: "Two"}]
await setup_test_config_entry(
hass,
hyperion_client=client,
options={CONF_EFFECT_HIDE_LIST: ["Two", "Three"]},
)
entity_state = hass.states.get(TEST_ENTITY_ID_1)
assert entity_state
assert entity_state.attributes["effect_list"] == [
"Solid",
"One",
]
async def test_device_info(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Verify device information includes expected details."""
client = create_mock_client()
await setup_test_config_entry(hass, hyperion_client=client)
device_id = get_hyperion_device_id(TEST_SYSINFO_ID, TEST_INSTANCE)
device = device_registry.async_get_device(identifiers={(DOMAIN, device_id)})
assert device
assert device.config_entries == {TEST_CONFIG_ENTRY_ID}
assert device.identifiers == {(DOMAIN, device_id)}
assert device.manufacturer == HYPERION_MANUFACTURER_NAME
assert device.model == HYPERION_MODEL_NAME
assert device.name == TEST_INSTANCE_1["friendly_name"]
entities_from_device = [
entry.entity_id
for entry in er.async_entries_for_device(entity_registry, device.id)
]
assert TEST_ENTITY_ID_1 in entities_from_device

View File

@@ -0,0 +1,179 @@
"""Tests for the Hyperion integration."""
from hyperion.const import (
KEY_ACTIVE,
KEY_COMPONENTID,
KEY_ORIGIN,
KEY_OWNER,
KEY_PRIORITY,
KEY_RGB,
KEY_VALUE,
KEY_VISIBLE,
)
from homeassistant.components.hyperion import get_hyperion_device_id
from homeassistant.components.hyperion.const import (
DOMAIN,
HYPERION_MANUFACTURER_NAME,
HYPERION_MODEL_NAME,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util import slugify
from . import (
TEST_CONFIG_ENTRY_ID,
TEST_INSTANCE,
TEST_INSTANCE_1,
TEST_SYSINFO_ID,
call_registered_callback,
create_mock_client,
setup_test_config_entry,
)
TEST_COMPONENTS = [
{"enabled": True, "name": "VISIBLE_PRIORITY"},
]
TEST_SENSOR_BASE_ENTITY_ID = "sensor.test_instance_1"
TEST_VISIBLE_EFFECT_SENSOR_ID = "sensor.test_instance_1_visible_priority"
async def test_sensor_has_correct_entities(hass: HomeAssistant) -> None:
"""Test that the correct sensor entities are created."""
client = create_mock_client()
client.components = TEST_COMPONENTS
await setup_test_config_entry(hass, hyperion_client=client)
for component in TEST_COMPONENTS:
name = slugify(component["name"])
entity_id = f"{TEST_SENSOR_BASE_ENTITY_ID}_{name}"
entity_state = hass.states.get(entity_id)
assert entity_state, f"Couldn't find entity: {entity_id}"
async def test_device_info(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Verify device information includes expected details."""
client = create_mock_client()
client.components = TEST_COMPONENTS
await setup_test_config_entry(hass, hyperion_client=client)
device_identifer = get_hyperion_device_id(TEST_SYSINFO_ID, TEST_INSTANCE)
device = device_registry.async_get_device(identifiers={(DOMAIN, device_identifer)})
assert device
assert device.config_entries == {TEST_CONFIG_ENTRY_ID}
assert device.identifiers == {(DOMAIN, device_identifer)}
assert device.manufacturer == HYPERION_MANUFACTURER_NAME
assert device.model == HYPERION_MODEL_NAME
assert device.name == TEST_INSTANCE_1["friendly_name"]
entities_from_device = [
entry.entity_id
for entry in er.async_entries_for_device(entity_registry, device.id)
]
for component in TEST_COMPONENTS:
name = slugify(component["name"])
entity_id = TEST_SENSOR_BASE_ENTITY_ID + "_" + name
assert entity_id in entities_from_device
async def test_visible_effect_state_changes(hass: HomeAssistant) -> None:
"""Verify that state changes are processed as expected for visible effect sensor."""
client = create_mock_client()
client.components = TEST_COMPONENTS
await setup_test_config_entry(hass, hyperion_client=client)
# Simulate a platform grabber effect state callback from Hyperion.
client.priorities = [
{
KEY_ACTIVE: True,
KEY_COMPONENTID: "GRABBER",
KEY_ORIGIN: "System",
KEY_OWNER: "X11",
KEY_PRIORITY: 250,
KEY_VISIBLE: True,
}
]
call_registered_callback(client, "priorities-update")
entity_state = hass.states.get(TEST_VISIBLE_EFFECT_SENSOR_ID)
assert entity_state
assert entity_state.state == client.priorities[0][KEY_OWNER]
assert (
entity_state.attributes["component_id"] == client.priorities[0][KEY_COMPONENTID]
)
assert entity_state.attributes["origin"] == client.priorities[0][KEY_ORIGIN]
assert entity_state.attributes["priority"] == client.priorities[0][KEY_PRIORITY]
# Simulate an effect state callback from Hyperion.
client.priorities = [
{
KEY_ACTIVE: True,
KEY_COMPONENTID: "EFFECT",
KEY_ORIGIN: "System",
KEY_OWNER: "Warm mood blobs",
KEY_PRIORITY: 250,
KEY_VISIBLE: True,
}
]
call_registered_callback(client, "priorities-update")
entity_state = hass.states.get(TEST_VISIBLE_EFFECT_SENSOR_ID)
assert entity_state
assert entity_state.state == client.priorities[0][KEY_OWNER]
assert (
entity_state.attributes["component_id"] == client.priorities[0][KEY_COMPONENTID]
)
assert entity_state.attributes["origin"] == client.priorities[0][KEY_ORIGIN]
assert entity_state.attributes["priority"] == client.priorities[0][KEY_PRIORITY]
# Simulate a USB Capture state callback from Hyperion.
client.priorities = [
{
KEY_ACTIVE: True,
KEY_COMPONENTID: "V4L",
KEY_ORIGIN: "System",
KEY_OWNER: "V4L2",
KEY_PRIORITY: 250,
KEY_VISIBLE: True,
}
]
call_registered_callback(client, "priorities-update")
entity_state = hass.states.get(TEST_VISIBLE_EFFECT_SENSOR_ID)
assert entity_state
assert entity_state.state == client.priorities[0][KEY_OWNER]
assert (
entity_state.attributes["component_id"] == client.priorities[0][KEY_COMPONENTID]
)
assert entity_state.attributes["origin"] == client.priorities[0][KEY_ORIGIN]
assert entity_state.attributes["priority"] == client.priorities[0][KEY_PRIORITY]
# Simulate a color effect state callback from Hyperion.
client.priorities = [
{
KEY_ACTIVE: True,
KEY_COMPONENTID: "COLOR",
KEY_ORIGIN: "System",
KEY_PRIORITY: 250,
KEY_VALUE: {KEY_RGB: [0, 0, 0]},
KEY_VISIBLE: True,
}
]
call_registered_callback(client, "priorities-update")
entity_state = hass.states.get(TEST_VISIBLE_EFFECT_SENSOR_ID)
assert entity_state
assert entity_state.state == str(client.priorities[0][KEY_VALUE][KEY_RGB])
assert (
entity_state.attributes["component_id"] == client.priorities[0][KEY_COMPONENTID]
)
assert entity_state.attributes["origin"] == client.priorities[0][KEY_ORIGIN]
assert entity_state.attributes["priority"] == client.priorities[0][KEY_PRIORITY]
assert entity_state.attributes["color"] == client.priorities[0][KEY_VALUE]

View File

@@ -0,0 +1,226 @@
"""Tests for the Hyperion integration."""
from datetime import timedelta
from unittest.mock import AsyncMock, call, patch
from hyperion.const import (
KEY_COMPONENT,
KEY_COMPONENTID_ALL,
KEY_COMPONENTID_TO_NAME,
KEY_COMPONENTSTATE,
KEY_STATE,
)
from homeassistant.components.hyperion import get_hyperion_device_id
from homeassistant.components.hyperion.const import (
DOMAIN,
HYPERION_MANUFACTURER_NAME,
HYPERION_MODEL_NAME,
TYPE_HYPERION_COMPONENT_SWITCH_BASE,
)
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.config_entries import RELOAD_AFTER_UPDATE_DELAY
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util import dt as dt_util, slugify
from . import (
TEST_CONFIG_ENTRY_ID,
TEST_INSTANCE,
TEST_INSTANCE_1,
TEST_SYSINFO_ID,
call_registered_callback,
create_mock_client,
register_test_entity,
setup_test_config_entry,
)
from tests.common import async_fire_time_changed
TEST_COMPONENTS = [
{"enabled": True, "name": "ALL"},
{"enabled": True, "name": "SMOOTHING"},
{"enabled": True, "name": "BLACKBORDER"},
{"enabled": False, "name": "FORWARDER"},
{"enabled": False, "name": "BOBLIGHTSERVER"},
{"enabled": False, "name": "GRABBER"},
{"enabled": False, "name": "V4L"},
{"enabled": True, "name": "LEDDEVICE"},
]
TEST_SWITCH_COMPONENT_BASE_ENTITY_ID = "switch.test_instance_1_component"
TEST_SWITCH_COMPONENT_ALL_ENTITY_ID = f"{TEST_SWITCH_COMPONENT_BASE_ENTITY_ID}_all"
async def test_switch_turn_on_off(hass: HomeAssistant) -> None:
"""Test turning the light on."""
client = create_mock_client()
client.async_send_set_component = AsyncMock(return_value=True)
client.components = TEST_COMPONENTS
# Setup component switch.
register_test_entity(
hass,
SWITCH_DOMAIN,
f"{TYPE_HYPERION_COMPONENT_SWITCH_BASE}_all",
TEST_SWITCH_COMPONENT_ALL_ENTITY_ID,
)
await setup_test_config_entry(hass, hyperion_client=client)
# Verify switch is on (as per TEST_COMPONENTS above).
entity_state = hass.states.get(TEST_SWITCH_COMPONENT_ALL_ENTITY_ID)
assert entity_state
assert entity_state.state == "on"
# Turn switch off.
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: TEST_SWITCH_COMPONENT_ALL_ENTITY_ID},
blocking=True,
)
# Verify correct parameters are passed to the library.
assert client.async_send_set_component.call_args == call(
**{KEY_COMPONENTSTATE: {KEY_COMPONENT: KEY_COMPONENTID_ALL, KEY_STATE: False}}
)
client.components[0] = {
"enabled": False,
"name": "ALL",
}
call_registered_callback(client, "components-update")
# Verify the switch turns off.
entity_state = hass.states.get(TEST_SWITCH_COMPONENT_ALL_ENTITY_ID)
assert entity_state
assert entity_state.state == "off"
# Turn switch on.
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: TEST_SWITCH_COMPONENT_ALL_ENTITY_ID},
blocking=True,
)
# Verify correct parameters are passed to the library.
assert client.async_send_set_component.call_args == call(
**{KEY_COMPONENTSTATE: {KEY_COMPONENT: KEY_COMPONENTID_ALL, KEY_STATE: True}}
)
client.components[0] = {
"enabled": True,
"name": "ALL",
}
call_registered_callback(client, "components-update")
# Verify the switch turns on.
entity_state = hass.states.get(TEST_SWITCH_COMPONENT_ALL_ENTITY_ID)
assert entity_state
assert entity_state.state == "on"
async def test_switch_has_correct_entities(hass: HomeAssistant) -> None:
"""Test that the correct switch entities are created."""
client = create_mock_client()
client.components = TEST_COMPONENTS
# Setup component switch.
for component in TEST_COMPONENTS:
name = slugify(KEY_COMPONENTID_TO_NAME[str(component["name"])])
register_test_entity(
hass,
SWITCH_DOMAIN,
f"{TYPE_HYPERION_COMPONENT_SWITCH_BASE}_{name}",
f"{TEST_SWITCH_COMPONENT_BASE_ENTITY_ID}_{name}",
)
await setup_test_config_entry(hass, hyperion_client=client)
for component in TEST_COMPONENTS:
name = slugify(KEY_COMPONENTID_TO_NAME[str(component["name"])])
entity_id = TEST_SWITCH_COMPONENT_BASE_ENTITY_ID + "_" + name
entity_state = hass.states.get(entity_id)
assert entity_state, f"Couldn't find entity: {entity_id}"
async def test_device_info(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Verify device information includes expected details."""
client = create_mock_client()
client.components = TEST_COMPONENTS
for component in TEST_COMPONENTS:
name = slugify(KEY_COMPONENTID_TO_NAME[str(component["name"])])
register_test_entity(
hass,
SWITCH_DOMAIN,
f"{TYPE_HYPERION_COMPONENT_SWITCH_BASE}_{name}",
f"{TEST_SWITCH_COMPONENT_BASE_ENTITY_ID}_{name}",
)
await setup_test_config_entry(hass, hyperion_client=client)
assert hass.states.get(TEST_SWITCH_COMPONENT_ALL_ENTITY_ID) is not None
device_identifer = get_hyperion_device_id(TEST_SYSINFO_ID, TEST_INSTANCE)
device = device_registry.async_get_device(identifiers={(DOMAIN, device_identifer)})
assert device
assert device.config_entries == {TEST_CONFIG_ENTRY_ID}
assert device.identifiers == {(DOMAIN, device_identifer)}
assert device.manufacturer == HYPERION_MANUFACTURER_NAME
assert device.model == HYPERION_MODEL_NAME
assert device.name == TEST_INSTANCE_1["friendly_name"]
entities_from_device = [
entry.entity_id
for entry in er.async_entries_for_device(entity_registry, device.id)
]
for component in TEST_COMPONENTS:
name = slugify(KEY_COMPONENTID_TO_NAME[str(component["name"])])
entity_id = TEST_SWITCH_COMPONENT_BASE_ENTITY_ID + "_" + name
assert entity_id in entities_from_device
async def test_switches_can_be_enabled(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Verify switches can be enabled."""
client = create_mock_client()
client.components = TEST_COMPONENTS
await setup_test_config_entry(hass, hyperion_client=client)
for component in TEST_COMPONENTS:
name = slugify(KEY_COMPONENTID_TO_NAME[str(component["name"])])
entity_id = TEST_SWITCH_COMPONENT_BASE_ENTITY_ID + "_" + name
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.disabled
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
entity_state = hass.states.get(entity_id)
assert not entity_state
with patch(
"homeassistant.components.hyperion.client.HyperionClient",
return_value=client,
):
updated_entry = entity_registry.async_update_entity(
entity_id, disabled_by=None
)
assert not updated_entry.disabled
await hass.async_block_till_done()
async_fire_time_changed(
hass,
dt_util.utcnow() + timedelta(seconds=RELOAD_AFTER_UPDATE_DELAY + 1),
)
await hass.async_block_till_done()
entity_state = hass.states.get(entity_id)
assert entity_state